Search code examples
sqlsql-serversql-server-2000

Can an SQL if else clause have a select inside?


I doubt this is possible but here goes.

I need to formulate a SQL query (absolutely not allowed a stored procedure) that does something like this:

Select A.valueFromTable -B.ValueFromTable As result
From table as A inner join table as B
on A.ValueID = B.ValueID
Where ValueID =5

But I need the condition:

if (result <0)
Begin
select A As result ....
end
else
select A-B as result ...

Any help would be greatly appreciated even if it's confirming that it cannot be done.

From searches I believe the version of SQL Server I am currently using is 8.0


Solution

  • Select 
        CASE
            WHEN A.valueFromTable -B.ValueFromTable < 0 THEN A.valueFromTable 
        ELSE A.valueFromTable -B.ValueFromTable END As result
    From table as A inner join table as B
    on A.ValueID = B.ValueID
    Where ValueID =5