sp_MSforeachtable group by or distinct count?

  • I need a simple grouped count of a value from each table in a database.

    Trying to figure out how to modify the script below to include a group by clause or distinct count with subquery?

    DECLARE @TableRowCounts TABLE ([TableName] VARCHAR(128), [RowCount] INT) ;

    INSERT INTO @TableRowCounts ([TableName], [RowCount])

    EXEC sp_MSforeachtable 'SELECT ''?'' [TableName], COUNT(*) [RowCount] FROM ? ' ;

    SELECT [TableName], [RowCount]

    FROM @TableRowCounts

    ORDER BY [TableName]

    GO

    I want the COUNT(*) to be something like this...

    COUNT(*) FROM (SELECT DISTINCT _key_out FROM ?)

    OR COUNT(*) FROM (SELECT _key_out FROM ? GROUP BY _key_out)

    This might not be possible using this sproc..everything I see on this topic never references actual fields in the many tables in the DB. Every table in the DB has the exact same fields (output from SSIS routine).

    Thanks!

    Paul

  • I'm not completely clear what you're doing. Do you mean you have a _key_out field in every table in the DB?

    Are you trying to get

    select count( distinct _key_out) from table1

  • Thats correct. I want a distinct count of every _key_out value in each table in the DB.

  • Does this not work?

    CREATE TABLE MyTable

    (

    _key_out VARCHAR(10)

    , myval int

    );

    INSERT INTO mytable SELECT 'A', 1

    INSERT INTO mytable SELECT 'A', 2

    INSERT INTO mytable SELECT 'B', 1

    INSERT INTO mytable SELECT 'C', 3

    CREATE TABLE MyTable2

    (

    _key_out VARCHAR(10)

    , myval int

    );

    INSERT INTO mytable2 SELECT 'A', 1

    INSERT INTO mytable2 SELECT 'B', 2

    INSERT INTO mytable2 SELECT 'B', 3

    INSERT INTO mytable2 SELECT 'C', 3

    EXEC sp_MSforeachtable 'select tablename=''?'', count(distinct _key_out) from ?'

    Gives 3.

    If I do this:

    EXEC sp_MSforeachtable 'select tablename=''?'', count( _key_out) from ?'

    I get 4.

  • Durrr...yes!

    Thanks Steve!

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply