8

My requirement is to get a number from a complex query and check if the num = desiredNum.

If it is equal to desiredNum, then I must perform another set of select statements,

Is there any way I can achieve this in a query rather than writing a function?

Eg:

select case when val =2  
then select val1 from table1  
else 'false'  
from (select val from table)  

Is this possible ??

boutta
  • 24,189
  • 7
  • 34
  • 49
swathy
  • 189
  • 1
  • 3
  • 14

2 Answers2

14
select case when val=2 then val1 else val end as thevalue
from table1

I assume you meant that val and val1 are both from the same table, but when val=2, to use val1 instead. If you actually had two tables, and they both have only one record each, then

select
    case when val=2
    then (select val1 from table1)
    else 'false'
    end
from table
RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262
0

I am not 100% I understand what you need. But I think you could use a union to do this:

create table theValues ( theValue integer)
create table table1 ( value1 integer)
create table table2 ( value2 integer)


INSERT INTO theValues (thevalue) VALUES (2)
INSERT INTO table1 ( value1 ) VALUES (17)
INSERT INTO table2 ( value2 ) VALUES (8)


SELECT value1 from table1 WHERE EXISTS (SELECT theValue from theValues WHERE theValue != 2)
UNION ALL 
SELECT value2 from table2 WHERE EXISTS (SELECT theValue from theValues WHERE theValue  = 2)

In this case the "magic number" is 2. If the theValues table query returns 2, then you get the results from the result from table2, else you get the result from table 1.

Cheers, Daniel

Daniel Williams
  • 8,912
  • 15
  • 68
  • 107
  • Hi Daniel, when my case condition is satisfied, I must be able to run another select query in db .. id this possible ?? – swathy Mar 04 '11 at 04:44