Only inserting a row if it's not already there

后端 未结 6 979
天涯浪人
天涯浪人 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 01:52

    I've done a similar operation in past using a different method. First, I declare a variable to hold the primary key. Then I populate that variable with the output of a select statement which looks for a record with those values. Then I do and IF statement. If primary key is null, then do insert, else, return some error code.

         DECLARE @existing varchar(10)
        SET @existing = (SELECT primaryKey FROM TABLE WHERE param1field = @param1 AND param2field = @param2)
    
        IF @existing is not null
        BEGIN
        INSERT INTO Table(param1Field, param2Field) VALUES(param1, param2)
        END
        ELSE
        Return 0
    END
    

提交回复
热议问题