2

我正在运行一些动态 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+''')
4

1 回答 1

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 '
于 2013-04-09T15:43:26.183 回答