表中的scope_identity()和scope_identity()之间的性能差异?

时间:2012-10-10 06:03:00

标签: sql sql-server performance

我有一张表说scope_test如下:

create table scope_test
(
id int identity(1,1),
val varchar(100)
)

现在当我在这个表中插入一行并通过2个不同的sql语句选择范围标识时,我会看到2个语句的性能差异:

insert into scope_test values('abcd')
select scope_identity() -- statement 1
select scope_identity() from scope_test -- statement 2

根据执行计划,语句1比语句2快:

enter image description here

我很高兴知道: 1.为什么这种性能差异,以及 2.使用声明1中使用的范围标识()是否安全,即没有表名?

1 个答案:

答案 0 :(得分:4)

性能上的差异仅仅是因为你做了不同的事情。 scope_identity的第二次使用不只是获取最后一个标识,它获取表中的所有记录,并为表中的每个记录选择scope_identity()的值。对于表中存在的每条记录,您只需从scope_identity()获取一次值。

因此,scope_identity()的第二次使用毫无意义,它将返回相同的值一次或多次(如果查询中使用的表为空,则返回零次)。 scope_identity()的值与您在查询中使用的表完全没有关系,即如果您在不同的表中插入记录,则无法使用它来获取在特定表中插入的最后一个ID。

相关问题