SQL - Inserting a row and returning primary key

前端 未结 8 1172
南笙
南笙 2020-12-01 18:07

I have a little witty problem. Say, I inserted a row with some data in a table where a primary key is present. How would one \"SELECT\" the primary key of the row one just i

8条回答
  •  不知归路
    2020-12-01 18:15

    If you need to retrieve the new index in MS SQL when there are triggers on the table then you have to use a little workaround. A simple OUTPUT will not work. You have to do something like this (in VB.NET):

    DECLARE @newKeyTbl TABLE (newKey INT);
    INSERT INTO myDbName(myFieldName) OUTPUT INSERTED.myKeyName INTO @newKeyTbl VALUES('myValue'); " & _
    SELECT newKey FROM @newKeyTbl;"
    

    If using .NET, then the return value from this query can be directly cast to an integer (you have to call "ExecuteScalar" on the .NET SqlCommand to get the return).

提交回复
热议问题