create function [dbo].[GetYearMonthDayFun](
@begin datetime ,
@end datetime)
returns varchar(50)
as
begin
/*
* 功能:计算两个日期之差 *
* 描述:返回年月日,结果精确到天,参数为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
sql计算时间差
最新推荐文章于 2024-08-09 11:10:24 发布