SQL Server Can you join two tables using a template that has columns as a list of column names from respective tables?

vshtjzan  于 2023-04-04  发布在  其他
关注(0)|答案(1)|浏览(154)

I am trying to use the template table that has 2 columns to create a desired Result table using:

  • The first column: a list of all the column names in Table A.
  • The Second Column : a list of all column names in Table B.

From the table below I want to use the column names from TableA and Table B and compare the values joining them on their ID.

Template Table
| TableA | TableB |
| ------------ | ------------ |
| Id | Id |
| Fruits1 | Fruits2 |
| Vegetables1 | Vegetables2 |

Table A

IdFruits1Vegetables1
1AppleCarrot
2BananaPumpkin

Table B

IdFruits2Vegetable2
1AppleCarrot
2BananaOnion

Desired Result

IDFruits1Fruits2Comparison1Vegetable1Vegetable2Comparison2
1AppleAppleTrueCarrotCarrotTrue
2BananaBananaTruePumpkinOnionFalse

How can I use the Template table to join Table A and Table B using the ID to produce the above table?

I tried Unpivoting the mapping table but I could not find a way.

vhmi4jdf

vhmi4jdf1#

It seems the best way to do this would be dynamic SQL.

You need to build up a list of columns

DECLARE @sql nvarchar(max);

SELECT @sql =
  STRING_AGG(
    CONCAT(
      '
  a.',
      QUOTENAME(t.TableA),
      '1,
  b.',
      QUOTENAME(t.TableB),
      '2,
  Comparison',
      ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
      ' = CASE WHEN b.',
      QUOTENAME(t.TableA),
      ' = a.',
      QUOTENAME(t.TableB),
      ' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END'
    ),
    ',
')
FROM Template t
WHERE t.TableA <> 'ID';

SET @sql = '
SELECT
  a.ID,
' + @sql + '
FROM TableA a
JOIN TableB b ON b.ID = a.ID;
`;

PRINT @sql;   -- your friend

EXEC sp_executesql @sql;

相关问题