Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net sqlclient insert output

I have a ms sql table PRODUCTS. And it has three columns ID (int),NAME (nvarchar),TSTAMP (timestamp)

I want to get new inserted row's both id and timestamp (like multiple select scope_identity). I can achieve that in sql as following:

INSERT INTO PRODUCTS (NAME)
OUTPUT inserted.ID,inserted.TSTAMP
VALUES ('Example Product')

But how can i read it in vb.net with sqlclient.sqlcommad on insertation? Which function of sqlcommand do i have to use and how? ExecuteReader maybe?

like image 338
user1645334 Avatar asked Jan 21 '26 08:01

user1645334


1 Answers

Using the ExecuteReader() method of SqlCommand would work the same as with SELECT.

OUTPUT clause works like a SELECT statement but its usage differs in INSERT, UPDATE and DELETE commands

Here's a sample code. Try it.

Dim connString As String = "server=Test; database=Test;" + _
                           "uid=sa; pwd="
Dim conn As New SqlConnection(connString)

Dim cmdString As String = "INSERT INTO PRODUCTS (NAME) " + _
                          "OUTPUT inserted.ID,inserted.TSTAMP " + _
                          "VALUES ('Example Product')"
Dim cmd As New SqlCommand(cmdString, conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
conn.Close()

Here're some links

Running The OUTPUT Clause From C#

Implementing the OUTPUT Clause in SQL Server 2008

like image 79
hgulyan Avatar answered Jan 24 '26 08:01

hgulyan