+ Reply to Thread
Results 1 to 2 of 2

Thread: joining multiple tables

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    10

    joining multiple tables

    I`d like to join multiples tables (A, B, C, and D) together. I know table A always exists. However, I only know at least one of the table form (B, C, D) exists.
    Code:
    Select * form table a     
    If table b exists left Join table b on a.id = b.id    
    If table c exists left Join table c on a.id = c.id    
    If table d exists left Join table d on a.id = d.id
    Can you tell me how to accomplish this ?

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    31
    You'll have to check the data dictionary views for that and use dynamic SQL
    Code:
    declare @myquery varchar(1000)
    
    set @myquery = 'Select * from a '
    if exists (select * from sysobjects where xtype='U' and name = 'b')
    begin
       set @myquery = @myquery + 'inner join b on b.id = a.id '
    end
    if exists (select * from sysobjects where xtype='U' and name = 'c')
    begin
       set @myquery = @myquery + 'inner join c on c.id = a.id '
    end
    if exists (select * from sysobjects where xtype='U' and name = 'd')
    begin
       set @myquery = @myquery + 'inner join d on d.id = a.id '
    end
    
    exec( @myquery)

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts