在表中插入数据之前,是否可以获取Id(IDENTITY)的新值?

在表中插入数据之前,是否可以获取Id(IDENTITY)的新值?

有可能写出类似的东西:

INSERT INTO Table1 SELECT *GET_NEW_IDENTITY*, Field1, Field2 FROM Table2 

我需要Id的值,因为我想在Table1中插入数据,然后, 在另一个表中插入数据,该表具有链接到Table1的外键 (带有Id)

IDENT_CURRENT 。 返回为指定表或视图生成的最后一个标识值。 生成的最后一个标识值可以用于任何会话和任何范围。

SCOPE_IDENTITY 。 返回插入同一范围内的标识列的最后一个标识值。 范围是一个模块:存储过程,触发器,函数或批处理。

OUTPUT 。 返回受INSERT,UPDATE,DELETE或MERGE语句影响的每一行的信息或表达式。 […]在INSERT或UPDATE操作之后,OUTPUT子句可用于检索标识或计算列的值。

您还可以让insert语句返回新插入的值以供以后使用。 例如

 create table demo( Id int identity primary key, data varchar(10)) go insert into demo(data) output inserted.Id values('something') 

不,因为它是添加一行创建新标识值的行为。

做你想做的事,

 SELECT newid = @@identity FROM table 

INSERT之后

为什么在插入之前需要获取标识值? 只需对Table2进行插入,返回SCOPE_IDENTITY() ,然后使用生成的Id值来插入Table1。

这只是快速演示。 您可以使用新ID进行插入以进行更新,以另一种方式插入另一个表,查询等。 希望我在格式化,编辑post时没有在脚本中插入错误

 -- run [1] before this script once to have environment --create temporary table once if not dropped after -- really only ID field is needed, the others are for illustration create table #temp_id (Id int, d1 int, d2 int) select * from Table2;-- this is read-only, filled once here source select * from Table1;--interesting for following runs insert into Table1 OUTPUT INSERTED.id -- really only ID is needed, the rest is for illustration , inserted.d1, inserted.d2 INTO #temp_id select field1, field2, null-- null to be merged later -- or inserted/updated into another table from Table2; select * from Table1; select * from #temp_id; MERGE Table1 AS TARGET USING #temp_id AS SOURCE ON (TARGET.id = SOURCE.id) WHEN MATCHED --AND OR are redundant if Table1.ID is PK THEN UPDATE SET TARGET.IDnew = SOURCE.id; select * from Table1; --drop table #temp_id --drop table table1 --drop table table2 

[1]
从问题中重现表并填充数据

 create table Table1( Id int identity primary key, d1 int, d2 int, IDnew int) create table Table2( field1 int, field2 int) insert into table2 values(111,222) insert into table2 values(333,444)