to_date 在 sql 服务器 2008 中不工作

to_date not working in sql server 2008

我遇到错误,我正在使用 SQL Server 2008

select * from  where rd_date between 
to_date('2018-17-05 00:00:00') and  to_date('2018-06-06 00:00:00')

当我执行时,出现以下错误

Msg 195, Level 15, State 10, Line 68 'to_date' is not a recognized built-in function name.

To_date 不是 sql 服务器中的函数:您可以在下面尝试

 select * from where rd_date between cast('2018-17-05 00:00:00' as date) and cast('2018-06-06 00:00:00' as date)

SELECT select * from where rd_date between CONVERT(DATETIME, '2018-17-05 00:00:00', 102) and CONVERT(DATETIME,'2018-06-06 00:00:00')

TRY_CONVERT 自 SQL Server 2012 起可用(returns 如果转换失败则为 NULL)

SELECT select * from where rd_date between TRY_CONVERT(DATETIME, '2018-17-05 00:00:00', 102) and TRY_CONVERT(DATETIME,'2018-06-06 00:00:00')

您的格式非常自定义,CONVERT 函数不支持(您可以将其用于某些特定的日期格式,如其他答案中所述)。因此,你需要做一些字符串操作来得到正确的格式,可以被SQL识别。尝试以下查询:

select cast(
           substring(col,1,5) + substring(col,9,2) + substring(col,5,3) + substring(col, 11, 20)
       as datetime)
from (values('2018-17-05 00:00:00'),('2018-06-06 00:00:00')) a(col)

@MSM,试试这个。请将 TABLENAME 替换为您正在查询的实际 table。您不需要 'to_date',因为您可能尚未定义该函数。

SELECT * 
FROM
  TABLENAME
where rd_date between CAST('20180517 10:35:21.177' AS DATE)  AND CAST('20180606 10:35:21.177' as DATE)

阅读其他答案可能不是个好主意,但我总是将硬编码日期简单地写成 'yyyy-mm-dd' 字符串,我对此总是很满意。
在您的示例中:

select * from  where rd_date between '2018-17-05' and  '2018-06-06'

现在我绝不会在这种情况下使用 Between,而是使用 >=<,当您的字段可能包含时间部分时,它们会更加清晰。