Only inserting a row if it's not already there

后端 未结 6 1017
天涯浪人
天涯浪人 2020-11-22 01:17

I had always used something similar to the following to achieve it:

INSERT INTO TheTable
SELECT
    @primaryKey,
    @value1,
    @value2
WHERE
    NOT EXIST         


        
6条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 02:01

    Firstly, huge shout out to our man @gbn for his contributions to the community. Can't even begin to explain how often I find myself following his advice.

    Anyway, enough fanboy-ing.

    To add slightly to his answer, perhaps "enhance" it. For those, like me, left feeling unsettled with what to do in the <> 2627 scenario (and no an empty CATCH is not an option). I found this little nugget from technet.

        BEGIN TRY
           INSERT etc
        END TRY
        BEGIN CATCH
            IF ERROR_NUMBER() <> 2627
              BEGIN
                    DECLARE @ErrorMessage NVARCHAR(4000);
                    DECLARE @ErrorSeverity INT;
                    DECLARE @ErrorState INT;
    
                    SELECT @ErrorMessage = ERROR_MESSAGE(),
                    @ErrorSeverity = ERROR_SEVERITY(),
                    @ErrorState = ERROR_STATE();
    
                        RAISERROR (
                            @ErrorMessage,
                            @ErrorSeverity,
                            @ErrorState
                        );
              END
        END CATCH
    

提交回复
热议问题