TSQL - 转换失败导致存储过程出错

时间:2015-06-22 13:10:56

标签: sql-server sql-server-2008 tsql

我在存储过程中遇到这种情况:

NSDate *startDate = [self.dateFormatter dateFromString:@"31.05.2015"];
self.beginningValueLabel.text = [self.dateFormatter stringFromDate:startDate];

我收到此错误:

  

从字符转换日期和/或时间时转换失败   字符串。

我尝试了这些日期,但没有变化。我犯了同样的错误。

我该怎么办?

2 个答案:

答案 0 :(得分:2)

您必须正确引用SQL代码中的日期字符串:

WHERE AFDTMODI BETWEEN '''+@DATE_RELEASE_START+''' AND '''+@DATE_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

答案 1 :(得分: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来做正确的工作。