Fast upsert Sql server 2008 R2

前端 未结 2 569
忘掉有多难
忘掉有多难 2021-01-04 01:25

I\'m trying to upsert records using SP into one table.

CREATE TABLE [dbo].[SHARE_AD_GROUP](
    [SHARE_AD_GROUP_ID] [int] IDENTITY(1,1) NOT NULL,
    [SHARE_         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-04 02:00

    I'm pretty sure you've already figured this out. But someone might find it useful.

    ALTER PROCEDURE [dbo].[PROC_INSERT_SHARE_AD_GROUP]
        @shareID int,
        @ownerId varchar(200),
        @sharePermissions varchar(65)
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
    
        MERGE [dbo].SHARE_AD_GROUP AS T
        USING
        (
            SELECT @shareID,@ownerId,@sharePermissions
        ) AS S
        (
            SELECT Share_ID,AD_Group,Share_Permissions
        )
        ON (T.SHARE_ID = S.Share_ID and T.AD_GROUP = S.AD_Group)
    
        WHEN MATCHED THEN
            UPDATE SET SHARE_PERMISSIONS = S.Share_Permissions
    
        WHEN NOT MATCHED THEN
            INSERT
                (SHARE_ID,AD_GROUP,SHARE_PERMISSIONS)
            VALUES
                (S.Share_ID,S.AD_Group,S.Share_Permissions)
        ;
    END
    

提交回复
热议问题