SQL - 在WHERE中使用SELECT Alias

时间:2015-01-16 20:28:22

标签: sql sql-server alias

我有一段时间让这个查询起作用。基本上我需要做一个CASE语句来获取该人的NickName,如果他们有一个,否则使用他们的FirstName。然后在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'.

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

3 个答案:

答案 0 :(得分:2)

您可以使用公用表表达式或子查询将FName创建为新结果集的一种虚拟列。您可以将结果集用作一种虚拟表,并在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%'

答案 1 :(得分:1)

使用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%'

答案 2 :(得分:1)

您可以在没有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 + '%')