Raouf
Raouf

Reputation: 1229

Get distinct values from each table and each column with SQL Server

I would like to loop through each table for a given database to get unique values for each char field.

My query might something like:

for each table:
    for each row in table:
       select distinct char_field
       from table
    loop
loop

How do I do this?

Upvotes: 0

Views: 3958

Answers (1)

Gottfried Lesigang
Gottfried Lesigang

Reputation: 67291

Try it like this

DECLARE cur CURSOR FOR
    SELECT 'SELECT DISTINCT ' + QUOTENAME(c.COLUMN_NAME) + 'AS ' + QUOTENAME(TABLE_CATALOG + '.' + TABLE_SCHEMA + '.' + TABLE_NAME) + ' FROM ' + QUOTENAME(TABLE_CATALOG) + '.' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
    FROM INFORMATION_SCHEMA.COLUMNS AS c
    WHERE c.DATA_TYPE LIKE '%char%' 

DECLARE @cmd VARCHAR(MAX);
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @cmd
    EXEC(@cmd);
    FETCH NEXT FROM cur INTO @cmd;
END

CLOSE cur;
DEALLOCATE cur;

This process opens a cursor with all columns of all tables, where the data-type contains char. It will create a statement to select all distinct values and executes this one after the other.

Upvotes: 2

Related Questions