【问题标题】:Case statement with subquery in then带有子查询的 case 语句 then
【发布时间】:2021-05-15 18:01:30
【问题描述】:

我有这个case语句,我的目标是根据变量“equipo”执行不同的查询

declare @equipo nvarchar(30)
set @equipo='CA10'

SELECT CASE

when @equipo in ('CA10','CA11') then
(select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment=@equipo AND readtime between GETDATE()-15 AND GETDATE())

when @equipo='CA62' then
(select top 100 a.ReadTime, a.EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment=@equipo AND readtime between GETDATE()-15 AND GETDATE())

else 'nothing'
end

我的问题是:这个查询有什么问题?它不断向我抛出错误:

当不使用 EXISTS 引入子查询时,选择列表中只能指定一个表达式。

【问题讨论】:

  • 看起来你想要的是一个IF 声明; SQL Server 不支持 Case (Switch) 语句。

标签: sql sql-server tsql case


【解决方案1】:

CASE 是一个 expression 而不是 statement - 这正是你所犯的错误:你不能从 case 表达式返回结果,只有一个单值。无论如何,您不同的whens 返回完全相同的值?但是假设您的内部查询实际上是不同的,您可以使用UNION ALL

select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment = @equipo
and readtime between getdate()-15 and getdate()
and @equipo in ('CA10','CA11')

union all 

select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment = @equipo
and readtime between getdate()-15 and getdate()
and @equipo in ('CA62');

注意:您应该真正使用 dateadd() 而不是 getdate()-15 - 以确保正确的结果(是 15 分钟、天还是小时?)。请注意,您知道between>=<=,因此包含两个边界。这可能会产生意想不到的结果,尤其是考虑到时间部分。

编辑:当您阐明了您的要求后,您可以使用IF 语句(如 Larnu 建议的那样),例如

if @equipo in ('CA10','CA11') begin
    select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
    from table
    where Equipment = @equipo
    and readtime between getdate()-15 and getdate();
end; else if @equipo in ('CA62') begin
    select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
    from table
    where Equipment = @equipo
    and readtime between getdate()-15 and getdate();
end; -- etc

【讨论】:

  • 感谢您的回答,我需要返回 5 个不同的查询,具体取决于“camion”的值,因此无法使用“union”解决方案,
  • @DavidMenacho 那么请确保您的问题反映了您的实际情况,以免我们浪费时间!任何客户端调用此查询都可以处理不同的结构化数据集吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
相关资源
最近更新 更多