从字符串动态sql转换日期和/或时间时转换失败

时间:2013-04-09 15:37:47

标签: sql sql-server-2008 dynamic

我有一些动态SQL我正在运行,当我手动写入变量时工作正常,但是一旦我将它们从手动写入实际变量,我得到上面的错误

代码是:

set @query = 'SELECT eng, ' + @colsNull + ' 
        from 
        (
            select eng, [count], cast(weekof as date) weekof
            from dbo.RPT_ENG_WEEK (''1 jan 2013'', ''9 apr 2013'', ''1 jan 2013'', ''9 apr 2013'')
        ) x
        pivot 
        (
            sum([count])
            for weekof in (' + @cols + ')
        ) p '

哪个工作正常,但一旦我将其更改为

set @query = 'SELECT eng, ' + @colsNull + ' 
        from 
        (
            select eng, [count], cast(weekof as date) weekof
            from dbo.RPT_ENG_WEEK ('+@from+', '+@to+', '+@start+', '+@end+')
        ) x
        pivot 
        (
            sum([count])
            for weekof in (' + @cols + ')
        ) p '

我收到错误。我也试过了

set @query = 'SELECT eng, ' + @colsNull + ' 
        from 
        (
            select eng, [count], cast(weekof as date) weekof
            from dbo.RPT_ENG_WEEK ((select CONVERT(DATE'+@from+',105)), (select CONVERT(DATE'+@to+',105)), (select CONVERT(DATE'+@start+',105)), (select CONVERT(DATE'+@end+',105)))
        ) x
        pivot 
        (
            sum([count])
            for weekof in (' + @cols + ')
        ) p '

但无济于事!

还试过

from dbo.RPT_ENG_WEEK ((select CONVERT(DATE'''+@from+''',105)), (select CONVERT(DATE'''+@to+''',105)), (select CONVERT(DATE'''+@start+''',105)), (select CONVERT(DATE'''+@end+''',105)))

from dbo.RPT_ENG_WEEK ('''+@from+''', '''+@to+''', '''+@start+''', '''+@end+''')

1 个答案:

答案 0 :(得分:2)

如果@from是这样的字符串:1 jan 2013

如果更改此位会发生什么:

from dbo.RPT_ENG_WEEK ('+@from+', '+@to+', '+@start+', '+@end+')

到此:

from dbo.RPT_ENG_WEEK ('''+@from+''', '''+@to+''', '''+@start+''', '''+@end+''')

每个位置都有三个单引号。

如果@from是DATETIME,您需要的格式为'd mmm yyyy',那么您可以针对每个日期尝试此操作:

CONVERT(VARCHAR, @from, 106)

所以整件事情就这样结束了:

set @query = 'SELECT eng, ' + @colsNull + ' 
        from 
        (
            select eng, [count], cast(weekof as date) weekof
            from dbo.RPT_ENG_WEEK (''' + CONVERT(VARCHAR, @from, 106) + ''', ''' + CONVERT(VARCHAR, @to, 106) + ''', ''' + CONVERT(VARCHAR, @start, 106) + ''')
        ) x
        pivot 
        (
            sum([count])
            for weekof in (' + @cols + ')
        ) p '