Question

Excuse my ignorance on this question if it is really simple but its driving me crazy and I have searched (tried and failed) different solutions from this site so here goes...

I am using SQL 2008 and trying to pull results from 12 tables into a single query so I have;

DECLARE @RefID nvarchar(10)
SET @RefID = 'test'

SELECT * From 
Table1, 
Table2, 
Table3, 
Table4, 
Table5, 
Table6, 
Table7,
Table8,
Table9,
Table10,
Table11,
Table12

WHERE table1.[RefID] = @RefID
AND Table2.[Ref ID] = @RefID
AND Table3.[Ref ID] = @RefID
AND Table4.[Ref ID] = @RefID 
AND Table5.[Ref ID] = @RefID
AND Table6.[Ref ID] = @RefID 
AND Table7.[Ref ID] = @RefID 
AND Table8.[Ref ID] = @RefID 
AND Table9.[Ref ID] = @RefID 
AND Table10.[Ref ID] = @RefID 
AND Table11.[RefID] = @RefID 
AND Table12.[RefID] = @RefID `

Now this works fine, is easy to understand and gives me one row will all the data which is exactly what I was looking for.. except with one issue

If a record does not exist in any of the tables, instead of ignoring it or simply give me blank/null values for that table - the query breaks down and I get no results

I would really appreciate any ideas

TIA

Was it helpful?

Solution 2

Realised the first two ideas weren't right:

Select
  *
From (
  Select 
    @RefID RefID
  ) a
    Left Outer Join
  Table1
    On a.RefID = Table1.RefID
  Table2 
    On a.RefID = Table2.RefID
    Left Outer Join
  Table3
    On a.RefID = Table3.RefID
    Left Outer Join
  Table4
    ...
    Left Outer Join
  Table12
    On a.RefID = Table12.RefID

If you don't want the extra RefID at the start, then replace * with Table1.*, Table2.*, ...

OTHER TIPS

The following should work as well...

select * 
from (select RefID = @RefID) x
left join Table1 t1 on t1.RefID = x.RefID
left join Table2 t2 on t2.RefID = x.RefID
left join Table3 t3 on t3.RefID = x.RefID
left join Table4 t4 on t4.RefID = x.RefID
left join Table5 t5 on t5.RefID = x.RefID
left join Table6 t6 on t6.RefID = x.RefID
left join Table7 t7 on t7.RefID = x.RefID
left join Table8 t8 on t8.RefID = x.RefID
left join Table9 t9 on t9.RefID = x.RefID
left join Table10 t10 on t10.RefID = x.RefID
left join Table11 t11 on t11.RefID = x.RefID
left join Table12 t12 on t12.RefID = x.RefID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top