Skip to content
Advertisement

SQL method for returning data from multiple tables based on column names

I am trying to do something a little weird and cannot figure out the right method for getting it done. Essentially I am trying to pull all tables/views and columns where the column name is like some string. In addition to that I would like to pull 1 row of data from that table/view and column combination. The second part is where I am lost. I know I can pull the necessary tables/views and columns with the below select statement.

SELECT      COLUMN_NAME AS 'ColumnName'
            ,TABLE_NAME AS  'TableName'
FROM        INFORMATION_SCHEMA.COLUMNS
WHERE       COLUMN_NAME LIKE '%email%'
ORDER BY    TableName,ColumnName;

So that I get something like the below

|ColumnName   |TableName   |
|emailAddress |all_emails  |
           ....

But I want to get something like this:

|ColumnName   |TableName   |Example             |
|emailAddress |all_emails  |first.last@gmail.com|
                    ....

Can anyone offer any insight?

Advertisement

Answer

I can’t think of a simple way to do this within a query, but here’s one option…

Put the list of the columns and tables into a temp table and run them through a loop, using dynamic SQL to select the max row for each.

I’ve added plenty of comments below to explain it.

DECLARE @SQL NVARCHAR(1000)
DECLARE @TABLE NVARCHAR(1000)
DECLARE @COLUMN NVARCHAR(1000)
DECLARE @SAMPLE NVARCHAR(1000)

DROP TABLE IF EXISTS ##TABLELIST

SELECT      COLUMN_NAME AS 'ColumnName'
           ,TABLE_NAME AS  'TableName'
           ,ROW_NUMBER() OVER (ORDER BY COLUMN_NAME,TABLE_NAME)[RN]

INTO ##TABLELIST

FROM        INFORMATION_SCHEMA.COLUMNS
WHERE       COLUMN_NAME LIKE '%email%';



ALTER TABLE ##TABLELIST

ADD [Sample] NVARCHAR(1000) -- Add a column for your sample row.

DECLARE @ROWCOUNTER INT = 1 -- Add a counter for the loop to use.

WHILE @ROWCOUNTER <= (SELECT MAX([RN]) FROM ##TABLELIST) -- Keep the loop running until the end of the list.

BEGIN

UPDATE ##TABLELIST
SET @TABLE  = TableName WHERE [RN] = @ROWCOUNTER -- Get the table name into a variable.

UPDATE ##TABLELIST
SET @COLUMN = ColumnName WHERE [RN] = @ROWCOUNTER -- Get the column name into a variable.


SET @SQL = 'SELECT @SAMPLE = MAX([' + @COLUMN + ']) FROM [' + @TABLE + ']' -- Create SQL statement to pull max column from table specified in variables.
 
EXEC SP_EXECUTESQL @SQL, N'@SAMPLE NVARCHAR(1000) OUTPUT', @SAMPLE OUTPUT -- Execute SQL and put the output into the @SAMPLE variable.


UPDATE ##TABLELIST
SET [Sample] = CAST(@SAMPLE AS NVARCHAR(1000)) WHERE [RN] = @ROWCOUNTER -- Insert the SQL output into the sample column.



SET @ROWCOUNTER = @ROWCOUNTER+1 -- Add one to the row counter to move to the next column and table.

END


SELECT * FROM ##TABLELIST -- Select final output.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement