什么是最好的使用方式不存在和插入?

时间:2015-11-06 05:15:36

标签: sql-server stored-procedures exists

我正在创建一个存储过程来检查用户名是否存在,如果不存在则插入到用户表中,然后获取相同用户名的userid。这就是我的尝试

ifelse

当我尝试执行时,表示零行受影响。问题是什么

alter Procedure Check_Name
 (
 --@idn integer,
@username varchar(25),
@password varchar(100)
--@role_id integer
)
As
Begin
INSERT INTO [user] (username,[password]) 
 SELECT username,[password]
 FROM [user] AS u
WHERE NOT EXISTS( 
SELECT idn FROM [user] AS t
WHERE u.username = t.username); 
End

1 个答案:

答案 0 :(得分:1)

您可以这样做: IF NOT EXISTS(SELECT 1 FROM [user] AS t WHERE t.username = @username) BEGIN INSERT INTO [user] (username,[password]) VALUES (@username, @password) END