数据类型varchar和datetimeoffset在add运算符中不兼容

时间:2013-09-13 09:10:37

标签: sql sql-server

当我尝试在我的SQL语句中使用动态查询代码时

Declare @Start datetimeoffset;
Declare @End datetimeoffset;
Declare @SqlCommand nvarchar(Max);

Set @Start = '2013-05-17 10:00:04.500 +00:00';
Set @End = '2013-09-17 10:00:04.500 +00:00'
Set @SqlCommand = 'Select * from Test where TimeLine > '+ @Start+' AND TimeLine < '+@End

Exec(@SqlCommand)

我收到消息说

  

Msg 402,Level 16,State 1,Line 8
  数据类型varchar和datetimeoffset在add运算符中不兼容。

请指导我正确使用。

2 个答案:

答案 0 :(得分:4)

您需要将DateTimeOffset值强制转换为varchars。 此外,您缺少其他报价。

这样的东西
Declare @Start datetimeoffset = '2013-05-17 10:00:04.500 +00:00'
Declare @End datetimeoffset = '2013-09-17 10:00:04.500 +00:00'
Declare @SqlCommand nvarchar(Max)

Set @SqlCommand = 'Select * from Test where SampleTime > '''+ CAST(@Start AS VARCHAR(50))+''' AND SampleTime < '''+CAST(@End AS VARCHAR(50)) + ''''

SELECT @SqlCommand

SQL Fiddle DEMO

答案 1 :(得分:0)

您应该添加'',如下所示,并将@Start / @End投射到varchar

Declare @Start datetimeoffset;
Declare @End datetimeoffset;
Declare @SqlCommand nvarchar(Max);

Set @Start = '2013-05-17 10:00:04.500 +00:00';
Set @End = '2013-09-17 10:00:04.500 +00:00'
Set @SqlCommand = 'Select * from Test where SampleTime > '''+ cast(@Start as varchar(100))+''' AND SampleTime < '''+cast(@End as varchar(100))+''' '

Exec(@SqlCommand)