Reputation: 3299
As we can have a command like this in C# or Java
return 1 < 2;
Is it possible to do something like that in SQL?
SELECT 1 < 2
or in my case:
Select
Case when sign = '<' then col1 < 10 else col1 > 10 end
from ...
Result: 0
When I use SELECT 1 < 2
I get an error:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '<'.
So it seems that there is a problem with this statement. I'm using TSQL.
Upvotes: 1
Views: 94
Reputation: 7763
You could also use the inline if statement instead of CASE:
SELECT IIF(1 < 2,'true','false')
Upvotes: 1
Reputation: 14928
I think you mean this:
DECLARE @Col1 INT = 10; --Set your value
SELECT Result = CASE WHEN @Col1 > 10 THEN CAST(@Col1 AS VARCHAR(10) ) + ' > 10'
WHEN @Col1 < 10 THEN CAST(@Col1 AS VARCHAR(10) ) + ' < 10'
ELSE CAST(@Col1 AS VARCHAR(10) ) + ' = 10'
END
OR
DECLARE @Col1 INT = 10;
DECLARE @VarForCompare INT = 55;
SELECT Result = CASE WHEN @Col1 > @VarForCompare THEN CAST(@Col1 AS VARCHAR(10) ) + ' > ' + CAST(@VarForCompare AS VARCHAR(10) )
WHEN @Col1 < @VarForCompare THEN CAST(@Col1 AS VARCHAR(10) ) + ' < ' + + CAST(@VarForCompare AS VARCHAR(10) )
ELSE CAST(@Col1 AS VARCHAR(10) ) + ' = ' + + CAST(@VarForCompare AS VARCHAR(10) )
END
OR using IF:
IF @Col1 > @VarForCompare
SELECT CAST(@Col1 AS VARCHAR(10) ) + ' > ' + CAST(@VarForCompare AS VARCHAR(10) ) Result
ELSE
IF @Col1 < @VarForCompare
SELECT CAST(@Col1 AS VARCHAR(10) ) + ' < ' + CAST(@VarForCompare AS VARCHAR(10) ) Result
ELSE
SELECT CAST(@Col1 AS VARCHAR(10) ) + ' = ' + CAST(@VarForCompare AS VARCHAR(10) ) Result
I don't see why you need Sign
variable.
Upvotes: 1
Reputation: 886
I don't know what DBMS you are using, I am using T-SQL in this example. This should work:
declare @col1 int
declare @sign varchar(1)
set @col1 = 10
set @sign = '<'
Select
case when (@sign = '<') and (@col1 < 10) then 1
when (@sign = '>') and (@col1 > 10) then 1
else 0
end
Upvotes: 1