我想循环遍历给定数据库的每个表,以获取每个char字段的唯一值。
我的查询可能类似于:
for each table:
for each row in table:
select distinct char_field
from table
loop
loop
我该怎么做?
答案 0 :(得分:1)
尝试这样
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;
此过程打开一个包含所有表的所有列的游标,其中数据类型包含char
。它将创建一个语句来选择所有不同的值并逐个执行。