INSERT INTO if not exists SQL server

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

I have a database structured as follows:

users

userid (Primary Key)
username

group



        
8条回答
  •  春和景丽
    2020-12-05 12:12

    @gbn answer needs SQL server 2008 or higher. I tried a non-merge way to do it. Ugly perhaps, but it works.

    declare @user varchar(50)
    set @user = 'username'
    insert into users (username) 
    select @user
    where not exists (
     select username 
     from users 
     where username = @user
    );
    

    If you want to test any of the answers, here is the SQL for the table -

    CREATE TABLE [dbo].[users](
        [userid] [int] NULL,
        [username] [varchar](50) NULL
    )
    
    INSERT [dbo].[users] ([userid], [username]) VALUES (1, N'John')
    INSERT [dbo].[users] ([userid], [username]) VALUES (2, N'David')
    INSERT [dbo].[users] ([userid], [username]) VALUES (3, N'Stacy')
    INSERT [dbo].[users] ([userid], [username]) VALUES (4, N'Arnold')
    INSERT [dbo].[users] ([userid], [username]) VALUES (5, N'Karen')
    

提交回复
热议问题