我需要在存儲過程中轉化爲函數幫助,轉換存儲過程到用戶定義的函數
CREATE PROCEDURE [dbo].[FunGetEmpExp] (@fromdate DATETIME,@todate DATETIME)
AS
BEGIN
DECLARE @TotalYears VARCHAR(2)
DECLARE @TotalMonths VARCHAR(2)
DECLARE @TotalDays VARCHAR(2), @Duration varchar(10)
SET @TotalYears = null
SET @TotalMonths = NULL
SET @TotalDays = NULL
SET @todate = DATEADD(day,1,@todate)
SELECT @TotalYears = CASE WHEN Month(@fromdate) <= Month(@Todate) AND (Day(@fromdate)<=Day(@Todate)) THEN DateDiff(YEAR,@fromdate,@Todate)
ELSE DateDiff(YEAR,@fromdate,@Todate) - 1 END
SELECT @TotalMonths = CASE WHEN (Day(@fromdate)<=Day(@Todate)) then DateDiff(MONTH,@fromdate,@Todate)- @TotalYears*12 ELSE DateDiff(MONTH,@fromdate,@Todate) - @TotalYears * 12 - 1 END
SELECT @TotalDays = DateDiff(DAY,DateAdd(MONTH, CASE WHEN (Day(@fromdate)<=Day(@Todate)) then DateDiff(MONTH,@fromdate,@Todate)-(DateDiff(YEAR,@fromdate,@Todate))*12
ELSE DateDiff(MONTH,@fromdate,@Todate)-(DateDiff(YEAR,@fromdate,@Todate))*12-1 end , DateAdd(YEAR,(DateDiff(YEAR,@fromdate,@Todate)),@fromdate)),@Todate)
IF (@TotalMonths >= 12)
BEGIN
SET @TotalYears = @TotalYears + 1 SET @TotalMonths = @TotalMonths - 12
END
SELECT @FromDate, @Todate, @TotalYears Yrs, @TotalMonths Mont, @TotalDays Days , @TotalYears + ' years,' + @TotalMonths + ' months,' + @TotalDays+ ' days'
END
函數的返回值應該是[日,月數和年兩個日期之間]
如:
exec FunGetEmpExp '2010-03-26','2011-01-31'
Return Value:0 years,10 months,6 days
你想在哪裏使用這個功能?一般來說,一個函數可以返回一個值,或者像@Jon所說的那樣,表值函數可能對你有幫助。 – shahkalpesh 2010-08-16 13:47:44