Why dateadd() creating problem

  • declare @sec varchar(3), @timeStyle varchar(3)

    set @sec = '60'

    set @timeStyle = '108'

    declare @query nvarchar(200)

    set @query =

    'select CONVERT (VARCHAR(10), DATEADD(S, '+@sec+', ''01-01-2000''), '+@timeStyle+') AS DURATION'

    print @query

    exec @query

    TakeCare,

    Bue!!


    TakeCare,
    Bue!!

  • your last statement needs to be:

    exec (@query)

    Cheers,

    - Mark


    Cheers,
    - Mark

  • Am I missing something or is the question that the query doesn't run because the exec is stated incorrectly? When I run the code, admittedly with my exec stated correctly, I get the result I would expect, 00:01:00

  • Hi Buell,

    I think, although your question seems to be answered, if your statement needs to be run dynamically you might want to consider NOT to use EXEC @query, but rather EXEC sp_executesql @query.

    Not only that Microsoft prefer this over EXECUTE, but you'll get a higher probability that execution plans can be reused.

    However, results are the same!

    Cheers,

    Frank

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • Mark's, ur answer did work.

    Frank's, ur answer does work even without the (). And since its a recommended. I'm using it finally.

    Honest 'Thax' for all support.

    TakeCare,

    Bue!!


    TakeCare,
    Bue!!

  • But does, 'Insert into '+@addDate+'' work with my above EXEC sp_executesql @query.

    I defined the @addDate as

    DECLARE @addDate table (dated varchar(12))

    TakeCare,

    Bue!!


    TakeCare,
    Bue!!

  • quote:


    But does, 'Insert into '+@addDate+'' work with my above EXEC sp_executesql @query.

    I defined the @addDate as

    DECLARE @addDate table (dated varchar(12))


    No, sp_executesql will be outside the scope of the current procedures scope, so the table variable won't exist inside the sp_executesql scope...same with temp tables. You can circumvent this problem by using a global scope temp table (i.e. ##MyTable), and then you can access it in both the outer procedure scope and the inner (sp_executesql) scope.

Viewing 8 posts - 1 through 7 (of 7 total)

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