MYSQL 自定义函数(if else)

IF OBJECT_ID('dbo.GetDateDiff', 'FN') IS NOT NULL OR OBJECT_ID('dbo.GetDateDiff', 'TF') IS NOT NULL OR OBJECT_ID('dbo.GetDateDiff', 'IF') IS NOT NULL DROP FUNCTION dbo.GetDateDiff     //判断此函数是否存在,若存在,删除,不存在,重建
GO

create function GetDateDiff(@start varchar(200),@end varchar(200),@t_start varchar(200),@t_end varchar(200))
returns @d table(time varchar(20))                                           //建立临时表,returns确定返回值类型
as                                                                                                 //函数写在begin,end 中
begin                                                                                          

declare @result int,@Max varchar(200),@Min varchar(200)               //定义变量
if(DATEDIFF(day,@start,@t_start)>0)                                                 //判断两个时间的大小
      set  @Max=@t_start
      else
       set  @Max=@start
       
       if(DATEDIFF(day,@end,@t_end)>0)
      set  @Min=@end
      else
       set  @Min=@t_end


 if(DATEDIFF(day,@t_start,@end) <0)
  set  @result=0
 else if(@end is not null)
      set  @result=DATEDIFF(day,@Max,@Min)                                    //返回两个时间的差值
 else
      set  @result=DATEDIFF(day,@Max,@t_end)

insert into @d(time) values (@result)                                                    //结果插入表中
return
end
GO

COMMIT

GO



select * from gEtdatediff('2015-02-12',null,'2013-03-24','2015-05-24')          //调用此函数

你可能感兴趣的:(mysql)