2017-06-28 6 views
0

ビュー内では、select文を1つのケースに入れ、それを列としてdelcaredします。列名は 'IR2'Microsoft SQLを使用して作成された列の式

'IR2'列の大文字と小文字は区別できますか?

「無効な列名 'IR2'」というエラーが表示されます。

私の回避策は何ですか?

case when r.ana = 'nh3' and r.serv='energy' and exists(select 1 from results x where x.no=r.no and x.ana='nh3' and x.sa='rejected' and x.serv <> 'energy') 
then '*' else r.sa end as IR2, 

CASE IR2 WHEN 'Released' then 
'' 
ELSE 
'*' 
END AS IR 
+0

あなたは、select句で別名IR2を使用することはできません – sle1306

答えて

1

CTEは最良の選択でしょう。現在のステートメントを継続したい場合は、caseステートメントのコピーを別のcaseステートメントに入れる必要があります。非常に乱雑なコード。

SELECT 
case when r.ana = 'nh3' and r.serv='energy' and 
exists(select 1 from results x where x.no=r.no and x.ana='nh3' and x.sa='rejected' and x.serv <> 'energy') 
then '*' else r.sa end as IR2, 

CASE 
    (case when r.ana = 'nh3' and r.serv='energy' 
     and exists(select 1 from results x where x.no=r.no and x.ana='nh3' and x.sa='rejected' and x.serv <> 'energy') 
     then '*' else r.sa end) 
WHEN 'Released' then 
    '' 
ELSE 
    '*' 
END AS IR 
2

サブクエリまたはCTEを使用できます。しかし、SQL Server内の別の楽しい方法はouter applyを使用している:

select v.IR2, 
     (case IR2 when 'Released' then '' else '*' end) as ir 
from . . . outer apply 
    (values (case when r.ana = 'nh3' and r.serv='energy' and 
         exists(select 1 from results x where x.no=r.no and x.ana='nh3' and x.sa='rejected' and x.serv <> 'energy') 
        then '*' else r.sa 
       end) 
    ) v(IR2) 
+2

IR2は、フィールドが、クエリ内の別名ではありません。エイリアスは 'order by'節でのみ使用でき、selectの他の部分では使用できません。 – sle1306

+0

@ sle1306。 。 。ハァッ? 'IR2'は' OUTER APPLY'を使って 'FROM'節で定義されています。あなたのコメントは間違っていて、なぜそれがupvotedになるのか分からない。 –

+0

私はあなたの答えのものではなく、質問の元の質問について取り上げていました。 – sle1306

関連する問題