---
title: "存储过程实现 日期统计期间"
author: "cfeers"
date: "2011-05-05T16:44:38Z"
tags: ["Go"]
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2011-05-05T16:45:01Z"
id: 1030413
url: "https://cfeers.iteye.com/blog/1030413"
---

CREATE TABLE \[dbo].\[t\_kjqj] (  
 \[nf] \[numeric](4, 0) NOT NULL ,  
 \[yf] \[numeric](4, 0) NOT NULL ,  
 \[rq1] \[smalldatetime] NOT NULL ,  
 \[rq2] \[smalldatetime] NOT NULL ,  
 \[qybz] \[varchar] (1) COLLATE Chinese\_PRC\_CI\_AS NULL  
)

 

 

 

 

CREATE  PROCEDURE \[dbo].\[p\_newkjqj] AS  
declare  
 @li\_maxnf integer,  
 @li\_nf integer,  
 @li\_yf integer,  
 @ldt\_1 datetime,  
 @ldt\_2 datetime  
  select @li\_maxnf=max(nf) from t\_kjqj  
  select @li\_nf=@li\_maxnf+1,@li\_yf=1  
  select @ldt\_1=convert(datetime, convert(varchar(10),dateadd(day,1,rq2),111)) from t\_kjqj where [nf=@li\_maxnf](mailto:nf=@li_maxnf) and yf=12

  while @li\_yf &lt; 13  
  begin  
    select @ldt\_2=dateadd(day,-1,dateadd(month,1,@ldt\_1))  
    insert into t\_kjqj(nf,yf,rq1,rq2) values(@li\_nf,@li\_yf,@ldt\_1,@ldt\_2)  
    select @li\_yf=@li\_yf+1,@ldt\_1=dateadd(month,1,@ldt\_1)  
  end

GO

 

生成如下数据：

 2001 1 2001-1-1 2001-1-31 0  
 2001 2 2001-2-1 2001-2-28 0  
 2001 3 2001-3-1 2001-3-31 0  
 2001 4 2001-4-1 2001-4-30 0  
 2001 5 2001-5-1 2001-5-31 0  
 2001 6 2001-6-1 2001-6-30 0  
 2001 7 2001-7-1 2001-7-31 0  
 2001 8 2001-8-1 2001-8-31 0  
 2001 9 2001-9-1 2001-9-30 0  
 2001 10 2001-10-1 2001-10-31 0  
 2001 11 2001-11-1 2001-11-30 0  
 2001 12 2001-12-1 2001-12-31 0