感谢大家的反馈
大家好,
我正在尝试创建一个存储过程,在两个不同的表中执行两次插入。
DECLARE @New_Group1_Id
DECLARE @New_Group2_Id
INSERT INTO Group1
(Group1_Desc)
VALUES (N'Indianapolis')
SELECT @New_Group1_Id = Scope_Identity()
INSERT INTO Group2
(Group2_Desc)
VALUES (N'Indianapolis')
SELECT @New_Group2_Id = Scope_Identity()
结果显示Ids的1和2而不是1和1(如果这些是有史以来第一个插入表中的记录)
有没有办法获取每个insert语句的IDENTITY值?我尝试过使用Scope_Identity()但结果 谢谢,
答案 0 :(得分:3)
您可能删除了其中一个表中的行,而是截断表(这将重置标识)并重试或重新设置表DBCC CHECKIDENT (Group1, RESEED, 0);
此处运行此操作以验证其是否按预期工作
Create table Group1(id int identity,Group1_Desc nvarchar(100))
create table Group2(id int identity,Group2_Desc nvarchar(100))
DECLARE @New_Group1_Id int
DECLARE @New_Group2_Id int
INSERT INTO Group1(Group1_Desc)
VALUES (N'Indianapolis')
SELECT @New_Group1_Id = Scope_Identity()
INSERT INTO Group2 (Group2_Desc)
VALUES (N'Indianapolis')
SELECT @New_Group2_Id = Scope_Identity()
select @New_Group1_Id,@New_Group2_Id
现在这样做
delete Group1
现在再次运行
DECLARE @New_Group1_Id int
DECLARE @New_Group2_Id int
INSERT INTO Group1(Group1_Desc)
VALUES (N'Indianapolis')
SELECT @New_Group1_Id = Scope_Identity()
INSERT INTO Group2 (Group2_Desc)
VALUES (N'Indianapolis')
SELECT @New_Group2_Id = Scope_Identity()
select @New_Group1_Id,@New_Group2_Id
你会发现两者都是2
现在截断表group1
truncate table Group1
再次运行,你将得到1和3
DECLARE @New_Group1_Id int
DECLARE @New_Group2_Id int
INSERT INTO Group1(Group1_Desc)
VALUES (N'Indianapolis')
SELECT @New_Group1_Id = Scope_Identity()
INSERT INTO Group2 (Group2_Desc)
VALUES (N'Indianapolis')
SELECT @New_Group2_Id = Scope_Identity()
select @New_Group1_Id,@New_Group2_Id