首页 > 解决方案 > 带有子查询的 case 语句 then

问题描述

我有这个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 引入子查询时,选择列表中只能指定一个表达式。

标签: sqlsql-servertsqlcase

解决方案


CASE是一个表达式而不是一个语句- 这正是您遇到的问题:您不能从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

推荐阅读