Return multiple values from a SQL Server function

后端 未结 5 1333
忘了有多久
忘了有多久 2020-12-14 06:06

How would I return multiple values (say, a number and a string) from a user-defined function in SQL Server?

5条回答
  •  时光说笑
    2020-12-14 06:55

    Example of using a stored procedure with multiple out parameters

    As User Mr. Brownstone suggested you can use a stored procedure; to make it easy for all i created a minimalist example. First create a stored procedure:

    Create PROCEDURE MultipleOutParameter
        @Input int,
        @Out1 int OUTPUT, 
        @Out2 int OUTPUT 
    AS
    BEGIN
        Select @Out1 = @Input + 1
        Select @Out2 = @Input + 2   
        Select 'this returns your normal Select-Statement' as Foo
              , 'amazing is it not?' as Bar
    
        -- Return can be used to get even more (afaik only int) values 
        Return(@Out1+@Out2+@Input)
    END 
    

    Calling the stored procedure

    To execute the stored procedure a few local variables are needed to receive the value:

    DECLARE @GetReturnResult int, @GetOut1 int, @GetOut2 int 
    EXEC @GetReturnResult = MultipleOutParameter  
        @Input = 1,
        @Out1 = @GetOut1 OUTPUT,
        @Out2 = @GetOut2 OUTPUT
    

    To see the values content you can do the following

    Select @GetReturnResult as ReturnResult, @GetOut1 as Out_1, @GetOut2 as Out_2 
    

    This will be the result:

    Result of Stored Procedure Call with multiple out parameters

提交回复
热议问题