Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 SQL Select with IF exists condition

Author  Topic 

mbbrennan
Starting Member

4 Posts

Posted - 2012-12-09 : 21:22:00
it is possible to do a select code from table where (if not exist (select value from table) else select value from other table)

I am getting an error on the "IF" part.

The if exists select statement works fine on it's own but not when I add it to the where.

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2012-12-09 : 21:30:08
[code]IF NOT EXISTS (Select * from Table Where Value = @Value)
BEGIN
Select Code from Table
END
ELSE
BEGIN
Select Value from OtherTable
END[/code]
Go to Top of Page

mbbrennan
Starting Member

4 Posts

Posted - 2012-12-09 : 21:44:05
Thanks. I have that and this select hypathetically returns a code that I want to then say select value from table where (if not not exist .. etc) -< this returns a code I want to use in a where.
This does not work.
Go to Top of Page

mbbrennan
Starting Member

4 Posts

Posted - 2012-12-09 : 22:39:39
This is the need:

A value I was to use in a where exists in 1 of two places (table). I need to check if it exists in table 1 use it otherwise check place 2 where it's guaranteed to be. The value returned from this I need to pass to a where clause. Has to be within a select statement and not transact sql.
Go to Top of Page

mbbrennan
Starting Member

4 Posts

Posted - 2012-12-10 : 00:24:48
I changed my code to a union but I still have 1 problem.

select col1 from tablea
union
select col1 from tableb

I need to apply precedence where if result is found in first select, I don't care about results from secomd select

I tried - select top 1 * from (select col1 from tablea union select col1 from tableb) but top 1 returned the highest value from col1 which is an int return type
Go to Top of Page

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2012-12-10 : 01:35:02
[quoteI need to apply precedence where if result is found in first select, I don't care about results from secomd select
[/quote]

SELECT col1, 1 const from tablea
union
select col1, 2 from tableb
ORDER BY const


--
Chandu
Go to Top of Page

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-12-10 : 07:50:50
The following is probably not the most efficient, but logically guaranteed to produce what you described:
select col1 from Tablea
union all
(
select col1 from Tableb
except
select col1 from Tablea
);
Go to Top of Page
   

- Advertisement -