在查询中有一些错误:RequestError:转换date和/或时间从string转换失败

我正在使用MS SQL Server 2008时,我运行此查询

select top 1 * from table_name where ModifiedDate='Wed Mar 16 2016 15:52:20 GMT+0530 (IST)' 

我得到这个错误

 there were some errors in the query: RequestError: Conversion failed when converting date and/or time from character string. 

我也试过CASTCONVERT但是有同样的错误

我正在使用节点mssql客户端

要直接回答这个问题,请使用下面的代码:

 select top 1 * from table_name where ModifiedDate=cast('2016-03-16 15:52:20 +05:30' as datetimeoffset) 

现在的解释。 要使用时区,您需要使用datetimeoffset – 常规的date时间字段不包括时区信息。 所以,这将工作:

 select cast('2016-7-16 15:52:20 +05:30' as datetimeoffset) 

使用AdventureWorks2012(这个语法也可以在sql 2008中工作,但是这是演示如何写AW2012数据库的这个查询):

 select top 1 * from Person.Address where ModifiedDate=cast('2002-01-04 00:00:00 +00:00' as datetimeoffset) 

请注意,在这种情况下,AW2012使用date时间字段,但不在此表中使用datetimeoffset字段 – 但是,它编译并运行。

下一个示例演示了时区偏移量的工作方式:

 select top 1 * from Person.Address where ModifiedDate=cast('2002-01-04 04:00:00 +04:00' as datetimeoffset) 

这将返回一个值,而将偏移量更改为1小时则不会返回结果。 (表格中有一个ModifiedDate为2002-01-04 00:00:00的logging):

 select top 1 * from Person.Address where ModifiedDate=cast('2002-01-04 04:00:00 +03:00' as datetimeoffset)