• One simply does not introduces Dynamic SQL
    without a section on how to prevent SQL Injection.

    The basic changes are simple enough to include them in the article and promote good code from the beginning. Parametrize your dynamic strings and validate securable (objects, schemas, databases) names.

    DECLARE @DBName AS VARCHAR(20);
    SET @DBName = 'Test';
    DECLARE @Date AS DATE;
    SET @Date = GETDATE();
    DECLARE @SQL AS NVARCHAR(2000);

    SELECT @SQL =
              N'SELECT COUNT(1) ' + CHAR(13)
            + N'FROM ' + QUOTENAME(d.name) + N'.[dbo].[CommonTable] ' + CHAR(13)
            + N'WHERE [InsertDate] = @iDate;'
    FROM sys.databases AS d
    WHERE d.name = @DBName;

    PRINT @SQL;
    EXEC sp_executesql @SQL, N'@iDate date', @iDate = @Date;

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2