2010-08-16 72 views
0

我需要在存儲過程中轉化爲函數幫助,轉換存儲過程到用戶定義的函數

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

你想在哪裏使用這個功能?一般來說,一個函數可以返回一個值,或者像@Jon所說的那樣,表值函數可能對你有幫助。 – shahkalpesh 2010-08-16 13:47:44

回答

1

你想創建一個Table-Valued function

+0

只有user310879想回到在最後的SELECT語句中的所有6列 - 如果他(她)想要的只是最後的字符串(如問題規定),那麼標量值函數可能會更好。 – 2010-08-16 14:03:40

+0

這就是事實,我非常喜歡從演示中分離數據 – 2010-08-16 14:32:30

1

相當簡單:

  1. 變化CREATE PROCEDURECREATE 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. 編譯功能。

您現在應該可以在select語句中使用該函數 - 例如。

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

應返回「0年,10個月,6天」。