• Peter Heller - Monday, February 12, 2018 5:42 AM

    I would have used the concat function SQL Server 2012 or better, eliminate the cast by letting concat handle the char(10) cast and use sysdatetime() instead of Getdate().


    declare @DBName as varchar(20);
    set @DBName = 'Branch1';
    declare @Date as date;
    set @Date = sysdatetime() --not Getdate();
    declare @SQL as varchar(2000);

    select @SQL
      = 'SELECT COUNT(1) ' + 'FROM [' + @DBName + '].[dbo].[CommonTable] ' + 'WHERE [InsertDate] = '''
      + cast(@Date as char(10)) + '''';
    print @SQL;

    select @SQL                                                                                                                                                
      = concat('SELECT COUNT(1) FROM [', @DBName, '].[dbo].[CommonTable] WHERE [InsertDate] = ', quotename(@Date, ''''));

    print @SQL;
    EXEC (@SQL)

    SysDateTime() returns more bytes, which isn't necessary here because you're dumping the result to a variable with the DATE datatype. 

    As a bit of a sidebar and , SysDateTime() is relatively crippled because it returns a DATETIME2() datatype compared to GETDATE() which uses the powerful DATETIME datatype.  DATETIME supports incredibly easy to use direct date/time math for period calculations (which is in the ISO standards) where DATETIME2() does not (at least not in SQL Server because they screwed it up).  If you use it to support supposed "portable code",  true portability is a myth and can't actually be accomplished to any great degree.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)