Dynamic variable error

  • Not sure why is this working. Any help is appreciated.

    "Msg 241, Level 16, State 1, Line 8"
    Conversion failed when converting date and/or time from character string.


    declare @DateIndex datetime
    declare @sql1 varchar(max)
    declare @sql2 varchar(max)

    set @DateIndex ='2017-05-04 12:22:47.003'

    set @sql1='

    select @sql2=''SomeDate_''+CONVERT(VARCHAR(MAX),DATEPART(QUARTER, '+@DateIndex+'))'

    print @sql2

  • curious_sqldba - Friday, May 12, 2017 11:50 AM

    Not sure why is this working. Any help is appreciated.

    "Msg 241, Level 16, State 1, Line 8"
    Conversion failed when converting date and/or time from character string.


    declare @DateIndex datetime
    declare @sql1 varchar(max)
    declare @sql2 varchar(max)

    set @DateIndex ='2017-05-04 12:22:47.003'

    set @sql1='

    select @sql2=''SomeDate_''+CONVERT(VARCHAR(MAX),DATEPART(QUARTER, '+@DateIndex+'))'

    print @sql2

    1 - You need to convert your @DateIndex to a varchar in order to append it to the string.
    2 - You are trying to print @sql2, but only @sql1 is set.


    declare @DateIndex datetime
    declare @sql1 varchar(max)
    declare @sql2 varchar(max)

    set @DateIndex = '2017-05-04 12:22:47.003';

    set @sql1='select @sql2=''SomeDate_''+CONVERT(VARCHAR(2),DATEPART(QUARTER, '''+CONVERT(VARCHAR(23),@DateIndex)+'''))'

    print @sql1

  • Why do you need the dynamic SQL in variable @sql1 here?  Couldn't you just set @sql2 directly:


    ...
    SET
    @sql2='SomeDate_'+CONVERT(VARCHAR(MAX),DATEPART(QUARTER, @DateIndex))
    PRINT @sql2

Viewing 3 posts - 1 through 2 (of 2 total)

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