2015-06-22 61 views
0

我這種情況在存儲過程:TSQL - 在存儲過程中的錯誤,由於轉換失敗

SET @DATE_RELEASE_START = '2015-01-01'; 
SET @DATE_RELEASE_END = '2015-05-31' 

    SELECT @statement = ' SELECT * 
          FROM (SELECT AFCDENTE, M.ID_MODIFICATION_CODE, COUNT(*) AS Conteggio--, CAST((COUNT(*) * 100/ 15032) AS decimal(10,7)) AS Percentage 
           FROM CIC_LOG_MODIFICHE AS L INNER JOIN ADM_MODIFICATION_CODE AS M ON L.CD_MODIFICATION_CODE = M.CD_MODIFICATION_CODE 
                  INNER JOIN CIC_PRODUZIONE AS P ON P.CD_CIC_PRODUZIONE = L.CD_CIC_PRODUZIONE 
           WHERE AFDTMODI BETWEEN '[email protected]_RELEASE_START+' AND '[email protected]_RELEASE_END+' AND P.CD_PLANT = '[email protected]_PLANT+' AND AFCDENTE IS NOT NULL 
           GROUP BY AFCDENTE, M.ID_MODIFICATION_CODE) as tbl 
         PIVOT (SUM(tbl.Conteggio) for tbl.ID_MODIFICATION_CODE in (' + @columns + ')) as pvt' 

我得到這個錯誤:

Conversion failed when converting date and/or time from character string.

我試圖鑄造的日期,但沒有改變。我犯了同樣的錯誤。

我該怎麼辦?

回答

2

我會建議做這樣的:

SET @DATE_RELEASE_START = '2015-01-01'; 
SET @DATE_RELEASE_END = '2015-05-31' 

    SELECT @statement = ' SELECT * 
          FROM (SELECT AFCDENTE, M.ID_MODIFICATION_CODE, COUNT(*) AS Conteggio--, CAST((COUNT(*) * 100/ 15032) AS decimal(10,7)) AS Percentage 
           FROM CIC_LOG_MODIFICHE AS L INNER JOIN ADM_MODIFICATION_CODE AS M ON L.CD_MODIFICATION_CODE = M.CD_MODIFICATION_CODE 
                  INNER JOIN CIC_PRODUZIONE AS P ON P.CD_CIC_PRODUZIONE = L.CD_CIC_PRODUZIONE 
           WHERE AFDTMODI BETWEEN @p0 AND @p1 AND P.CD_PLANT = @p2 AND AFCDENTE IS NOT NULL 
           GROUP BY AFCDENTE, M.ID_MODIFICATION_CODE) as tbl 
         PIVOT (SUM(tbl.Conteggio) for tbl.ID_MODIFICATION_CODE in (' + @columns + ')) as pvt' 

EXECUTE sp_executesql @statement, N'@p0 DATETIME2, @p1 DATETIME2, @p0 NVARCHAR(1000)', @p0 = @DATE_RELEASE_START, @p1 = @DATE_RELEASE_END, @p2 = @CD_PLANT; 

相反鑄造他們爲VARCHAR,只是將它們作爲變量,然後用sp_executesql做正確的工作。

+0

哎呀!如果類型是'datetime'或者傳遞一個時間組件,則需要使用'YYYYMMDD'。 'YYYY-MM-DD'適用於'date'類型 –

+0

我使用'DATETIME2'並根據文檔支持'YYYY-MM-DD'。 https://msdn.microsoft.com/en-us/library/bb677335.aspx糾正我,如果我錯了。 –

+1

好工作。它的作品 – Galma88

2

你必須報日期字符串中的SQL代碼正確:

WHERE AFDTMODI BETWEEN '''[email protected]_RELEASE_START+''' AND '''[email protected]_RELEASE_END+''' 

否則SQL將讀取

WHERE AFDTMODI BETWEEN 2015-01-01 AND 2015-05-31 

,而不是

WHERE AFDTMODI BETWEEN '2015-01-01' AND '2015-05-31' 

我們已經在通過日期/時間之前也有問題值存儲到Management Studio中的存儲過程。我們需要將日期設爲2015010120150531

+0

我得到相同的錯誤 – Galma88

+0

@ Galma88添加到我的答案。 –

+1

你是如何通過它們的?在'declare @start date ='2015-12-31'中沒有不明確的地方,這會創建一個日期類型的變量和正確的日期。你把日期和日期混合在一起了嗎?在這種情況下,您必須指定完整的ISO日期時間或使用'YYYYMMDD'格式 –