Siamak Ferdos
Siamak Ferdos

Reputation: 3299

select a condition as column in sql

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

Answers (4)

Steve Ford
Steve Ford

Reputation: 7763

You could also use the inline if statement instead of CASE:

SELECT IIF(1 < 2,'true','false')

Upvotes: 1

Hong Van Vit
Hong Van Vit

Reputation: 2986

select case when 1 <2 then 'true' else 'false' end

Upvotes: 1

Ilyes
Ilyes

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

Hemisphera
Hemisphera

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

Related Questions