如何在2字符串日期之间使用命令

时间:2016-06-06 08:08:26

标签: sql sql-server sql-server-2008

我正在使用以下选择查询,但问题是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

输出:

enter image description here

2 个答案:

答案 0 :(得分:3)

使用CONVERTIssueDate投射到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