Dynamic SQL String

  • Hi,

    This statement fragment works in query analyzer:

    Age=DateDiff(d,CS.AdmSrvDate,GetDate())

    but when I try to add it to a dynamic sql string by appending it to @strsql in a stored procedure, like this:

    SET @strSQL = @strSQL + ' DateDiff(d,CS.AdmSrvDate, ' + GetDate() + ')'

    I get the error:

    Syntax error converting datetime from character string.

    Am I doing something wrong with the single quotes?

    Thank you!

  • Brenna, try

    SET @strSQL = @strSQL + ' DateDiff(d,CS.AdmSrvDate, + GetDate() + )'

    Just a couple less single quotes.

    HTH

  • Thanks!

    What if I want to use a variable in the DTS, for example, @RptDate, instead of GetDate()?

    Brenna

     

  • Since DATEDIFF returns an Integer value, SQL Server tries to cast your @strSQL also to an INT, because INT has a higher precedence. What about this?

    DECLARE @strSQL NVARCHAR(50)

    DECLARE @MyDate DATETIME

    Set @MyDAte=GETDATE()

    SET @strSQL= 'The Int value of today is: '

    PRINT @strSQL+ CAST(DateDiff(d,0,@MyDate) AS NVARCHAR(5))

    The Int value of today is: 38453

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

  • Why messing with dynamic SQL in the first place?

    What is the purpose of this exercise? Does it have to be dynamic?

    /Kenneth

  • The larger statement as a whole needs to be dynamic. I'm using a stored procedure as a datasource for a Crystal report.  The joins in the SQL statement need to change based on which parameters the user chooses at run time.  Is there a better way to do this?

    I want the datasource to include a column with the age of each account in days, from a given date (AdmSrvDate) to today.

  • Thank you, Frank!  This worked:

     

    SET @strSQL = @strSQL + ' CAST(DateDiff(d,CS.AdmSrvDate,  GetDate()) AS nvarchar(5))'

  • Ooops.  Forgot that I wanted to calculate age from @RptDate, not GetDate().

    This works:

    SET @strSQL = @strSQL + ' CAST(DateDiff(d,CS.AdmSrvDate, ' + '''' + CONVERT(varchar,@RptDate,101) +''''+ ') AS nvarchar(5)) END'

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

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