MERGE批量增删查改数据

MERGE优点:

  在批量处理数据的时候,我可以用到merge一次完成数据处理。

示例代码一:

MERGE INTO student AS t
using (SELECT '丽水' AS NAME,20 AS age UNION ALL SELECT '王五' AS NAME ,21 AS age) s
ON t.Age=s.age
WHEN MATCHED
THEN UPDATE SET t.Name=s.NAME
WHEN NOT MATCHED 
THEN INSERT VALUES(s.NAME,s.age)
WHEN NOT MATCHED BY SOURCE 
THEN DELETE;

实例一output还可以返回增删查改的变化

 

示例二:

ALTER PROCEDURE pro_send
AS
BEGIN
    --查询需要发放
    DECLARE @ruleTabs TABLE
    (
        id INT ,
        phone NVARCHAR(12),
        tluxRuleId INT ,
        value INT ,
        ValidityTime INT
    )

    BEGIN TRANSACTION
    BEGIN TRY
        

        INSERT INTO @ruleTabs
                ( id, phone, tluxRuleId, value,ValidityTime )
        SELECT TOP 50 a.id,a.PhoneNo, b.TluxRuleID,c.Value,c.ValidityTime FROM dbo.hk_RaffleResult AS a
        LEFT JOIN dbo.hk_RaffleResultType AS b ON a.PrizeId=b.PrizeId
        LEFT JOIN dbo.hk_TluxRule AS c ON b.TluxRuleID=c.Id
        WHERE a.Status=1 AND a.IsAutoUse=1

        SELECT * FROM @ruleTabs

        --发放券
        MERGE INTO dbo.hk_Tlux AS t
        USING @ruleTabs AS s
        ON t.RaffleResultId=s.id
        WHEN NOT MATCHED THEN
        INSERT ( TluxNumber ,Status ,CreateTime ,ExpireTime ,
                 Type ,UserPhone ,UserType ,UserTime ,Remark ,
                 FlowNo ,StorePhone ,TluxRuleID ,RaffleResultId
                )
        VALUES( 
                 s.value,1,GETDATE(),DATEADD(DAY,s.ValidityTime-1,CONVERT(varchar(100), GETDATE(), 102)),
                 5,NULL,NULL,NULL,'',
                 NULL,s.phone,s.tluxRuleId,id);

        --修改发放状态
        UPDATE dbo.hk_RaffleResult SET Status=2 
        FROM  dbo.hk_RaffleResult AS a INNER JOIN @ruleTabs AS b ON a.id=b.id

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        ROLLBACK 
    END CATCH

END
GO

 

posted @ 2017-12-14 18:12  zhuyapeng  阅读(1244)  评论(0编辑  收藏  举报