Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

tsql - How to use CASE alias in WHERE CLAUSE?

I'm trying to put the "val" into where clause, but it returns error:

    Select ff.FormID, ff.FieldID, ff.FieldName, ff.Title, 
    ff.DefaultValue, fv.Value, 
    val = case fv.Value when null then cast(ff.DefaultValue as nvarchar) else fv.Value end,
    ff.DataType from
    (SELECT FormID, FieldID, FieldName, Title, DataType, DefaultValue FROM FormFields where FormID = '766A38D8-8058-42C6-AC46-A18C00D3C1DC' and DEL = 0) as ff
    left join
    (select FormID, FieldID, Value from FormValues where FormID = '766A38D8-8058-42C6-AC46-A18C00D3C1DC' and ItemID = 'FD63CCA2-C95F-4AB4-B84B-A220017027E7' and DEL = 0) as fv
    on ff.FormID = fv.FormID and ff.FieldID = fv.FieldID
where val is not null


Msg 207, Level 16, State 1, Line 9
Invalid column name 'val'.

Any kind help is appreciated :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not allowed to use aliases in where clause (in sql server), because the order of logical execution of the query is as follows:

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

As you can see WHERE clause is being executed before SELECT, that's why you cannot refer to aliases from SELECT clause

Try:

Select ff.FormID, ff.FieldID, ff.FieldName, ff.Title, 
ff.DefaultValue, fv.Value, 
val = case fv.Value when null then cast(ff.DefaultValue as nvarchar) else fv.Value end,
ff.DataType from
(SELECT FormID, FieldID, FieldName, Title, DataType, DefaultValue FROM FormFields where FormID = '766A38D8-8058-42C6-AC46-A18C00D3C1DC' and DEL = 0) as ff
left join
(select FormID, FieldID, Value from FormValues where FormID = '766A38D8-8058-42C6-AC46-A18C00D3C1DC' and ItemID = 'FD63CCA2-C95F-4AB4-B84B-A220017027E7' and DEL = 0) as fv
on ff.FormID = fv.FormID and ff.FieldID = fv.FieldID
where case fv.Value when null then cast(ff.DefaultValue as nvarchar) else fv.Value end is not null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...