MERGE批量增删查改数据

Posted zhuyapeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于MERGE批量增删查改数据的主要内容,如果未能解决你的问题,请参考以下文章

EF基本操作增删查改分页,join……等

基于MVC实现增删查改

基于MVC实现增删查改

php mysql增删查改

2016/3/13 MySQL 增删查改 CRUD 用代码实现

php怎么对文件内容进行增删查改?