SQL Server output parameter issue

后端 未结 8 1643
南旧
南旧 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:36

    Yes, you can use an OUTPUT parameter for both passing in and retrieving values (although I can't think of a good reason to do that at the moment).

    Here's a trivial example that demonstrates this:

    -- The stored procedure
    CREATE PROCEDURE OutParamExample
        @pNum int OUTPUT
    AS
    BEGIN
        select @pNum
        set @pNum = @pNum + 5
    END
    GO
    
    -- use a local variable to retrieve your output param value
    declare @TheNumber int
    set @TheNumber = 10
    
    print @TheNumber
    exec OutParamExample @TheNumber OUTPUT
    print @TheNumber
    

    The results will look like this:

    10
    
    -----------
    10
    
    (1 row(s) affected)
    
    15
    

    EDIT: OK, I think I missed a "not" in the second paragraph and may not have answered the question you asked. If you want a strict output parameter (e.g. something like a return code), you certainly don't have to provide a value to the local variable passed as the output parameter, but you still have to declare that local variable so that you'll have a way of accessing the returned value outside of the scope of the procedure itself.

    For example:

    declare @LocalNumber int
    -- I don't have to assign a value to @LocalNumber to pass it as a parameter
    exex OutParamExample @LocalNumber OUTPUT  
    -- (assume SP has been altered to assign some reasonable value)
    
    -- but I do have to declare it as a local variable so I can get to
    -- the return value after the stored procedure has been called
    print @LocalNumber
    

提交回复
热议问题