在Where子句中,添加检查参数是否为空字符串

时间:2015-01-09 11:28:57

标签: sql select conditional-statements sql-server-2014

我必须在SQL中编写查询,该查询将返回帐户ID。

对于此查询,我有输入参数,可以为空。

在数据库中,这里是某些字段为空或空的行。因此,如果参数为空,我还需要检查字段是否为空。

SELECT a.Account_ID   
    FROM Accounts a
    WHERE a.FirstName = @FirstName /*Add check if @FirstName = '' then a.FirstName IS NULL */ 
        AND a.LastName = @LastName 
        AND a.Middle = @MiddleName
        AND a.Email = @Email 
        AND a.Company = @Company

5 个答案:

答案 0 :(得分:1)

我认为这是您需要的条件:

SELECT a.Account_ID   
    FROM Accounts a
    WHERE ((@FirstName='' and a.FirstName is null) or a.FirstName = @FirstName) /*Add check if @FirstName = '' then a.FirstName IS NULL */ 
        AND a.LastName = @LastName 
        AND a.Middle = @MiddleName
        AND a.Email = @Email 
        AND a.Company = @Company

答案 1 :(得分:0)

如果我想要空行参数的特殊行为,我通常会这样做:

SELECT a.Account_ID   
FROM Accounts a
WHERE 
 (
     (@firstname != '' AND a.FirstName = @FirstName) 
     OR (@firstname = '' AND a.FirstName is null)
 )
 AND a.LastName = @LastName AND a.Middle = @MiddleName
 AND a.Email = @Email AND a.Company = @Company

我有一个括号内的OR来处理param =''和param!=''的情况。

答案 2 :(得分:0)

不确定我是否理解这个问题,但这有帮助吗?

SELECT a.Account_ID   
FROM Accounts a
WHERE ISNULL(a.FirstName,'') = @FirstName 
    AND a.LastName = @LastName 
    AND a.Middle = @MiddleName
    AND a.Email = @Email 
    AND a.Company = @Company

答案 3 :(得分:0)

试试这个:

SELECT a.Account_ID   
FROM Accounts a
WHERE 1 = (CASE WHEN @FirstName != '' AND a.FirstName = @FirstName THEN 1 
                WHEN @FirstName = '' AND a.FirstName IS NULL THEN 1 
                ELSE 0 
           END) AND 
      a.LastName = @LastName AND 
      a.Middle = @MiddleName AND 
      a.Email = @Email AND 
      a.Company = @Company

答案 4 :(得分:0)

case子句也可以在where条件中使用,如在所选字段列表中那样:

SELECT a.Account_ID   
    FROM Accounts a
    WHERE case when @FirstName = '' then a.FirstName = @FirstName 
               else a.FirstName IS NULL 
          end
      AND a.LastName = @LastName 
      AND a.Middle = @MiddleName
      AND a.Email = @Email 
      AND a.Company = @Company