SqlServer Function 实例
① sql server function 创建
这里使用一个计算年龄精确到分的function作为一个demo,
create Function [dbo].[fn_GetAge]
(
@BIRTHDAY DateTime ,
@MATH_DATEE DateTime
) returns Varchar(20)
Begin
DECLARE
@n_minute decimal(10,0),
@n_Hour decimal(10,0) ,
@n_Days decimal(10,0) ,
@n_Months decimal(10,0) ,
@n_Years decimal(10,0),
@v_Return Varchar(20)
set @n_Years =datediff(YEAR,@BIRTHDAY,@MATH_DATEE) ;
set @n_Months = datediff(MONTH,@BIRTHDAY,@MATH_DATEE) ;
set @n_Days =datediff(DAY,@BIRTHDAY,@MATH_DATEE) ;
set @n_Hour =datediff(HOUR,@BIRTHDAY,@MATH_DATEE) ;
set @n_minute = datediff(MINUTE,@BIRTHDAY,@MATH_DATEE) ;
set @v_Return='0';
IF @n_Years = 0
BEGIN
IF @n_Months = 0
BEGIN
IF @n_Days = 0
BEGIN
IF @n_Hour = 0
BEGIN
set @v_Return = convert(varchar(20),@n_minute) + '分';
END
ELSE
BEGIN
set @v_Return = convert(varchar(20),@n_Hour) + '小时';
END
END
ELSE
BEGIN
set @v_Return = convert(varchar(20),@n_Days) + '天';
END
END
ELSE
BEGIN
set @v_Return = convert(varchar(20),@n_Months) + '月';
END
END
ELSE
BEGIN
set @v_Return = convert(varchar(20),@n_Years) + '岁';
END
Return @v_Return;
End;
GO
② sql server function 使用
select dbo.fn_GetAge('2012-04-25 03:00:00.000','2012-04-25 06:42:00.000') as 年龄
结果:
直如弦,死道边;曲如钩,反封侯