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

 

转载于:https://www.cnblogs.com/zhuyapeng/p/8039121.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值