2012-04-13 77 views
4

我能夠在下面創建存儲過程,但是現在我在刪除它並將其創建爲函數時遇到了一些問題。任何幫助將不勝感激:如何創建一個函數是SQL Server 2008 R2?

CREATE PROC spTriangular 
    @ValueIn int, 
    @ValueOut int OUTPUT 
AS 
    DECLARE @InWorking int 
    DECLARE @OutWorking int 

    IF @ValueIn != 1 
    BEGIN 
     SELECT @InWorking = @ValueIn - 1 
     EXEC spTriangular @InWorking, @OutWorking OUTPUT 

     SELECT @ValueOut = @ValueIn + @OutWorking 
    END 
    ELSE 
    BEGIN 
     SELECT @ValueOut = 1 
    END 

    RETURN 
GO 

運行此存儲過程:

DECLARE @WorkingOut int 
DECLARE @WorkingIn int 

SELECT @WorkingIn = 5 

EXEC spTriangular @WorkingIn, @WorkingOut OUTPUT 

PRINT CAST(@WorkingIn AS varchar) + ' Triangular is ' + CAST(@WorkingOut AS varchar) 
GO 

Triangular is 15 

回答

2

試試這個:

CREATE FUNCTION dbo.spTriangular 
(@ValueIn int) 
RETURNS int 
AS 
    DECLARE @ValueOut int 
    DECLARE @InWorking int 
    DECLARE @OutWorking int 
    IF @ValueIn != 1 
    BEGIN 
      SELECT @InWorking = @ValueIn - 1 
      SELECT @OutWorking = dbo.spTriangular(@InWorking) 

      SELECT @ValueOut = @ValueIn + @OutWorking 
    END 
    ELSE 
    BEGIN 
      SELECT @ValueOut = 1 
    END 
    RETURN(@ValueOut) 
相關問題