SQL - 在 WHERE 中使用 SELECT 别名

SQL - using SELECT Alias in WHERE

我很难让这个查询正常工作。基本上我需要做一个 CASE 语句来获取此人的昵称(如果有的话),否则使用他们的名字。然后在 WHERE 语句中,对上面的 CASE 语句执行 LIKE 语句。

如果我 执行 FirstName/NickName 我已经能够让它工作,但是当我添加其他列时它停止工作。

这是我得到的

SELECT
    LastName
  , Company
  , Status
  , CASE
      WHEN NickName = '' THEN FirstName
      WHEN NickName IS NULL THEN FirstName
      ELSE NickName
    END AS FName
FROM database
WHERE
       Status = 'Active'
  AND  Company = '@Company'
  AND  FName + ' ' + LastName LIKE '%@search%'
  OR   LastName + ', ' + FName LIKE '%@search%'

显然上面的方法不起作用,因为我试图在我的 WHERE 子句中使用别名。我得到

Msg 207, Level 16, State 1, Line 14
Invalid column name 'FName'.
Msg 207, Level 16, State 1, Line 15
Invalid column name 'FName'.

非常感谢任何帮助。谢谢!

您可以使用通用 Table 表达式或子查询将 FName 创建为新结果集的一种虚拟列。您可以将结果集用作一种虚拟 table 并在 where 子句中对其进行过滤。

SELECT *
FROM (
  SELECT
    LastName
    , Company
    , Status
    , CASE
        WHEN NickName IS NULL OR NickName = '' THEN FirstName
        ELSE NickName
      END AS FName
  FROM database
  WHERE Status = 'Active'
  AND  Company = '@Company'
) FNames
WHERE FName + ' ' + LastName LIKE '%@search%'
   OR LastName + ', ' + FName LIKE '%@search%'

使用CROSS APPLY创建别名

SELECT LastName
     , Company
     , Status
     , FName
FROM database
     CROSS APPLY (
         SELECT CASE WHEN NickName = '' THEN FirstName
                     WHEN NickName IS NULL THEN FirstName
                     ELSE NickName
                END AS FName
     ) AS CA1
WHERE Status = 'Active'
      AND  Company = '@Company'
      AND  FName + ' ' + LastName LIKE '%@search%'
      OR   LastName + ', ' + FName LIKE '%@search%'

你可以不用 CASE 语句

SELECT *
FROM (
    SELECT
        LastName
      , Company
      , Status
      , ISNULL(NULLIF(NickName, ''), FirstName) AS FName
    FROM database
    WHERE Status = 'Active'
      AND Company = '@Company') data
WHERE (FName + ' ' + LastName LIKE '%' + @search + '%')
   OR (LastName + ', ' + FName LIKE '%' + @search + '%')