1. 程式人生 > >sqlserver 算兩個日期間的月份數

sqlserver 算兩個日期間的月份數

create  FUNCTION f_GetRentalMonths_double(@StartDate DATETIME ,@EndDate DATE)  
RETURNS DECIMAL(10,4)    
AS  
BEGIN  
  DECLARE @DiffMonths  DECIMAL(10,4) ,
           @DiffDays INT ,
          @BuZuMonths  DECIMAL (10,4)
  SET @DiffMonths=CAST(0 AS DECIMAL(10,4))
  while(@EndDate>=DATEADD(DAY,-1,DATEADD
(MONTH,1,@StartDate))) begin SET @DiffMonths=@DiffMonths+CAST(1 AS DECIMAL(10,4)) SeT @StartDate=DATEADD(MONTH,1,@StartDate) end --不足月天數 SET @DiffDays = DATEDIFF(DAY,@StartDate,@EndDate) + 1 --不足月天數/月天數,得到月份數 SET @BuZuMonths=round( CAST(@DiffDays AS DECIMAL(10,2))/(CAST(365 AS DECIMAL(10,2
))/CASt(12 AS DECIMAL(10,2))),4) SET @DiffMonths=@DiffMonths+@BuZuMonths RETURN @DiffMonths END GO