Results 1 to 4 of 4

Thread: using if exists result?

  1. #1

    Thread Starter
    PowerPoster motil's Avatar
    Join Date
    Apr 2009
    Location
    Tel Aviv, Israel
    Posts
    2,143

    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

  2. #2
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: using if exists result?

    Just iterate through result of query, if iteration count is zero then there were no records.

  3. #3
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,127

    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.
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  4. #4
    Super Moderator FunkyDexter's Avatar
    Join Date
    Apr 2005
    Location
    An obscure body in the SK system. The inhabitants call it Earth
    Posts
    7,957

    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
  •  



Click Here to Expand Forum to Full Width