游标从SQL Server 2008上的每个表和字段获取所有不同的值

时间:2017-07-17 16:02:53

标签: sql-server sql-server-2008 cursor

我正在尝试在SQL Server数据库上执行游标以获取每个表中的所有Distinct值。 我希望表中的值看起来像这样:

 Database   Schema   Table   Field   Value
     A         dbo     T1     F1       1
     A         dbo     T1     F1       2
     A         dbo     T1     F1       3
    ...        ...     ...    ...     ...

我的麻烦是当我尝试使用QUOTENAME(TABLE_CATALOG)放置数据库名称时,它不会评估函数,而是将函数写入我想要生成的表。 我试过没有结果的单/双引号。

¿我应该如何编写查询?谢谢!

Set Nocount ON

DECLARE cur CURSOR FOR
SELECT 'SELECT DISTINCT ' + ''' QUOTENAME(TABLE_CATALOG) + '''+' As DBName,'+ + QUOTENAME(c.COLUMN_NAME) + ' AS Datos' + ' 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;

Set Nocount OFF

BTW:我从代码(Get distinct values from each table and each column with SQL Server

中获取了代码并对其进行了编辑

1 个答案:

答案 0 :(得分:0)

''' QUOTENAME(TABLE_CATALOG) + '''你没有得到正确的引用。它应该是''' + QUOTENAME(TABLE_CATALOG) + '''

引用通过将它们加倍来逃避,例如。

SELECT 'blah' --> blah
SELECT 'it''s' --> it's
SELECT ' Alex''' + 's pen' -->  Alex's pen

语法错误

SELECT 'it's' --> syntax error

完成的查询在这里:

SET NOCOUNT ON

DECLARE cur CURSOR FOR
SELECT 'SELECT DISTINCT ''' + QUOTENAME(TABLE_CATALOG) + ''' As DBName, ''' + QUOTENAME(TABLE_SCHEMA) + ''' AS [Schema], ''' + QUOTENAME(COLUMN_NAME) + ''' AS ColumnName, '
    +  QUOTENAME(c.COLUMN_NAME) + ' AS Datos ' +
    '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;

SET NOCOUNT OFF

注意:

  • 如果您不希望字符串被QUOTENAME(方块)包围,请删除[]
  • INFORMATION_SCHEMA.COLUMNS的评论:为了您的目的,此视图将返回https://stackoverflow.com/a/7310746/6305294中所述的正确数据(来自@ShannonSeverance的评论)。此视图缺少的是有关列属性的详细信息。