2013-04-09 119 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

相關問題