对于嵌套的IF ELSE,在T-SQL中是否有可行的替代方法用于比较,其中必须根据比较结果进行不同的逻辑?我的情况是涉及选择表示评估条件的nvarchar值,并根据条件进行评估。我最初试图在CASE声明中实现如下:
SELECT
CASE @condition
WHEN '<' THEN
IF (@processing_time < @threshold_value)
BEGIN
SET @condition_met = 1 --compare threshold_value and processing_time
END
WHEN '<=' THEN
IF (@processing_time <= @threshold_value)
BEGIN
SET @condition_met = 1 --compare threshold_value and processing_time
END
WHEN '>' THEN
IF (@processing_time > @threshold_value)
BEGIN
SET @condition_met = 1 --compare threshold_value and processing_time
END
WHEN '>=' THEN
IF (@processing_time >= @threshold_value)
BEGIN
SET @condition_met = 1 --compare threshold_value and processing_time
END
WHEN '=' THEN
IF (@processing_time = @threshold_value)
BEGIN
SET @condition_met = 1 --compare threshold_value and processing_time
END
END -- end case statement
然而,基于我在别处看到的以及我得到的语法错误,似乎case语句中的WHEN子句只能赋值,而不能执行评估逻辑。我能想到的唯一选择是使用嵌套的IF / ELSE语句执行等效逻辑。有没有更好的办法?重新设计表/数据类型是一种选择。
答案 0 :(得分:4)
我这里没有数据库来检查这个语法没有输入错字,但这应该这样做..
set @condition_met = (SELECT
CASE WHEN (@condition = '<' AND @processing_time < @threshold_value) OR
(@condition = '<=' AND @processing_time <= @threshold_value) OR
(@condition = '>' AND @processing_time > @threshold_value) OR
(@condition = '>=' AND @processing_time >= @threshold_value) OR
(@condition = '=' AND @processing_time = @threshold_value)
THEN 1 ELSE 0 END)
或者你可以简单地做一系列IF
陈述来做同样的事情,例如
SET @condition_met = 0;
IF @condition = "<" AND @processing_time < @threshold_value SET @condition_met = 1;
IF @condition = "<=" AND @processing_time <= @threshold_value SET @condition_met = 1;
etc..
答案 1 :(得分:2)
SELECT @Condition_Met = CASE
WHEN (@condition = '<' AND @processing_time < @threshold_value) OR
(@condition = '<=' AND @processing_time <= @threshold_value) OR
(@condition = '>' AND @processing_time > @threshold_value) OR
(@condition = '>=' AND @processing_time >= @threshold_value) OR
(@condition = '=' AND @processing_time = @threshold_value)
THEN 1 ELSE 0 END
在我看来,你似乎试图做太多的程序代码,而不是基于集合或声明性。我觉得这整个事物都属于一个更大的查询的一部分,所以你甚至不需要声明这些变量。
答案 2 :(得分:0)
还要考虑动态SQL解决方案。
declare @op varchar(5) = '>'
declare @sql nvarchar(max) =
'declare @condition_met bit
declare @processing_time int = 7
declare @threshold_value int = 6
select @condition_met = case when @processing_time'+@op+'@threshold_value then 1 else 0 end
select @condition_met'
exec (@sql)
如果表达式位于WHERE
子句中且@processing_time
或@threshold_value
是索引列并且您确实想要使用索引,那么它可能很有用。