我创建了以下存储过程,在创建新员工时将调用该过程。 只要员工在Employee表中不存在,插入就应该成功。
为了检查这一点,我决定检查FirstName,LastName和DateOfBirth。如果一行包含所有这些列的3路匹配,则插入失败。
我所看到的是,If语句将我的AND视为OR。 如果发生一次匹配,则插入失败。
经过一番搜索,我无法看到我的If结构出了什么问题。 任何帮助将不胜感激。
Create Procedure CreateEmployee
(
@Role_ID Int,
@FirstName Varchar(50),
@LastName Varchar(50),
@DateOfBirth Varchar(50),
@Active Bit
)
As
Begin
If Not Exists (Select FirstName From Employee Where FirstName = @FirstName)
AND Not Exists (Select LastName From Employee Where LastName = @LastName)
AND Not Exists (Select DateOfBirth From Employee Where DateOfBirth = @DateOfBirth)
Begin
Insert Into Employee (Role_ID, FirstName, LastName, DateOfBirth, Active)
Values (@Role_ID, @FirstName, @LastName, @DateOfBirth, @Active)
End
Else
Begin
Select 'User already exists!'
End
End
答案 0 :(得分:6)
为什么你不只是为你的支票运行1个查询?
If Not Exists (Select 1 From Employee
Where FirstName = @FirstName
and LastName = @LastName
and DateOfBirth = @DateOfBirth)
begin
...
答案 1 :(得分:0)
这是(sql server的@@rowcount
)的另一种方式:使用Where not exists
。 Similar Sql Fiddle Demo
Insert Into Employee (Role_ID, FirstName, LastName, DateOfBirth, Active)
Select @Role_ID, @FirstName, @LastName, @DateOfBirth, @Active
Where not exists (
select 1 from Employee where FirstName = @FirstName
and LastName = @LastName
and DateOfBirth = @DateOfBirth
)
If @@rowcount=0 select 'User already exists!'