将存储过程转换为用户定义的函数

时间:2010-08-16 13:05:43

标签: sql sql-server-2005

我需要帮助将存储过程转换为函数,

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

2 个答案:

答案 0 :(得分:1)

您想要创建Table-Valued function

答案 1 :(得分:1)

相当简单:

  1. CREATE PROCEDURE更改为CREATE FUNCTION
  2. 在输入参数后添加一个返回数据类型,因此@todate DATETIME)变为@todate DATETIME) RETURNS VARCHAR(255)
  3. 更改最终选择以返回输出值 - 因此SELECT @FromDate, @Todate, @TotalYears Yrs, @TotalMonths Mont, @TotalDays Days , @TotalYears + ' years,' + @TotalMonths + ' months,' + @TotalDays+ ' days'变为RETURN @TotalYears + ' years,' + @TotalMonths + ' months,' + @TotalDays+ ' days'
  4. 编译功能。
  5. 您现在应该能够在select语句中使用该函数 - 例如

    select [dbo].[FunGetEmpExp]('2010-03-26','2011-01-31')
    

    应该返回'0年,10个月,6天'。