我要如何插入到表中,并取回主键值?(How do I insert into a table and

2019-08-03 06:58发布

我有一个主键设置为自动增量。

我做多个查询,我需要检索主键值作为另一个表(外键使用IsIdentity = TRUE )。

是否有任何优雅的方式,当我做插入查询以获取主键值? 现在我再次查询并获得在该列,这似乎真的哈克的最高值。

有什么建议?

Answer 1:

insert into YourTable values (...)

得到与SCOPE_IDENTITY新的PK()

select scope_identity()


Answer 2:

如果您使用的是SQL Server 2005或更高版本,可以使用OUTPUT子句。

create table T(
  pk int identity primary key,
  dat varchar(20)
);
go

insert into T
output inserted.pk
values ('new item');
go

drop table T;

输出可以被引导到一个表以及到客户端。 例如:

create table T(
  pk int identity primary key,
  dat varchar(20)
);

create table U(
  i int identity(1001,1) primary key,
  T_pk int not null,
  d datetime
);
go


insert into T
output inserted.pk, getdate()
into U(T_pk,d)
values ('new item'), ('newer item');
go

select * from T;
select * from U;
go

drop table T, U;

与SQL Server 2008开始,您可以使用“组合的DML”为更多的可能性。



Answer 3:

INSERT INTO YourTable (1, 2, etc.)
OUTPUT inserted.yourIDcolumn
VALUES (value1, value2, value...)

注:这是MS SQL 2005和更高



Answer 4:

SCOPE_IDENTITY()可能是你想要的。 它返回由它执行相同的代码上下文插入的最后记录的ID。

IDENT_CURRENT(“表名”)受并发问题。 也就是说,有没有保证,另一个记录不会INSERT和调用IDENT_CURRENT之间插入。

我必须承认,我不知道到VillageIdiot的爆发是指什么惊奇的来源,但我本人很惊讶,这个问题似乎并没有是重复的。



Answer 5:

哇靠!!!

只需调用SCOPE_IDENTITY()函数:

insert into your_talble(col1,col2) values('blah','more blah')
select scope_identity()

因为如果任何其他语句使插入选择最高值将返回错误。 函数scope_identity()返回在当前环境中创建的身份(即是你的发言)



Answer 6:

您应该使用SCOPE_IDENTITY()。 我建议换行INSERT语句和SCOPE_IDENTITY()进入交易。



文章来源: How do I insert into a table and get back the primary key value?