Reputation: 35
I need a result set of multiple tables combined. I have a query with a from clause using a table for each country that are selected in the parameter.
Ex:
@prmCountry='AU,UK,US'
Now in the from clause the table name is as such that it has to run for each country separately:
from tbl_abc t1
left outer join tbl_country_(CountryName) t2
on.....
How to exactly do this?
Upvotes: 0
Views: 109
Reputation: 50163
As your question is not more clear, but you are looking in some dynamic SQL
Query :
DECLARE @prmCountry VARCHAR(MAX)= 'AU,UK,US';
DECLARE @SQL NVARCHAR(MAX)= N'';
DECLARE @Query NVARCHAR(MAX);
SELECT @SQL+=N' left join table_'+CC.Country+' on table_'+CC.Country+'.<column> = t1.<column>'
FROM
(
SELECT split.a.value('.', 'NVARCHAR(MAX)') [Country]
FROM
(
SELECT CAST('<A>'+REPLACE(@prmCountry, ',', '</A><A>')+'</A>' AS XML) AS Country
) C
CROSS APPLY Country.nodes('/A') AS split(a)
) CC;
SET @Query = 'SELECT * FROM tbl_abc t1'+@SQL+';';
PRINT @Query;
--EXECUTE sp_executesql @query
SQL
Query produce :
SELECT * FROM tbl_abc t1
left join table_AU on table_AU.<column> = t1.<column>
left join table_UK on table_UK.<column> = t1.<column>
left join table_US on table_US.<column> = t1.<column>;
@prmCountry
values into rows form.@prmCountry
valuesUpvotes: 1
Reputation: 33
Use UNION ALL like this:
SELECT
tbl_abc t1
left outer join tbl_country_('AU') t2
on.....
UNION ALL
SELECT
tbl_abc t1
left outer join tbl_country_('US') t2
on.....
...and so on
Upvotes: 0