How To Write a Case Statment to check two tables

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Brian Connelly
    New Member
    • Jan 2011
    • 103

    How To Write a Case Statment to check two tables

    I have a Invoice Number that can appear in either two tables (history = table A and current= table B) which have all the same fields, but not both tables at one time. I want to check If the invoice is in table A and if so then grab other fields, if not check table B. How would I write a Case statement of If Statement for this?
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Outer join the two tables and use coalesce on the two fields to return the one with data.

    Comment

    • Brian Connelly
      New Member
      • Jan 2011
      • 103

      #3
      Do you have a small sample of how to do that? Im kind of new to advance SQL.

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        It would be something like this:
        Code:
        SELECT *
        tableA FULL OUTER JOIN tableB
        ON tableA.ID = tableB.ID
        WHERE COALESCE(tableA.ID, tableB.ID) = 12345

        Comment

        • ariful alam
          New Member
          • Jan 2011
          • 185

          #5
          You can check the following:
          Code:
          if exists (select * from tableA where id = 1234)
          begin
             select * from tableA where id = 1234
          end
          else if exists (select * from tableB where id = 1234)
          begin
             select * from tableB where id = 1234
          end
          else
          begin
             select 'answer'=0
          end

          Comment

          Working...