Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

dynamic SQL to get distinct values from specific table.column combinations

$
0
0

Hi,

I have a table variable that contains a list of specific table names and certain columns within those tables (see example code).  The goal is to write dynamic SQL to generate the results that the individual SELECT DISTINCT statements are producing in the example below.  How can this be achieved?

DECLARE @List TABLE
(
  TableName           NVARCHAR(50),
  ColumnName          NVARCHAR(50),
    PRIMARY KEY CLUSTERED(TableName, ColumnName)
);

INSERT INTO
  @List
VALUES
  ('Table1', 'Column7'),
  ('Table1', 'Column12'),
  ('Table6', 'Column2'),
  ('Table4', 'Column21');

--goal: to write dynamic SQL that will do the equivalent of this
SELECT DISTINCT Column7 FROM Table1;
SELECT DISTINCT Column12 FROM Table1;
SELECT DISTINCT Column2 FROM Table6;
SELECT DISTINCT Column21 FROM Table4;


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>