INSERT INTO if not exists SQL server

前端 未结 8 513
无人共我
无人共我 2020-12-05 11:45

I have a database structured as follows:

users

userid (Primary Key)
username

group



        
8条回答
  •  情深已故
    2020-12-05 12:14

    There is a simple solution! I Found it in this post!

    INSERT INTO users (Username) 
    SELECT ('username')
    WHERE NOT EXISTS(SELECT * FROM users WHERE Username= 'username')
    

    In my project I needed to do it with 2 values. So my code was:

    INSERT INTO MyTable (ColName1, ColName2) 
    SELECT 'Value1','Value2' 
    WHERE NOT EXISTS
    (SELECT * FROM MyTable WHERE ColName1 = 'Value1' AND ColName2= 'Value2')
    

    Hope this helps!

提交回复
热议问题