sql-servervb.nett-sqlexecutenonquery

Executing INSERT from Identity column Output in VB.NET


Using VB.NET and SQL Server: I have a table [Item_List]. When I add a new item from a Windows form, I want to insert the record into the Item_List table, get the ItemID which is an IDENTITY, and use that to insert a corresponding record into the financial tracking [Inventory_Transactions] table.

I tested the following query directly in a T-SQL query window with success:

DECLARE @OutputTbl TABLE (ItemID INT);

INSERT INTO [Item_List] (Item_Name, Vendor, Quantity, Price, Category, Active, Notes, Created) 
OUTPUT INSERTED.ItemID INTO @OutputTbl(ItemID) 
VALUES ('Test Item', 'Walmart', 42, 4.22, 'Stuff', 1, '', CURRENT_TIMESTAMP);

INSERT INTO Inventory_Transactions (TransDate, Category, Transactee, Amount, Item, Quantity, Description) 
    SELECT 
        CURRENT_TIMESTAMP, 'Stuff', 'Walmart', -4.22, ItemID, 42, '';

However when I try to run using ExecuteNonQuery() I get an error

Invalid column name 'ItemID'

I've used the exact script from above and also below with parameters - same error.

Dim sql As String = "DECLARE @OutputTbl TABLE (ItemID INT); " &
                    "INSERT INTO [Item_List] (Item_Name, Vendor, Quantity, Price, Category, Active, Notes, Created) " &
                    "OUTPUT INSERTED.ItemID  INTO @OutputTbl(ItemID) " &
                    "VALUES (@ItemName, @Vendor, @Quantity, @Price, @Category, @Active, @Notes, CURRENT_TIMESTAMP); " &
                    "INSERT INTO Inventory_Transactions (TransDate, Category, Transactee, Amount, Item, Quantity, Description) " &
                    "SELECT CURRENT_TIMESTAMP, @Category, @Vendor, '-' + @Price, ItemID, @Quantity, @Notes;"

Using conn As New SqlConnection(My.Settings.dbConnectionString)
        Dim cmd As New SqlCommand(sql, conn)

        If Not IsNothing(params) Then
            For Each param In params
                cmd.Parameters.Add(param)
            Next
        End If

        If cmd.Connection.State <> ConnectionState.Open Then 
           cmd.Connection.Open()

        Dim rows As Integer = cmd.ExecuteNonQuery()
End Using

How can I implement this in VB?


Solution

  • I think this:

    "SELECT CURRENT_TIMESTAMP, @Category, @Vendor, '-' + @Price, ItemID, @Quantity, @Notes;"
    

    should be:

    "SELECT CURRENT_TIMESTAMP, @Category, @Vendor, '-' + @Price, ItemID, @Quantity, @Notes from @OutputTbl;"