简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM