SQL Server:在存储过程中检索自动递增的ID?

问题描述:

我的数据库有一个父表,该表具有自动递增的主键标识"ID"和一个普通的"TIMESTAMP列".我有带有外键的子表,这些子表引用父"ID"列.

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.

我想编写一个存储过程,将一个新列插入到父数据库和子数据库中.如何将子"ID"列设置为等于新的自动递增的父"ID"列?这是否需要一个单独的:

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

还是有另一种方法?

您可以从SCOPE_IDENTITY()中检索它.例如:

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

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