我用Google搜索,但没有发现任何符合我案例的内容。
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。其余的解决方案运行良好,直到我将日期时间付诸实践。
答案 0 :(得分: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)
'
答案 1 :(得分:0)
我不确定,但我猜您已将附加撇号(')附加到@from_
和@to_
SET @from = CAST('''+@from_+''' AS datetime)
SET @to = CAST('''+@to_+''' AS datetime)
另外,为什么不直接设置像这样的值
SET @from = @from_
SET @to = @to_
答案 2 :(得分: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