2010-10-13 56 views

回答

6

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

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

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

+2

从来没有在任何情况下使用ident_current这个,它不会返回正确的结果,如果你有多个用户!如果您的版本不支持输出子句,则输出是最佳选择或scope_identity()。 – HLGEM 2010-10-13 15:30:51

0

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

做你想做什么,

SELECT newid = @@identity FROM table 

只是INSERT

+0

@@身份是很危险的使用并不会可靠地返回正确的结果。你不应该为此使用它。 – HLGEM 2010-10-13 15:31:32

0

为什么你需要做的插入之前获得的标识值后?只需插入到Table2返回SCOPE_IDENTITY(),然后使用生成的Id值插入到Table1。

+0

因为我想为perf执行批量插入(不是逐行插入) – 2010-10-13 13:13:24

+1

在这种情况下,不,您不能这样做。您必须在每行插入后获取身份,如@smirkingman在其答案中所示。 – 2010-10-13 13:15:02

+0

@AJ:好的,谢谢 – 2010-10-13 13:16:58

2

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

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

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

-- 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)