从字符串转换日期出错

时间:2014-05-19 15:47:31

标签: sql sql-server pivot-table

我试图做一个动态表,其中列数取决于日期范围。所以,我试图使用数据透视表。每次运行查询时,我都会收到此错误:

Msg 241, Level 16, State 1, Line 18
Conversion failed when converting date and/or time from character string.

这是查询(MSSQL):

DECLARE @StartDate AS DATETIME  
DECLARE @EndDate AS DATETIME  
DECLARE @Query NVARCHAR(MAX)  
DECLARE @Str_Dates NVARCHAR(MAX)  

SET @StartDate = '2014-05-01'
SET @EndDate = '2014-05-16'

SELECT  @Str_Dates = STUFF(( SELECT DISTINCT
                    '],[' + CONVERT(VARCHAR(10),CreateDate,111)
                    FROM myDB.dbo.SaleTransaction
                    WHERE CreateDate BETWEEN @StartDate AND @EndDate
                    ORDER BY 1 
                    FOR XML PATH('')
                    ), 1, 2, '') 
                    + ']'

SET @Query = 
'SELECT * FROM
(
SELECT CreateDate AS [DATE], ItemID, Description, SUM(Quantity) AS [QTY]
FROM myDB.dbo.SaleTransactionDetails
WHERE CreateDate BETWEEN '+@StartDate+' AND '+@EndDate+'
GROUP BY CreateDate, ItemID, Description
) tpvt     
PIVOT (SUM(tpvt.QDE) FOR tpvt.DATE
IN ('+@Str_Dates+')) AS pvt'

EXECUTE (@Query)  

如果我删除WHERE CreateDate BETWEEN '+@StartDate+' AND '+@EndDate+',则查询运行没有问题。因此,我尝试以多种方式使用CONVERT函数将变量转换为日期,但没有成功 知道我可以做些什么来使用这些变量并且没有错误吗?

3 个答案:

答案 0 :(得分:0)

试试这个:

SET @StartDate = convert(datetime,'2014-05-01')
SET @EndDate = convert(datetime,'2014-05-16')

答案 1 :(得分:0)

  1. 在TSQL中,日期/时间以字符串形式显示,字符串由单引号括起。

  2. 使用两个单引号来转义字符串中的单引号。

  3. 所以将代码修改为

    'WHERE CreateDate BETWEEN '''+@StartDate+''' AND '''+ @EndDate+ '''
    

答案 2 :(得分:0)

WHERE CreateDate BETWEEN '+@StartDate+'

您不能将(+)字符串连接到日期时间。

将其转换为动态SQL中的引用字符串:

'CreateDate BETWEEN ''' + CONVERT(VARCHAR(8), @StartDate, 112) + ''' AND ...