如何使用合并查询在不同的表中插入

时间:2016-09-30 09:58:29

标签: sql sql-server stored-procedures

这里我尝试使用存储过程添加批量数据 但问题是我不想更新数据我想在条件匹配时将数据插入临时表

 Alter PROCEDURE [dbo].[Update_Customers] 
     @typeMembership aspnet_Membership_type READONLY
    AS
    BEGIN
          SET NOCOUNT ON;

          MERGE INTO aspnet_Membership c1
          USING @typeMembership c2
          ON c1.EmployeeCode=c2.EmployeeCode
          WHEN MATCHED THEN
          UPDATE SET  
          c1.[EmployeeCode] =  c2.[EmployeeCode] ,
          c1.[EmployeeTypeId] = c2.[EmployeeTypeId] ,
          c1.[FirstName] = c2.[FirstName] ,
          c1.[LastName] =  c2.[LastName] ,
          c1.[Gender] =  c2.[Gender] ,
          c1.[Email] =  c2.[Email]  ,
          c1.[MobilePIN] = c2.[MobilePIN] ,
          c1.[Current_Address] =  c2.[Current_Address] ,
          c1.[Permanent_Address] =  c2.[Permanent_Address] ,
          c1.[IsApproved] = c2.[IsApproved]  
          WHEN NOT MATCHED THEN
          INSERT VALUES (c2.EmployeeCode, c2.EmployeeTypeId,c2.FirstName,c2.LastName,c2.Gender,c2.Email,c2.MobilePIN,c2.Current_Address, c2.Permanent_Address,c2.IsApproved);
    END

1 个答案:

答案 0 :(得分:0)

AFAIK你无法通过合并来做到这一点。您必须编写不同的插入语句:

BEGIN TRY
BEGIN TRANSACTION

INSERT INTO thirdTable (<ColumnsList>)
SELECT <ValuesList>
FROM @typeMembership c2
WHERE EXISTS
(
    SELECT 1
    FROM aspnet_Membership c1
    WHERE c1.EmployeeCode = c2.EmployeeCode
);

INSERT INTO aspnet_Membership (<ColumnsList>)
SELECT <ValuesList>
FROM @typeMembership c2
WHERE NOT EXISTS
(
    SELECT 1
    FROM aspnet_Membership c1
    WHERE c1.EmployeeCode = c2.EmployeeCode
);

COMMIT TRANSACTION
END TRY
BEGIN CATCH
    IF @@Trancount > 0
        ROLLBACK TRANSACTION
END CATCH