在SQLServer/MySQL数据库中如何取得刚插入的标识值 在SQLServer数据库中
数据库实际应用中,我们往往需要得到刚刚插入 的标志值来往相关表中写入数据。但我们平常得到的真的是我们需要的那个值么?
(1)、有时我们会使用 SELECT @@Identity 来获得我们刚刚插入的值,比如下面的代码
代码一:
use tempdb
if exists (select * from sys.objects where object_id = object_id(N'[test1]') and type in (N'u'))
drop table [test1]
go
create table test1
(
id int identity(1,1),
content nvarchar(100)
)
insert into test1 (content) values ('solorez')
select @@identity
乐观情况下,这样做是没问题的,但如果我们如果先运行下面的代码二创建一个触发器、再运行代码三:
代码二:
create table test2
(
id int identity(100,1),
content nvarchar(100)
)
create trigger tri_test1_identitytest_I
on test1 after insert
as
begin
insert into test2
select content from inserted
end
代码三:
insert into test1 (content) values ('solorez2')
select @@identity