Skip to content
Advertisement

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# ?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement