Is there a viable alternative in T-SQL to a nested IF ELSE for comparisons in which different logic must take place based on the result of the comparison? My situation is involves selecting a nvarchar value representing the condition for evaluation, and based on the condition an evaluation takes place. I initially sought to implement this in a CASE statement as follows:
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
However, based on what I have seen elsewhere and the syntax errors I am getting, it seems that the WHEN clause in a case statement can only assign values, not perform evaluation logic. The only alternative I can think of is to perform equivalent logic using nested IF/ELSE statements. IS there a better way? Redesign of tables/data types is an option.
I haven’t got a database here to check this syntax hasn’t got typos in it but this should do it..
Alternatively you could simply do a series of
IFstatements to do the same thing, E.g.