SQL - 如果陈述似乎忽略'AND'

问题描述:

我做了以下存储过程,将在创建新员工时调用。 只要员工不存在于Employee表中,插入应该是成功的。SQL - 如果陈述似乎忽略'AND'

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

@bonCodigo:你为什么要添加mysql标记?在这个问题中,我看不到任何对mysql的引用。这是MySQL或SQL服务器? – Kaf 2013-02-11 10:23:41

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

If Not Exists (Select 1 From Employee 
       Where FirstName = @FirstName 
        and LastName = @LastName 
        and DateOfBirth = @DateOfBirth) 
    begin 
     ... 
+0

嗯。这是...好多了:/ 非常感谢! – Corgalas 2013-02-11 09:49:44

+0

@Corgalas没问题。很高兴我能帮上忙。 – 2013-02-11 09:54:01

这是另一种@@rowcount对于SQL Server):使用Where not existsSimilar 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!'