SQL server计算两个日期相差多少年,多少月,多少日。
1 CREATE PROCEDURE [dbo].[Getdatediff] 2 @fromdate nvarchar(10), 3 @todate nvarchar(10) 4 as 5 DECLARE @yeardiff 6 INTEGER DECLARE @monthdiff 7 INTEGER DECLARE @daydiff 8 INTEGER DECLARE @tomonth 9 INTEGER DECLARE @fromday 10 INTEGER DECLARE @today 11 12 INTEGER SET @yeardiff= LTRIM(datediff(yy,@fromdate,@todate)) 13 SET @monthdiff= LTRIM(datediff(mm,@fromdate,@todate)%12) 14 SET @tomonth= MONTH(cast(@todate AS DATETIME)) 15 SET @fromday= DAY(cast(@fromdate AS DATETIME)) 16 SET @today= DAY(cast(@todate AS DATETIME)) 17 IF 18 (@today - @fromday)<0 19 BEGIN 20 21 IF 22 (@tomonth-1)=1 OR (@tomonth-1)=3 OR (@tomonth-1)=5 OR (@tomonth-1)=7 OR (@tomonth-1)=8 OR (@tomonth-1)=10 OR (@tomonth-1)=12 23 BEGIN 24 25 SET 26 @daydiff = 31 + @today - @fromday 27 SET 28 @monthdiff=@monthdiff-1 29 30 END 31 32 ELSE 33 34 BEGIN 35 36 SET 37 @daydiff=30+@today-@fromday 38 SET 39 @monthdiff=@monthdiff-1 40 END 41 42 END 43 44 ELSE 45 46 BEGIN 47 48 SET 49 50 @daydiff=@today-@fromday 51 52 END 53 54 SELECT CAST(@yeardiff AS NVARCHAR(10)) +'年'+ CAST(@monthdiff AS NVARCHAR(10))+'月'+ CAST(@daydiff AS NVARCHAR(10))+'日'