Fast upsert Sql server 2008 R2

前端 未结 2 568
忘掉有多难
忘掉有多难 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 01:56

    I think merge statement is faster then what you demonstrate in your 2 ways. if you need to know more about how to write MERGE INTO Query in sql server then please follow the links..

    http://blog.sqlauthority.com/2008/08/28/sql-server-2008-introduction-to-merge-statement-one-statement-for-insert-update-delete/

    https://www.simple-talk.com/sql/learn-sql-server/the-merge-statement-in-sql-server-2008/

    and your merge block looks like this, you need to put that in your store procedure or any other places.

    MERGE INTO SHARE_AD_GROUP A
    USING (
        SELECT SHARE_AD_GROUP_ID,
            SHARE_ID,
            AD_GROUP,
            SHARE_PERMISSIONS
        FROM SHARE_AD_GROUP
        WHERE SHARE_ID = @shareID AND AD_GROUP = @ownerId
    ) B ON (A.SHARE_AD_GROUP_ID = B.SHARE_AD_GROUP_ID)
    WHEN MATCHED THEN
        UPDATE SET A.SHARE_PERMISSIONS = B.SHARE_PERMISSIONS
    WHEN NOT MATCHED THEN
        INSERT (SHARE_PERMISSIONS) VALUES(@sharePermissions);
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题