加入具有多个动态表的第一个表

时间:2018-10-21 09:56:08

标签: sql-server sql-server-2008-r2

带有示例数据的表:

CREATE TABLE TBL_1
(
    ID int,
    FName varchar(100),
    LName varchar(100),
    MobileNumber varchar(20)
);

INSERT INTO TBL_1 
VALUES (1, 'John', 'Mak', '1234567890'),
       (2, 'Jack', 'Douj', '9876543210'),
       (3, 'Ozam', 'Utna', '9087987678');

CREATE TABLE TBL_2 
(
    ID int,
    PNumber varchar(20),
    Name varchar(100)
);

INSERT INTO TBL_2 
VALUES (1, '1234567890', 'John'), 
       (2, '9876543210', 'Jack'), 
       (3, '6365454541', 'Povel');

CREATE TABLE TBL_3
(
    AID int,
    FullName varchar(100),
    Address varchar(500)
);

INSERT INTO TBL_3 
VALUES (27061, 'Ozam Utna', 'USA'),
       (27042, 'Yazok Itana', 'UK'), 
       (27089, 'James Erout', 'AUS');

我想将TBL_1联接到TBL_2,将TBL_1联接到TBL_3,并显示TBL_2TBL_3中的列。

注意

  1. 我正在从WHERE Clause之类的UI中获得连接表的条件,例如:

    TBL_1.MobileNumber = TBL_2.PNumber OR 
    TBL_3.FullName LIKE '%' + TBL_1.FName + '%' OR 
    TBL_3.FullName LIKE '%'+ TBL_1.LName +'%'
    
  2. 我要准备动态JOIN,因为我要获得2或可能有更多表来与TBL_1匹配。

我的尝试

DECLARE @Condition VARCHAR(MAX) = 'TBL_1.MobileNumber = TBL_2.PNumber OR TBL_3.FullName LIKE ''%''+ TBL_1.FName +''%'' OR TBL_3.FullName LIKE ''%''+ TBL_1.LName +''%'''
DECLARE @JOIN VARCHAR(MAX) = ''
DECLARE @Table VARCHAR(MAX) = 'TBL_1'
DECLARE @Tables VARCHAR(MAX) = 'TBL_2,TBL_3'
DECLARE @OutputColumn VARCHAR(MAX) = 'TBL_2.Name,TBL_3.Address'
DECLARE @Query VARCHAR(MAX) = ''

SET @JOIN = STUFF((SELECT ' CROSS JOIN ' + Item FROM Function_Split(@Tables,',') FOR XML PATH ('')), 1, 1, '') 

PRINT(@JOIN)

SET @Query = 'SELECT '+@OutputColumn+' FROM '+@Table+' '+@JOIN+' WHERE '+@Condition+'';
PRINT(@Query);    

EXEC(@Query);

但是我得到的输出不正确:

Name    Address
---------------
John    USA
John    UK
John    AUS
Jack    USA
Jack    UK
Jack    AUS
John    USA
Jack    USA
Povel   USA

0 个答案:

没有答案