• ScottPletcher (12/16/2013)


    Sean Lange (12/16/2013)


    A slight modification to the fine code Luis posted should work for you. I changed the global temp table to instead use a temp table inside the dynamic sql. This may or not work for you. If you need to get at this data for more than just this select you may want to go back to the global temp table.

    DECLARE @SQL nvarchar(MAX) = 'create table #Temp(TableName sysname, DateMod datetime, MyRowCount bigint);'

    SELECT @SQL = @SQL + 'insert #Temp SELECT ''' + TABLE_NAME + ''' as TableName,

    DATEADD( dd, DATEDIFF( dd, 0, _When), 0),

    COUNT(*)

    FROM [' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']

    GROUP BY DATEADD( dd, DATEDIFF( dd, 0, _When), 0);'

    FROM INFORMATION_SCHEMA.tables

    where TABLE_NAME like ('table%') --I added this part to help limit the tables since my test database does not meet your criteria for table structure.

    select @SQL = @SQL + 'select * from #Temp;'

    exec (@SQL)

    There is one mild inconsistency in this code.

    The temp table contains "MyRowCount bigint", but "COUNT(*)" is in the SELECT -- it should be "COUNT_BIG(*)" if a bigint result is desired.

    Ahh yes. Of course I have no idea if the OP needs bigint or not. The point you are making is to be consistent which my code was not. Thanks for the catch. 😉

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/