4

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?

Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
user1645334
  • 89
  • 1
  • 7

1 Answers1

2

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

hgulyan
  • 8,099
  • 8
  • 50
  • 75