1

我用谷歌搜索并没有找到任何与我的情况相匹配的东西。

declare @from_ datetime, @to_ datetime
SET @from_ = '2013-01-01' 
SET @to_ = '2013-10-01' 

DECLARE @query NVARCHAR(4000) 
SET @query = N'
DECLARE @from datetime, @to datetime
SET @from = CAST('''+@from_+''' AS datetime)
SET @to = CAST('''+@to_+''' AS datetime)
'

给出错误:

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

SET @query = N'34号线

我也试过有CONVERT(datetime, '+@from_+', 102)和没有, 102)'''

并且只有

SET @from = CAST('+@from_+' AS datetime)

结果相同

解决方案是 PIVOT 的一部分,所以我有声明、选择、透视和执行 @query。解决方案的其余部分运行良好,直到我开始使用日期时间。

4

3 回答 3

2

您的问题是您正在使用 varchar 添加日期时间。试试这个:

declare @from_ char(8), @to_ char(8)
SET @from_ = '20130101' 
SET @to_ = '20131001' 

DECLARE @query NVARCHAR(4000) 
SET @query = N'
DECLARE @from datetime, @to datetime
SET @from = CAST('''+@from_+''' AS datetime)
SET @to = CAST('''+@to_+''' AS datetime)
'
于 2013-10-30T08:54:38.663 回答
0

我不确定,但我猜您已将撇号(')附加到@from_@to_

SET @from = CAST('''+@from_+''' AS datetime)
SET @to = CAST('''+@to_+''' AS datetime)

另外你为什么不直接设置这样的值

SET @from = @from_
SET @to = @to_
于 2013-10-30T08:49:32.637 回答
0

像这样试试

declare @from_ NVARCHAR(50), @to_ NVARCHAR(50)
SET @from_ = '2013-01-01' 
SET @to_ = '2013-10-01' 

DECLARE @query NVARCHAR(4000) 
SET @query = N'
DECLARE @from datetime, @to datetime
SET @from = CAST('''+@from_+''' AS datetime)
SET @to = CAST('''+@to_+''' AS datetime)'
EXEC SP_EXECUTESQL @query
于 2013-10-30T09:00:17.670 回答