我有以下条件:
表 1
col1 col2 col3
1 40 100(tblABC 的标识列值)
2 41 101(tblDEF 的标识列值)
表 2
col1 col2 col3
40 tblABC tblABCPrimaryKey
41 tblDEF tblDEFPrimaryKey
========== 不同的表 ==============
tblABC
tblPrimaryKeyId col2
100 VALUE
tblDEF
tblPrimaryKeyId col2
101 值
我需要在连接
选择 Table-1.col1、
Table-2.col2、
[ tblABC.col2 OR tblDEF.col2 等取决于表]
从 Table-1
INNER JOIN 中获得以下列(连接到这里)
我想
从表 1 中获取col1,
从表 2 中获取 col2 ,其中表 1 的col2 与表 2 的 col1 匹配,
来自(表 2 的 COL2 中的表,其中表 2 的 col3 与这些表中的列匹配)的 col2 col-2 [不同的表])
请帮忙。
DECLARE @sql NVARCHAR(MAX) = '
SELECT Table1.col1
, Table2.col2,
, COALESCE(';
SELECT
@sql = @sql + #Table2.col2 + '.col2, '
FROM #Table2;
SET @sql = @sql + ' NULL)
INNER JOIN Table2
ON Table1.col2 = Table2.col1';
SELECT
@sql = @sql + '
LEFT JOIN ' + col2 + '
ON Table2.col2 = ''' + col2 + '''
AND Table1.col3 = ' + col2 + '.col1'
FROM #Table2
EXEC sys.sp_executesql @sql;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句