1

我制作了以下存储过程,将在创建新员工时调用。只要员工表中不存在员工,插入就应该成功。

为了检查这一点,我决定检查 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
4

2 回答 2

6

为什么你不只是为你的支票运行 1 个查询?

If Not Exists (Select 1 From Employee 
               Where FirstName = @FirstName 
                     and LastName = @LastName 
                     and DateOfBirth = @DateOfBirth)
    begin
        ...
于 2013-02-11T09:42:33.000 回答
0

这是另一种方式@@rowcount对于 sql server):使用Where not exists. 类似的 Sql Fiddle 演示

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!'
于 2013-02-11T10:15:52.327 回答