|
-
Apr 19th, 2011, 08:14 AM
#1
using if exists result?
Hello,
Is there a way to use the if exists select statement result ?
for example:
Code:
IF EXISTS (SELECT col1 FROM table1 where id = 1)
BEGIN
SELECT col1 FROM table1 where id = 1
END
ELSE
BEGIN
-- select from other table
END
in my example above I had to select the same data twice, one for checking if the data exists and then select it again to use it..
so is there a way to use the data i've already selected in the "IF EXISTS" clause ?
thanks and best regards.
* Rate It  If you Like it
__________________________________________________________________________________________
" Programming is like sex: one mistake and you’re providing support for a lifetime."
Get last SQL insert ID 
-
Apr 19th, 2011, 07:46 PM
#2
Re: using if exists result?
Just iterate through result of query, if iteration count is zero then there were no records.
-
Apr 20th, 2011, 03:56 AM
#3
Re: using if exists result?
Something like this?
Code:
SELECT PatientNum FROM tabPatientRecords WHERE PatientNum = 'X'
IF @@ROWCOUNT = 0
SELECT PatientNum FROM tabPatientRecords WHERE PatientNum = 'PN1'
Last edited by dee-u; Apr 20th, 2011 at 04:10 AM.
-
Apr 20th, 2011, 09:15 AM
#4
Re: using if exists result?
Haven't actually tried this and it's a bit on the cludgy side but I think you could use an ISNULL and Sub Selects:-
SELECT ISNULL(
(SELECT col1 FROM table1 where id = 1),
(SELECT col1 FROM table2 where id = 1))
if the record doesn't exist in table 1 the first subselect will return a null so the isnull will cause the second select to be run instead.
The best argument against democracy is a five minute conversation with the average voter - Winston Churchill
Hadoop actually sounds more like the way they greet each other in Yorkshire - Inferrd
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|