SQL Server: Retrieve auto-incremented ID inside a stored procedure?

主宰稳场 提交于 2020-01-03 18:02:27

问题


My database has a parent table with an auto-incrementing primary key identity 'ID', and a normal 'TIMESTAMP column'. I have child tables with a foreign key that refer to the parent 'ID' column.

I want to write a stored procedure that inserts a new column into both the parent and child databases. How would I set the child 'ID' column to equal the new auto-incremented parent 'ID' column? Does this require a separate:

SELECT TOP 1 * FROM PARENT_TABLE

Or is there another way?


回答1:


You can retrieve it from SCOPE_IDENITY(). For example:

declare @myid int
INSERT INTO table (field) VALUES ('value')
SELECT @myid = SCOPE_IDENTITY()



回答2:


select scope_identity();



来源:https://stackoverflow.com/questions/831810/sql-server-retrieve-auto-incremented-id-inside-a-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!