我正在使用以下选择查询,但问题是IssueDate
列位于varchar
且未提供正确的结果。在SQL中命令字符串日期之间是否有任何使用方法:
SELECT Pkid AS [Bill Id],
InvoiceNumber,
InvoiceType,
IssueDate,
FinalTotal
FROM tblInvoiceMain
WHERE IssueDate BETWEEN '01 June 2016' AND '06 June 2016'
ORDER BY Pkid DESC
输出:
答案 0 :(得分:3)
使用CONVERT
将IssueDate
投射到DATE
类型。此外,使用日期常量时,请使用YYYYMMDD
格式。
SELECT
Pkid AS [Bill Id], InvoiceNumber, InvoiceType, IssueDate, FinalTotal
FROM tblInvoiceMain
WHERE
CONVERT(DATE, IssueDate, 106) BETWEEN CAST('20160601' AS DATE) AND CAST('20160606' AS DATE)
ORDER BY Pkid DESC
但是,如果您在IssueDate
上有索引,则会阻止使用它。我的建议是修复您的架构并使用正确的数据类型来存储您的值。
答案 1 :(得分:3)
SELECT Pkid AS [Bill Id],
InvoiceNumber,
InvoiceType,
IssueDate,
FinalTotal
FROM tblInvoiceMain
WHERE CAST(IssueDate AS DATE) BETWEEN '20160601' AND '20160606'
ORDER BY Pkid DESC
如果执行时间非常长:
ALTER TABLE dbo.tblInvoiceMain
ADD IssueDate2 AS CAST(IssueDate AS DATE)
GO
CREATE NONCLUSTERED INDEX ix
ON dbo.tblInvoiceMain (IssueDate2)
INCLUDE (Pkid, InvoiceNumber, InvoiceType, IssueDate, FinalTotal)
GO
SELECT Pkid AS [Bill Id],
InvoiceNumber,
InvoiceType,
IssueDate,
FinalTotal
FROM tblInvoiceMain
WHERE IssueDate2 BETWEEN '20160601' AND '20160606'
ORDER BY Pkid DESC