Home Forums SQL Server 2008 SQL Server 2008 - General Dynamic SQL and DATEADD with User Defined Variable in Number/2nd position RE: Dynamic SQL and DATEADD with User Defined Variable in Number/2nd position

  • It's as simple as this:

    SET @sql = 'SELECT * FROM <sometable>

    WHERE dateadd(hh, @tzoffset, END_DATETIME) BETWEEN @StartDate AND @EndDate'

    When you work with dynamic SQL you should use parameterised statements for many reasons, and one is exactly that it is simpler.

    The way you run the query is this:

    EXEC sp_executesql @sql, N'@tzoffset smallint, @StartDate datetime, @EndDate datetime',

    @tzoffset, @StartDate, @EndDate

    You can read more about sp_executesql in my article on dynamic SQL:

    http://www.sommarskog.se/dynamic_sql.html#sp_executesql

    By the way, I think a better solution is

    SET @sql = 'SELECT * FROM <sometable>

    WHERE END_DATETIME BETWEEN dateadd(hh, -@tzOffset, @StartDate) AND dateadd(hh, -@tzOffset, @EndDate'

    While longer, the first solution runs the risk that the optimzer will not use any index on END_DATETIME.

    [font="Times New Roman"]Erland Sommarskog, SQL Server MVP, www.sommarskog.se[/font]