如何在WHERE CLAUSE中使用CASE别名? [英] How to use CASE alias in WHERE CLAUSE?
本文介绍了如何在WHERE CLAUSE中使用CASE别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将"val"放入where子句,但它会返回错误:
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'.
感谢任何帮助:)
推荐答案
不允许在where子句中使用别名(在SQL Server中),因为查询的逻辑执行顺序如下:
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:
- 从
- 开启
- 加入
- 在哪里
- 组别
- 多维数据集或具有汇总
- 拥有
- 选择
- DISTINCT
- ORDER BY
- TOP
- FROM
- ON
- JOIN
- WHERE
- GROUP BY
- WITH CUBE or WITH ROLLUP
- HAVING
- SELECT
- DISTINCT
- ORDER BY
- TOP
您可以看到WHERE
子句在SELECT
之前执行,这就是为什么您不能从SELECT
子句引用别名的原因
As you can see WHERE
clause is being executed before SELECT
, that's why you cannot refer to aliases from SELECT
clause
尝试:
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
这篇关于如何在WHERE CLAUSE中使用CASE别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文