我怎樣才能想出一個存儲過程來選擇過去30天的結果?查找前x天的記錄嗎?
where MONTH(RequestDate) > 6 and DAY(RequestDate) >= 10
and MONTH(RequestDate) < 21 and DAY(RequestDate) < 7
我怎樣才能想出一個存儲過程來選擇過去30天的結果?查找前x天的記錄嗎?
where MONTH(RequestDate) > 6 and DAY(RequestDate) >= 10
and MONTH(RequestDate) < 21 and DAY(RequestDate) < 7
是這樣的嗎?
CREATE PROC GetSomeHistory
@NumDaysPrevious int
AS
BEGIN
SELECT * FROM MyTable
WHERE RequestDate BETWEEN DATEADD(dd, -1 * @NumDaysPrevious, getdate())
AND getdate();
END
......
EXEC GetSomeHistory 55;
您是否在尋找過去的30天或上個月?要了解啓動和每個月的月底(「通用」爲您的評論說),用途:
select dateadd(month,datediff(month,0,getdate()),0),
dateadd(mm,datediff(mm,-1,getdate()),-1)
SELECT *
FROM Table
WHERE myDate >= DATEADD(MONTH, -1, GETDATE())
每月做起來比在30天的模塊做不同的。測試此列如下......
declare @mydate smalldatetime
set @mydate = '07/6/01'
select @mydate
select DATEADD(month, 2, @mydate), DATEDIFF(day, DATEADD(month, 2, @mydate), @mydate)
select DATEADD(month, 1, @mydate), DATEDIFF(day, DATEADD(month, 1, @mydate), @mydate)
select DATEADD(month, -1, @mydate), DATEDIFF(day, DATEADD(month, -1, @mydate), @mydate)
select DATEADD(month, -2, @mydate), DATEDIFF(day, DATEADD(month, -2, @mydate), @mydate)
select DATEADD(month, -3, @mydate), DATEDIFF(day, DATEADD(month, -3, @mydate), @mydate)
下面是結果:
2001-07-06 00:00:00
2001-09-06 00:00:00 | -62
2001-08-06 00:00:00 | -31
2001-06-06 00:00:00 | 30
2001-06-06 00:00:00 | 30
2001-05-06 00:00:00 | 61
2001-04-06 00:00:00 | 91
天數只,但肯定的。 – dexter