I used a cursor to iterate through each table and column in the INFORMATION_SCHEMA.COLUMNS
view, which builds and executes a dynamic SQL query for each combination to retrieve the top 10 values from that column Where I stored the results in a temporary table #Top10Values
.
DECLARE @schema NVARCHAR(128)
DECLARE @table NVARCHAR(128)
DECLARE @column NVARCHAR(128)
DECLARE @sql NVARCHAR(MAX)
CREATE TABLE #Top10Values
(
[Schema] NVARCHAR(128),
[Table] NVARCHAR(128),
[Column] NVARCHAR(128),
[Data Type] NVARCHAR(128),
[NULL] NVARCHAR(3),
[Reference_Data (top ten values)] NVARCHAR(MAX)
)
DECLARE column_cursor CURSOR FOR
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA <> 'sys' -- Exclude system tables if necessary
ORDER BY TABLE_SCHEMA, TABLE_NAME
OPEN column_cursor
FETCH NEXT FROM column_cursor INTO @schema, @table, @column
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = '
INSERT INTO #Top10Values ([Schema], [Table], [Column], [Data Type], [NULL], [Reference_Data (top ten values)])
SELECT ''' + @schema + ''', ''' + @table + ''', ''' + @column + ''',
DATA_TYPE, IS_NULLABLE,
STUFF((SELECT TOP 10 '', '' + QUOTENAME(' + @column + ')
FROM ' + QUOTENAME(@schema) + '.' + QUOTENAME(@table) + '
WHERE ' + QUOTENAME(@column) + ' IS NOT NULL
ORDER BY ' + QUOTENAME(@column) + '
FOR XML PATH('''')), 1, 2, '''')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ''' + @schema + '''
AND TABLE_NAME = ''' + @table + '''
AND COLUMN_NAME = ''' + @column + ''''
EXEC sp_executesql @sql
FETCH NEXT FROM column_cursor INTO @schema, @table, @column
END
CLOSE column_cursor
DEALLOCATE column_cursor
SELECT *
FROM #Top10Values
ORDER BY [Schema], [Table]
DROP TABLE #Top10Values
This is an example of my fictive database :
Schema Table Column Data Type NULL Reference_Data (top ten values)
dbo ClientInterface ACCOUNT_OFFICER float YES [401], [401], [401], [401], [401], [401], [401], [401], [401], [401]
dbo ClientInterface OTHER_OFFICER float YES [2006], [2006], [2006], [2006], [2006], [2006], [2006], [2006], [2006], [2008]
dbo ClientInterface INDUSTRY float YES [1005], [1005], [1006], [1010], [1010], [1010], [1010], [1010], [1010], [1010]
dbo ClientInterface NATIONALITY nvarchar YES [TN], [TN], [TN], [TN], [TN], [TN], [TN], [TN], [TN], [TN]
dbo ClientInterface GENDER nvarchar YES [FEMALE], [FEMALE], [FEMALE], [FEMALE], [FEMALE], [FEMALE], [FEMALE], [FEMALE], [FEMALE], [FEMALE]
dbo ClientInterface SECTOR float YES [1000], [1000], [1000], [1000], [1000], [1000], [1000], [1000], [1000], [1000]