码迷,mamicode.com
首页 > 其他好文 > 详细

MERGE批量增删查改数据

时间:2017-12-14 19:27:38      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:number   var   批量   增删查改   convert   put   from   col   nvarchar   

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

 

MERGE批量增删查改数据

标签:number   var   批量   增删查改   convert   put   from   col   nvarchar   

原文地址:http://www.cnblogs.com/zhuyapeng/p/8039121.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!