自己一個人在家,沒什麼事情做,突然想起很久沒有寫東西了,於是.............
經常在對兩個日期計算時,不僅想得到單獨的年月日,想得到其詳細信息,即將日期結果精確到天,下面上一個function和一個procedure 用於完成這個功能。
第一個函數版
create function [dbo].[GetYearMonthDayFun](
@begin datetime ,
@end datetime)
returns varchar(50)
as
begin
/*
* 功能:計算兩個日期之差 *
* 作者:charry0110 *
* 描述:返回年月日,結果精確到天,參數為getdate()時計算出生信息*
*/
declare @Ageyear int
declare @Agemonth int
declare @Ageday int
set @Ageyear =datediff(year, @begin, @end)-
case when dateadd(year, datediff(year, @begin, @end), @begin)> @end
then 1 else 0 end
set @Agemonth=ltrim(datediff(month, @begin, @end)-
case when dateadd(month,datediff(month, @begin, @end),@begin)> @end
then 1 else 0 end)-12*@Ageyear
if(day(@begin)<day(@end) or day(@begin)=day(@end))
set @Ageday=day(@end)-day(@begin)
else
set @Ageday=datediff(day,(ltrim(year(@end))+'-'
+ltrim(month(dateadd(mm,-1,@end)))+'-'+ltrim(day(@begin))),
(ltrim(year(@end))+'-'+ltrim(month(@end))+'-'+ltrim(day(@end))))
return ltrim(@Ageyear)+'年'+ltrim(@Agemonth)+'月'+ltrim(@Ageday)+'天'
/*
--示例1
select dbo.GetYearMonthDayFun('2008-6-21',getdate())
--示例2
select dbo.GetYearMonthDayFun(crdate,refdate) from sysobjects
--示例3
select dbo.GetYearMonthDayFun(crdate,getdate()) from sysobjects
*/
end
第二個存儲過程版
create procedure [dbo].[GetYearMonthDayPro]
(
@begin datetime ,
@end datetime
)
as
begin
/*
* 功能:計算兩個日期之差 *
* 作者:charry0110 *
* 描述:返回年月日,結果精確到天,參數為getdate()時計算出生信息*
*/
declare @Ageyear int
declare @Agemonth int
declare @Ageday int
set @Ageyear =datediff(year, @begin, @end)-
case when dateadd(year, datediff(year, @begin, @end), @begin)> @end
then 1 else 0 end
set @Agemonth=ltrim(datediff(month, @begin, @end)-
case when dateadd(month,datediff(month, @begin, @end),@begin)> @end
then 1 else 0 end)-12*@Ageyear
if(day(@begin)<day(@end) or day(@begin)=day(@end))
set @Ageday=day(@end)-day(@begin)
else
set @Ageday=datediff(day,(ltrim(year(@end))+'-'
+ltrim(month(dateadd(mm,-1,@end)))+'-'+ltrim(day(@begin))),
(ltrim(year(@end))+'-'+ltrim(month(@end))+'-'+ltrim(day(@end))))
select ltrim(@Ageyear)+'年'+ltrim(@Agemonth)+'月'+ltrim(@Ageday)+'天'
/*
--示例1
exec GetYearMonthDayPro '2008-6-21','2008-7-21'
*/
end