SQLServer自訂函數——fnDateInterval

來源:互聯網
上載者:User

/*************************************************************
** File: fnDateInterval.sql
** Name: fnDateInterval
** Description: Get the interval between the start date and the end date.
  Use the format as "Number Years and Number Months and Number Days" to express the interval
  取得兩個時間的間隔,用“XX年XX月XX日”來表示。
** Return values: varchar(100) 
** Parameters: @dtmStart,@dtmEnd
** Author: 何毅翔(MyGodness)
** Date: 2005-3-31
** Use Method: select dbo.fnDateInterval('2005-2-18','2005-4-6')
*************************************************************/

Create function fnDateInterval(@dtmStart datetime,@dtmEnd datetime)
returns varchar(100)
As
Begin
declare @chvInterval varchar(100)
select @chvInterval=convert(varchar(10),@dtmStart,120)+'距離'+convert(varchar(10),@dtmEnd,120)

--如果開始日期晚於結束日期
declare @dtmTemp datetime
if @dtmStart>@dtmEnd
 select @dtmTemp=@dtmStart,@dtmStart=@dtmEnd,@dtmEnd=@dtmTemp,@chvInterval=@chvInterval+'已經過了'
else
 select @chvInterval=@chvInterval+'還有'

declare @y int,@m int,@d int
select @y=datediff(yy,@dtmStart,@dtmEnd)
if datediff(d,dateadd(yy,@y,@dtmStart),@dtmEnd)<=0
  select @y=@y-1
select @m=datediff(m,@dtmStart,@dtmEnd)-@y*12-1

declare @dtmStart2 datetime --開始日期下個月的第一天
declare @dtmEnd2 datetime --結束日期當月的第一天
select @dtmStart2=dateadd(mm,datediff(mm,0,@dtmStart)+1,0)
select @dtmEnd2=dateadd(mm,datediff(mm,0,@dtmEnd),0)

select @d=datediff(d,@dtmStart,@dtmStart2)-datediff(d,@dtmEnd,@dtmEnd2)

declare @dtmDaysOfStart int --開始日期當月的天數
select @dtmDaysOfStart=datediff(d,dateadd(mm,datediff(mm,0,@dtmStart),0),dateadd(mm,datediff(mm,0,@dtmStart)+1,0))

declare @dtmDaysOfEnd int --結束日期當月的天數
select @dtmDaysOfEnd=datediff(d,dateadd(mm,datediff(mm,0,@dtmEnd),0),dateadd(mm,datediff(mm,0,@dtmEnd)+1,0))

if @dtmDaysOfStart<=@d
 select @d=@d-@dtmDaysOfStart,@m=@m+1
if @m=12
 select @m=0,@y=@y+1

declare @chvY varchar(20),@chvM varchar(20),@chvD varchar(20)
if @y=0
 select @chvY=''
else
 select @chvY=cast(@y as varchar)+'年'
if @m=0
 select @chvM=''
else
 select @chvM=cast(@m as varchar)+'個月'
if @d=0
 select @chvD=''
else
 select @chvD=cast(@d as varchar)+'天'
if @y=0 and @m=0 and @d=0
 select @chvD='0天'

select @chvInterval=@chvInterval+@chvY+@chvM+@chvD

return @chvInterval
End

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.