获取多个插入的Scope_identity

时间:2015-01-29 13:15:53

标签: sql sql-server

For table1 Inserted 3 records

它应该获得这三个身份,它应该在表3中插入3个记录(但它没有发生 - 它插入3个具有相同身份的记录,即.last范围标识)

 create table table1(ID INT identity(1,1),Name varchar(50))
    insert into table1 values('Ram'),('Sitha'),('Laxman')
    create table table1(ID INT identity(1,1),Name varchar(50))
    create table table3(ID INT ,Name varchar(50))

    insert into table2(Name)
    select Name from table1
        declare @id int;
        set @id= (select scope_Identity())
    begin
    insert into table3(ID,Name)
    select @id,Name from table2
    end

    select * from table2
    select * from table3

如何获取插入的所有身份我是否需要编写循环(或)我是否需要创建触发器。

请给我一个解决方案,我正在努力解决过去4个小时。

感谢anvance

3 个答案:

答案 0 :(得分:1)

您可以使用OUTPUT子句从任意数量的插入中获取标识。

create table table1(ID INT identity(1,1),Name varchar(50))
DECLARE @T1 Table (ID int, name varchar(50))
insert into table1 
    OUTPUT inserted.ID, Inserted.Name INTO @T1
    values('Ram'),('Sitha'),('Laxman')

答案 1 :(得分:1)

使用OUTPUT子句处理多行插入:

INSERT INTO dbo.table2(Name)
OUTPUT inserted.ID, inserted.Name INTO table3
SELECT Name FROM dbo.table1;

答案 2 :(得分:-1)

DECLARE @IdentityId INT,@Count INT=1
    DECLARE  @temp AS TABLE (Id INT IDENTITY ,Name NVARCHAR(100))

   INSERT INTO @temp(Name)
   SELECT Name FROM table1

   WHILE @Count <=(SELECT COUNT(SId) FROM @temp)
   BEGIN
     INSERT INTO table2(Name)
    SELECT Name FROM @temp
        WHERE Id=@Count

        SET @IdentityId  = SCOPE_IDENTITY()

        INSERT INTO tabel3(@IdentityId,Name)
        SELECT 3, @IdentityId,1,GETDATE() 
        SET @Count=@Count+1
   END
相关问题