如何在表上多次插入后从表中获取所有id

时间:2014-12-01 11:14:30

标签: sql asp.net

我将datatable作为输入参数传递给存储过程。我已经为它创建了自定义类型。 这是我的存储过程:

 INSERT INTO Employee
                ([Name],[Lname],[Code])
    SELECT [Name],[Lname],@Code
    FROM   @tblEmp A
    WHERE  NOT EXISTS (SELECT 1
                       FROM   Employee B
                       inner join Contactdetail c
                       on cid = B.cid
                       WHERE  B.[Name] = A.[Name]
                              AND B.[Lname] = A.[Lname]
                              AND C.[mobno] = A.[mobno]) 

这里我从datatable获取记录并插入Employee表。数据表包含Name,Lname和mobileno。我想检查Name,Lname和mobileno的组合。如果Employee表中存在它的组合,请不要在Employee.Else Insert.After插入记录后插入记录([Name],[Lname],@ Code)。从Employee,我想要所有插入记录的id.Scope_identity给出table的最后一个标识。我想要所有id,它们是新插入表中的,因为在同一个sp中,我想进一步处理。

2 个答案:

答案 0 :(得分:1)

您可以使用MERGE语句进行此操作。 (可能在这个查询中有一个错误,但它只是让你了解它背后的想法......)

MERGE INTO Employee AS Target
USING (SELECT B.[Name], B.[Lname], C.[mobno]
        FROM  Employee B
        inner join Contactdetail c
        on cid = B.cid ) AS source (Name, Lname, mobno)
ON   Target.[Name] = Source.[Name]
 AND Target.[Lname] = Source.[Lname]
 AND Target.[mobno] = Source.[mobno]
WHEN NOT MATCHED BY TARGET THEN
INSERT (Name, Lname, code) VALUES (Name, Lname, @Code);

答案 1 :(得分:1)

您可以使用Output子句,如:

DECLARE @InsertedIDs table(EmployeeID int);

INSERT INTO Employee
                ([Name],[Lname],[Code])
             --
             OUTPUT INSERTED.ID
             INTO @InsertedIDs 
             --
    SELECT [Name],[Lname],@Code
    FROM   @tblEmp A
    WHERE  NOT EXISTS (SELECT 1
                       FROM   Employee B
                       inner join Contactdetail c
                       on cid = B.cid
                       WHERE  B.[Name] = A.[Name]
                              AND B.[Lname] = A.[Lname]
                              AND C.[mobno] = A.[mobno]) 

[DEMO]