我需要帮助将存储过程转换为函数,
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
答案 0 :(得分:1)
答案 1 :(得分:1)
相当简单:
CREATE PROCEDURE
更改为CREATE FUNCTION
。@todate DATETIME)
变为@todate DATETIME) RETURNS VARCHAR(255)
。SELECT @FromDate, @Todate, @TotalYears Yrs, @TotalMonths Mont, @TotalDays Days , @TotalYears + ' years,' + @TotalMonths + ' months,' + @TotalDays+ ' days'
变为RETURN @TotalYears + ' years,' + @TotalMonths + ' months,' + @TotalDays+ ' days'
。您现在应该能够在select语句中使用该函数 - 例如
select [dbo].[FunGetEmpExp]('2010-03-26','2011-01-31')
应该返回'0年,10个月,6天'。