18

I'm using SqlServer 2005 and I have a column that I named.

The query is something like:

SELECT id, CASE WHEN <snip extensive column definition> END AS myAlias
FROM myTable
WHERE myAlias IS NOT NULL

However, this gives me the error:

"Invalid column name 'myAlias'."

Is there a way to get around this? In the past I've included the column definition in either the WHERE or the HAVING section, but those were mostly simple, IE COUNT(*) or whatever. I can include the whole column definition in this ad-hoc query, but if for some reason I needed to do this in a production query I'd prefer to have the column definition only once so I don't have to update both (and forget to do one at some point)

4

5 に答える 5

16

そのような where 句でエイリアスを参照することはできません... WHERE で CASE を複製するか、次のようなサブクエリを使用する必要があります。

SELECT id, myAlias
FROM
(
    SELECT id, CASE WHEN <snip extensive column definition> END AS myAlias
    FROM myTable
) data
WHERE myAlias IS NOT NULL
于 2010-02-22T15:02:15.933 に答える
6

CTE を使用することもオプションです。

;with cte (id, myAlias)
 as (select id, case when <snip extensive column definition> end as myAlias 
      from myTable)
 select id, myAlias
  from cte
  where myAlias is not null
于 2010-02-22T15:14:15.313 に答える
4

同じCASEステートメントをWHERE句に入れます。

SELECT id, CASE WHEN <snip extensive column definition> END AS myAlias
FROM myTable
WHERE CASE WHEN <snip extensive column definition> END IS NOT NULL

編集

もう 1 つのオプションは、クエリをネストすることです。

SELECT id, myAlias
FROM (
    SELECT id, CASE WHEN <snip extensive column definition> END AS myAlias
    FROM myTable
) AS subTable
WHERE myAlias IS NOT NULL

(編集:HAVINGこれは間違っていたため、オプションを削除しました(@ OMG Poniesに感謝します))

于 2010-02-22T15:01:50.183 に答える
1

put the case in the where. SQL Server will be smart enough to just evaluate it one time so you aren't really duplicating the code:

SELECT id, CASE WHEN <snip extensive column definition> END AS myAlias
FROM myTable
WHERE CASE WHEN <snip extensive column definition> END IS NOT NULL

you could wrap it in a derived table:

SELECT dt.id, dt.myAlias
    FROM (
          SELECT id, CASE WHEN <snip extensive column definition> END AS myAlias
          FROM myTable
         ) dt
    WHERE dt.myAlias IS NOT NULL

However, I try to avoid having derived tables without a restrictive WHERE. You can try it to see if it affects performance or not.

于 2010-02-22T15:00:12.830 に答える