使用条件在 SQL 中设置选项
Using condition to set OPTION in SQL
有没有办法根据条件设置 OPTION 语句?下面的代码正在存储过程中执行。 select 语句只是一个示例。选项放置必须在 WHERE 语句之后,但是我在 WHERE 之后使用 IF 语句时出错。
我需要这样的东西:
declare @time int = datepart(hh, getdate())
select *
from my_table
where x = something
if (@time > 8)
OPTION (LABEL = 'day')
else
OPTION (LABEL = 'night')
end
你基本上有两个选择。要么重复 SQL:
声明@time int = datepart(hh, getdate());
if @time > 8
select *
from my_table
where x = something
OPTION (LABEL = 'day') ;
else
select *
from my_table
where x = something
OPTION (LABEL = 'night') ;
或使用动态SQL:
declare @sql nvarchar(max);
set @sql = '
select *
from my_table
where x = something
option (label = ''[label]'')
';
set @sql = replace(@sql, '[label]', case when @time > 8 then 'day' else 'night' end);
exec sp_executesql @sql;
有没有办法根据条件设置 OPTION 语句?下面的代码正在存储过程中执行。 select 语句只是一个示例。选项放置必须在 WHERE 语句之后,但是我在 WHERE 之后使用 IF 语句时出错。
我需要这样的东西:
declare @time int = datepart(hh, getdate())
select *
from my_table
where x = something
if (@time > 8)
OPTION (LABEL = 'day')
else
OPTION (LABEL = 'night')
end
你基本上有两个选择。要么重复 SQL:
声明@time int = datepart(hh, getdate());
if @time > 8
select *
from my_table
where x = something
OPTION (LABEL = 'day') ;
else
select *
from my_table
where x = something
OPTION (LABEL = 'night') ;
或使用动态SQL:
declare @sql nvarchar(max);
set @sql = '
select *
from my_table
where x = something
option (label = ''[label]'')
';
set @sql = replace(@sql, '[label]', case when @time > 8 then 'day' else 'night' end);
exec sp_executesql @sql;