【问题标题】:How to use CASE alias in WHERE CLAUSE?如何在 WHERE CLAUSE 中使用 CASE 别名?
【发布时间】:2023-04-11 02:15:01
【问题描述】:

我正在尝试将“val”放入 where 子句,但它返回错误:

    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 子句放在子查询之外,或者您必须在 WHERE 中重新声明您的 CASE 表达式。
  • 你不能在那里引用别名,除非这是一个子查询并且你从中选择。相反,您可以在 where 子句中使用 val 的 case 语句。它可能看起来很乱,但它确实有效。
  • 参见“SELECT 语句的逻辑处理顺序”。 WHERE 是第 4 步。并且“因为 SELECT 子句是第 8 步,所以在该子句中定义的任何列别名或派生列都不能被前面的子句引用”

标签: tsql case where clause


【解决方案1】:

where子句(sql server中)不允许使用别名,因为查询的逻辑执行顺序如下:

  1. 来自
  2. 开启
  3. 加入
  4. 在哪里
  5. 分组依据
  6. 使用多维数据集或使用汇总
  7. 选择
  8. 不同
  9. 订购人
  10. 顶部

如您所见,WHERE 子句在 SELECT 之前执行,这就是为什么您不能从 SELECT 子句中引用别名

试试:

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

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 2016-10-30
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    相关资源
    最近更新 更多