Reputation: 919
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
Upvotes: 0
Views: 34
Reputation: 27202
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';
Upvotes: 2