SQL Server output parameter issue

后端 未结 8 1645
南旧
南旧 2020-12-24 11:42

I am using SQL Server 2008 Enterprise. I am learning OUTPUT parameter of SQL Server stored procedure. For example, stored procedure sp_add_jobschedule has an OUTPUT paramete

相关标签:
8条回答
  • 2020-12-24 12:44

    Two other things I think that are worth noting:

    1) You can pass more than one parameter as OUTPUT,

    2) You do not have to call the parameters with OUTPUT if you don't want the results

    CREATE PROCEDURE ManyOutputs @a int, @b int output, @c varchar(100) output, @d bit output
    AS
    BEGIN
        SET @b = @a + 11
        SET @c = 'The Value of A is ' + CAST(@a AS varchar(5)) + ', and the value of B is ' + CAST(@b AS varchar(5))
        IF (@a % 2 = 1)
            SET @d = 1
        ELSE
            SET @d = 0
    END
    GO
    

    Calling this routine:

    DECLARE @bVal int
    DECLARE @cVal varchar(100)
    DECLARE @dVal bit
    
    EXEC ManyOutputs 1, @bVal, @cVal, @dVal
    SELECT @bVal AS bVal, @cVal as cVal, @dVal as dVal
    

    Returns NULL, NULL, NULL

    EXEC ManyOutputs 2, @bVal OUT, @cVal OUT, @dVal OUT
    SELECT @bVal AS bVal, @cVal as cVal, @dVal as dVal
    

    Returns 13, "The Value of A is 2, and the value of B is 13", 0

    EXEC ManyOutputs 3, @bVal, @cVal, @dVal
    SELECT @bVal AS bVal, @cVal as cVal, @dVal as dVal
    

    Returns 13, "The Value of A is 2, and the value of B is 13", 0

    (the same as the last call, because we didn't get new values by using OUTPUT, so it retained the old values.)

    EXEC ManyOutputs 5, @bVal OUT, @cVal OUT, @dVal OUT
    SELECT @bVal AS bVal, @cVal as cVal, @dVal as dVal
    

    Returns 16, "The Value of A is 5, and the value of B is 16", 1

    0 讨论(0)
  • 2020-12-24 12:46

    Adding further to what others have said above, OUTPUT parameters can act as INPUT as well as OUTPUT. But, it depends on the stored procedure to use the value passed to it.

    If the stored procedures ignores the value passed in for OUTPUT parameter (which it generally should), the INPUT value gets ignored anyway.

    Using Sergey's code, I can use the value user passed for @intOutput (if I need to)

    create PROCEDURE test_proc
    
    @intInput int,
    @intOutput int OUTPUT
    
    AS
    set @intOutput = @intOutput + 1 
    
    go
    

    But, that defeats the purpose of OUTPUT parameter.
    To give a different view, c# compiler forces you to overwrite the out parameter's value by assignment (without using the output parameter).

    e.g. I cannot do this in c#. Here it acts as only out parameter (i.e ignore the value user passed to this function)

    static void dosomething(out int i)
    {
        //i = 0;
        i = i + 1;
    }
    
    0 讨论(0)
提交回复
热议问题