简体   繁体   中英

Combining multiple tables in SQL

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?

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>;
  1. In above, first Splited the @prmCountry values into rows form.
  2. Create dynamic left join query with @prmCountry values

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM