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

In Where clause add check if Parameter is empty string

我必须在 SQL 中编写查询,这将 return 帐户 ID。

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

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

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

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

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 != '' 的情况。

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

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

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

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

试试这个:

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

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