如何使用while循环MS SQL Server输出存储过程的结果?

时间:2015-05-26 17:17:23

标签: sql sql-server tsql sql-server-2014

我正在对海啸在不同半径之间的波浪时间进行一些计算。我无法将存储过程的结果输出到表中。我得到的输出是一个没有任何数据存储的空白表。日志显示“0行受影响”。由于某种原因,我的输入和输出没有注册。我认为它可能与我在循环内部使用SP的方式有关。

    CREATE PROCEDURE SP_Tsunami
(
    @oceanDepth int,
    @radii1 int,
    @radii2 int,
    @tsunamiSpeed int OUTPUT,
    @tsunamiTimeDifference int OUTPUT
)
    AS
    BEGIN
        SET @tsunamiSpeed = sqrt(32.1725 * @oceanDepth) * (60.0/88.0);
        Truncate Table dbo.Tsunami

        DECLARE @i int
            SET @i = 0;
            WHILE (@i <= 10000)
            BEGIN
                INSERT INTO dbo.Tsunami (Radius, Wavetime)
                VALUES
                    (@i, (@i / @tsunamiSpeed))
                SET @i = @i + 100;  
            END         

        DECLARE @tsunamiTime1 int
        DECLARE @tsunamiTime2 int
        SET @tsunamiTime1 = (Select Wavetime From Tsunami WHERE Radius = @radii1);
        SET @tsunamiTime2 = (Select Wavetime From Tsunami WHERE Radius = @radii2);
        SET @tsunamiTimeDifference = (@tsunamiTime2 - @tsunamiTime1);   
    END

    /* Outputs */
    DECLARE @Out_tsunamiSpeed int
    DECLARE @Out_tsunamiTimeDifference int


    /* Inputs */
    DECLARE @IN_oceanDepth int
    DECLARE @IN_radii1 int
    DECLARE @IN_radii2 int
    SET @IN_oceanDepth = 15088; 
    SET @IN_radii1 = 2500; 
    SET @IN_radii2 = 7500;

    Execute SP_Tsunami @oceanDepth = @IN_oceanDepth, @radii1 = @IN_radii1, @radii2 = @IN_radii2, @tsunamiSpeed = @Out_tsunamiSpeed OUTPUT, @tsunamiTimeDifference = @Out_tsunamiTimeDifference OUTPUT

1 个答案:

答案 0 :(得分:0)

将数据插入表格然后从那里读取是没有意义的。您插入表中的所有行最终只从表中读取一行,以便为变量赋值。

同样将过程名称前缀从sp_更改为其他内容,sp_是系统存储过程前缀。

我已经改变了程序定义,希望它有意义。

ALTER PROCEDURE SP_Tsunami
(
    @oceanDepth int,
    @radii1 int,
    @radii2 int,
    @tsunamiSpeed int OUTPUT,
    @tsunamiTimeDifference int OUTPUT
)
AS
BEGIN
    SET @tsunamiSpeed = sqrt(32.1725 * @oceanDepth) * (60.0/88.0);


    DECLARE @tsunamiTime1 int
    DECLARE @tsunamiTime2 int

    SET @tsunamiTime1 = @radii1 / @tsunamiSpeed;
    SET @tsunamiTime2 = @radii2 / @tsunamiSpeed;

    SET @tsunamiTimeDifference = (@tsunamiTime2 - @tsunamiTime1);   
END
GO

使用您提供的数据执行该过程。

/* Outputs */
DECLARE @Out_tsunamiSpeed int
DECLARE @Out_tsunamiTimeDifference int


/* Inputs */
DECLARE @IN_oceanDepth int
DECLARE @IN_radii1 int
DECLARE @IN_radii2 int
SET @IN_oceanDepth = 15088; 
SET @IN_radii1 = 2500; 
SET @IN_radii2 = 7500;

Execute SP_Tsunami @oceanDepth = @IN_oceanDepth
                 , @radii1 = @IN_radii1
                 , @radii2 = @IN_radii2
                 , @tsunamiSpeed = @Out_tsunamiSpeed OUTPUT
                 , @tsunamiTimeDifference = @Out_tsunamiTimeDifference OUTPUT

SELECT @Out_tsunamiSpeed AS Out_tsunamiSpeed
      ,@Out_tsunamiTimeDifference AS Out_tsunamiTimeDifference

结果集:

Out_tsunamiSpeed    Out_tsunamiTimeDifference
     475                         10