MERGE Query and deleting records

前端 未结 4 1613
花落未央
花落未央 2021-01-01 09:02

I have a table that looks something like:

AccountID, ItemID
1, 100
1, 200
2, 300

I have a proc that accepts a table value parameter which u

4条回答
  •  滥情空心
    2021-01-01 09:54

    Create a table type variable in sql database

    CREATE TYPE [dbo].[YourTableType] AS TABLE(
         [AccountID] [int] NULL,
         [ItemID] [int] NULL
         )
       GO
    

    Make Changes in your Update Procedure

    ALTER PROCEDURE YourProcedure
    @Items YourTableType READONLY
    AS
    BEGIN
       MERGE INTO [dbo].[YourTable] as Target
       USING @Items as Source
    ON 
        Target.[AccountID]=Source.[AccountID] and 
        Target.[ItemID]=Source.[ItemID] 
       WHEN NOT MATCHED by TARGET THEN
         INSERT 
            ([AccountID],
             [ItemID])
         VALUES 
           (Source.[AccountID],
            Source.[ItemID])
    
       WHEN NOT MATCHED BY SOURCE AND 
            target.[ItemID] IN(SELECT [ItemID] FROM @Items) 
    THEN
        DELETE;
    

    END

提交回复
热议问题