诚信审计

时间:2014-02-05 19:24:47

标签: sql sql-server sql-server-2008 dynamic-data

所以这是我的问题。

我需要计算每个数据库中每个表中所有不同值的计数。

Example:
[db 1]
[table 1] 
[column 1] count()
[column 1] distinct()
[column 1] count()
[column 1] distinct() 
[column 2] count()
[column 2] distinct() etc

[db 2]
[table 1] 
[column 1] count()
[column 1] distinct()
[column 2] count()
[column 2] distinct() etc

现在我到目前为止:

DECLARE @TableName   VARCHAR (MAX) =     'sales'

SELECT DISTINCT
     'SELECT '
   + RIGHT (ColumnList, LEN (ColumnList) - 1)
   + ' FROM '
   + Table_Name +' group BY '+ (ColumnList)','
  FROM INFORMATION_SCHEMA.COLUMNS   COL1
   CROSS APPLY (SELECT ', COUNT ( ' + COLUMN_NAME + ')'+ ','+COLUMN_NAME
                  FROM INFORMATION_SCHEMA.COLUMNS COL2
                 WHERE COL1.TABLE_NAME = COL2.TABLE_NAME
                FOR XML PATH ( '' )) TableColumns (ColumnList)

WHERE 1 = 1 AND COL1.TABLE_NAME = @TableName

所以我只需要小组的帮助。

1 个答案:

答案 0 :(得分:0)

Ohh noo @SaUce再次使用了可怕的CURSOR。

这是解决方案的唯一,这是不是最好的部分,但在这里我将如何做。

以下代码将返回所有行的COUNT()和当前数据库中每个表的COUNT(DISTINCT Column),您只需要弄清楚如何为每个数据库执行它

无论你怎么做,你都必须考虑COUNT(*)和COUNT(DISTINCT)是昂贵的操作,所以最好保存你上次执行它的日期。根据数据库的大小,这可能需要数小时(可能是几天)才能完成。

IF OBJECT_ID('tempdb.dbo.#tempTable') IS NOT NULL
    DROP TABLE #tempTable;

CREATE TABLE #tempTable
    (
     TableName VARCHAR(250)
    ,ColumnName VARCHAR(250)
    ,TotalCount BIGINT
    ,DistinctCount BIGINT
    )

DECLARE @column_name VARCHAR(250)
   ,@table_name VARCHAR(150)
   ,@SQLStatement NVARCHAR(500)

DECLARE table_cursor CURSOR
FOR
    SELECT DISTINCT OBJECT_NAME(object_id)
        FROM sys.tables t
        ORDER BY 1

OPEN table_Cursor
FETCH NEXT FROM table_cursor INTO @table_name

WHILE @@FETCH_STATUS = 0
    BEGIN

        DECLARE column_cursor CURSOR
        FOR
            SELECT DISTINCT name
                FROM sys.columns c
                WHERE OBJECT_NAME(object_id) = @table_name

        OPEN column_cursor

        FETCH NEXT FROM column_cursor
        INTO @column_name

        WHILE @@FETCH_STATUS = 0
            BEGIN
                SET @SQLStatement = N'
                INSERT INTO #tempTable
                SELECT ''' + @table_name + '''
                ,''' + @column_name + '''
                ,COUNT(*)
                ,COUNT(Distinct ' + @column_name + ')
                FROM ' + @table_name + ' WITH(NOLOCK)'

                --PRINT @SQLStatement

                EXECUTE sp_executesql
                    @SQLStatement

                FETCH NEXT FROM column_cursor INTO @column_name 
            END
        CLOSE column_cursor;
        DEALLOCATE column_cursor;

        FETCH NEXT FROM table_cursor INTO @table_name
    END
CLOSE table_cursor
DEALLOCATE table_cursor

SELECT *
    FROM #tempTable