2011-06-14 48 views
2

我工作的一个存储过程,需要历时9个月的数据。需要一个语法,它会自动删除,当新数据将被添加到表中的最早的数据(最新9个月数据)。如何让过去的9个月的数据?

这句法会在选择语法中使用。

我用

select * from tablename t 
left outer join calendartable r on 
t.fiscal_month=r.fiscal_month 
where t.date > dateadd(m,-9,date) 

我知道这是错误的。你能帮我解决这个问题吗?

感谢

+0

通常,使用代码标签格式化代码并包含表结构的想法是一个好主意。 – JNK 2011-06-14 15:41:40

+0

我知道它容易让你们也为更好地理解.. – Shahsra 2011-06-14 15:44:53

+0

小的修改我的问题,如果我们有一个日期,然后回答以下问题,将工作。但是如果我们有[Fiscal_Month]而不是[Date],那么呢? [Fiscal_Month]的例子就像这个'2012M03','2011M05'等,然后dateadd(m,-9,date)语法不会在那里工作..我们还能做什么? – Shahsra 2011-06-14 18:17:23

回答

5

你可能想GETDATE从现在开始计算九个月边界:

where t.date >= dateadd(m,-9, GETDATE()) 

请注意,如果t.date是日期和时间字段不只是约会,你会看到奇怪的行为在九个月的边界上,除非你也在比较之前舍弃了时间。

或者,如果你比较它与另一个值如插入的记录在你的触发器中的日期,那么你得到的可能是好的,例如,像

declare @latest date 
select @latest = inserted.date 
delete from ... where t.date < dateadd(m, -9, @latest) 

虽然我建议你居然归档关数据,而不是将其删除。


既然你已经明确你想要整整两个月,即从上月底9个月,你可以使用

declare @today date; 
declare @firstOfMonth date; 
declare @nineMonthsAgo date; 
set @today = GETDATE(); 
set @firstOfMonth = DATEADD(d, 1-DAY(@today), @today); 
set @nineMonthsAgo = DATEADD(m, -9, @firstOfMonth); 

... WHERE date >= @nineMonthsAgo AND date < @firstOfMonth 
+0

+1打我吧... – Moose 2011-06-14 15:45:59

+0

感谢您的回复...我看到你已经把getdate()置于顶端..如果我们需要从今天的日期数据是好事..如果我们想要数据上个月2011年5月31日.. – Shahsra 2011-06-14 16:09:53

1

好像它是相当接近。你现在需要9个月还是9个月?

怎么样:

declare @date datetime 

set @date = dateadd(m, -9, getdate()) -- 9 months from right now 

select * 
from tablename t 
    left outer join calendartable r 
    on t.fiscal_month=r.fiscal_month 
where t.date > @date 
+0

表中的数据在每个月的15号上传,我需要从上个月末抽取显示9个月的数据。假设今天是06/14/11,并且明天数据将要上传,他们需要从2010年9月1日至2011年5月31日的数据。希望您现在了解我的问题。 – Shahsra 2011-06-14 16:07:25

1

如果您需要删除数据时,添加新数据,你需要做一个触发器。触发器内的sintax就是这样的。

DELETE t 
FROM 
tablename t 
left outer join calendartable r on 
t.fiscal_month=r.fiscal_month 
where datediff(month, t.date, GETDATE()) > 9 

和SELECT来检索您的数据将是相似的。

select * from tablename t 
left outer join calendartable r on 
t.fiscal_month=r.fiscal_month 
where datediff(month, t.date, GETDATE()) < 9