I have a database structured as follows:
users
userid (Primary Key)
username
group
@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')