2013-04-09 140 views
2

我有一点动态SQL我运行的工作正常,当我手动写入变量,但只要我改变它们从手动写入到实际变量,我得到上面的错误。从字符串动态转换日期和/或时间时转换失败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 ('[email protected]+', '[email protected]+', '[email protected]+', '[email protected]+') 
     ) 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'[email protected]+',105)), (select CONVERT(DATE'[email protected]+',105)), (select CONVERT(DATE'[email protected]+',105)), (select CONVERT(DATE'[email protected]+',105))) 
     ) x 
     pivot 
     (
      sum([count]) 
      for weekof in (' + @cols + ') 
     ) p ' 

但无济于事!

也曾尝试

from dbo.RPT_ENG_WEEK ((select CONVERT(DATE'''[email protected]+''',105)), (select CONVERT(DATE'''[email protected]+''',105)), (select CONVERT(DATE'''[email protected]+''',105)), (select CONVERT(DATE'''[email protected]+''',105))) 

from dbo.RPT_ENG_WEEK ('''[email protected]+''', '''[email protected]+''', '''[email protected]+''', '''[email protected]+''') 
+0

不这个位上有足够多的单引号'from dbo.RPT_ENG_WEEK('+ @ from +','+ @ to +','+ @ start +','+ @ end +')'我想。 – 2013-04-09 15:40:03

+0

@Dommer是不是我放在中间代码块? – franglais 2013-04-09 15:42:08

+0

我现在也试过 from dbo.RPT_ENG_WEEK('''+ @ from +''','''+ @ to +''','''+ @ start +''','''+ @ end +' '') 但没有快乐! – franglais 2013-04-09 15:43:41

回答

2

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

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

from dbo.RPT_ENG_WEEK ('[email protected]+', '[email protected]+', '[email protected]+', '[email protected]+') 

对此:

from dbo.RPT_ENG_WEEK ('''[email protected]+''', '''[email protected]+''', '''[email protected]+''', '''[email protected]+''') 

这是三个单引号在每个位置。

如果@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 ' 
+0

仍然出现错误!哦,动态SQL的乐趣...:D – franglais 2013-04-09 15:45:32

+0

所以'从dbo.RPT_ENG_WEEK(CONVERT(VARCHAR,('''+ @ from +''',106)'etc? – franglais 2013-04-09 15:55:04

+0

不,请看最新的编辑。 – 2013-04-09 15:59:37

相关问题