Skip to content
Advertisement

How do I select a Left Join based on a condition

I’m trying to run a left join based on a condition in a SQL Server database. Here’s the code:

DECLARE @DB as nvarchar(25)

$DB = 'db1' --I can just reset this from time to time

SELECT h.name, h.address, w.status
FROM [db0].[dbo].[orec] h
IF ($DB = 'db1')
  BEGIN
    LEFT JOIN [db1].[dbo].[oabc] w on h.id = w.id
  END
ELSE
  BEGIN
    LEFT JOIN [db2].[dbo].[oabc] w on h.id = w.id
  END

Advertisement

Answer

You could try a conditional join:

SELECT h.[name], h.[address], coalesce(w1.[status],w2.[status]) [status]
FROM [db0].[dbo].[orec] h
LEFT JOIN [db1].[dbo].[oabc] w1 on h.id = w1.id and @DB = 'db1'
LEFT JOIN [db2].[dbo].[oabc] w2 on h.id = w2.id and @DB != 'db1';
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement