查询不返回正确的记录

时间:2012-02-14 15:23:42

标签: sql sql-server-2008

您好我有这个代码我想修复,问题是当我在同一年内传递一个参数时说

startDate = 01/01/2011  EndDate 07/01/2011

它的工作原理是返回正确的数据,但问题是当我尝试在不同的年份使用它时,比如说

startDate = 02/01/2011 EndDate 01/25/2012   
--(wont work shows blank all thought there is data in both years).

这是我的sql代码

ALTER PROCEDURE [dbo].[GetOrderByDateRange]
    @startDate nvarchar(50),
    @endDate nvarchar(50)
AS
BEGIN
    DECLARE @days varchar(100)
    set @days = DATEDIFF(d, @StartDate, DATEADD(day,+1,@EndDate)) 

    SELECT distinct(CONVERT(char(10), OrdDate, 101)) as OrdDate,
    COUNT(PurchaseId) as OrdCount,
    SUM(Total) as OrdTotals,
    AVG(Total) as AvgOrdAmount,
    SUM(SubTotal) as Net,
    @days as 'Days'
    FROM [PurchaseOrders]
    WHERE CONVERT(char(10), OrdDate, 101) >= @startDate 
      AND CONVERT(char(10), OrdDate, 101) <= @endDate
    GROUP BY CONVERT(char(10), OrdDate, 101) 
END

GO

2 个答案:

答案 0 :(得分:2)

不要使用CONVERT ...假设OrdDate是DATETIME列,它应该是:

CREATE PROCEDURE dbo.GetOrderByDateRange
    @StartDate DATE, -- pass 'yyyy-mm-dd' format
    @EndDate   DATE
AS
BEGIN
    SET NOCOUNT ON;
...
    WHERE OrdDate >= @startDate AND OrdDate < DATEADD(DAY, 1, @endDate)
END
GO

答案 1 :(得分:0)

尝试将日期格式转换为标准yyyy-MM-dd

希望这是有帮助的