问题描述
以下是我在 chinook DB 上尝试的查询,但出现此错误。请帮助我如何解决这个问题? 错误 ==> 'datetime' 不是可识别的内置函数名称。
select count(i.invoiceid),sum(i.total)
from invoice as i
where i.invoicedate between datetime('2011-01-01 00:00:00') and datetime('2011-12-31 00:00:00'
解决方法
SQL Server 自动将“正确”格式的字符串转换为 datetime
s:
where i.invoicedate between '2011-01-01T00:00:00') and '2011-12-31T00:00:00'
这是 datetime
文档中的 explained。
它还自动将“正确”格式的字符串转换为 date
s:
where i.invoicedate between '20110101' and '20111231'
对于除 1 之外的几乎所有国际化设置,它还接受 date
的连字符:
where i.invoicedate between '2011-01-01' and '2011-12-31'
出于可读性和 ISO 8601 合规性,我个人更喜欢连字符。其他人不喜欢使用连字符,因为这是 SQL Server 标准。这确实是个人喜好。
如果您真的想具体一点,也可以使用 convert()
:
where i.invoicedate between convert(date,'2011-01-01',120) and convert(date,'2011-12-31',120)
在您的上下文中,您似乎只需要日期。但是,您还暗示 invoicedate
确实是 datetime
。那么你应该小心时间组件。 我的建议是在日期/时间值上避免使用 between
。
所以,我怀疑你真的打算:
where i.invoicedate >= '2011-01-01') and
i.invoicedate < '2012-01-01'
这将包括 2011 年 12 月 31 日发送的所有发票 -- 这适用于 date
和 datetime
值。