Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO if not exists SQL server

I have a database structured as follows:

users

userid (Primary Key)
username

group

groupid (PK)
groupName

user_groups

userid (Foreign Key)
groupid (Foreign Key)

The first time a user logs in I would like their info to be added to the users table. So essentially the logic I would like to have if

if (//users table does not contain username)
{
INSERT INTO users VALUES (username);
}

How can I do this intelligently using SQL Server/C# ?

like image 436
Simon Kiely Avatar asked Mar 10 '12 18:03

Simon Kiely


People also ask

How do you use if not exists SQL?

NOT EXISTS is used with a subquery in the WHERE clause to check if the result of the subquery returns TRUE or FALSE. The Boolean value is then used to narrow down the rows from the outer select statement.

Which command insert rows that do not exist and update the rows that exist?

Using INSERT IGNORE This means that an INSERT IGNORE statement which contains a duplicate value in a UNIQUE index or PRIMARY KEY field does not produce an error, but will instead simply ignore that particular INSERT command entirely.


1 Answers

Or using the new MERGE syntax:

merge into users u
using ( 
   select 'username' as uname
) t on t.uname = u.username
when not matched then 
  insert (username) values (t.uname);
like image 192
a_horse_with_no_name Avatar answered Sep 30 '22 17:09

a_horse_with_no_name