<p>13.7 练习</p>

1. 将第12章中的spTriangular存储过程重新实现为函数。

先看看第12章中的spTriangular存储过程的定义与用法示例。

定义:

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);

现在将存储过程spTriangular实现为函数如下:

CREATE FUNCTION dbo.fnTriangular(@ValueIn int)
RETURNS int
AS
BEGIN
	DECLARE @ReturnValue int;
	
	IF @ValueIn > 1 
	BEGIN
		SELECT @ReturnValue = @ValueIn + dbo.fnTriangular(@ValueIn - 1);
	END
	ELSE
	BEGIN
		SET @ReturnValue = 1
	END
	RETURN @ReturnValue
END

调用示例:

SELECT dbo.fnTriangular(5)