set @var = exec stored_procedure

前端 未结 3 1291
深忆病人
深忆病人 2020-12-14 11:23

Is it possible to assign at variable a value returned from exec stored procedure?

Something like

DECLARE @count int
SET @count = Execute dbo.usp_GetC         


        
相关标签:
3条回答
  • 2020-12-14 11:25

    If you use RETURN in the proc

    DECLARE @count int
    EXECUTE @count = dbo.usp_GetCount @Id=123
    

    OUTPUT parameter

    DECLARE @count int
    EXECUTE dbo.usp_GetCount @Id=123, @count OUTPUT
    

    Redirect the results to temp table/table variable

    DECLARE @count int
    DECLARE @cache TABLE (CountCol int NOT NULL)
    INSERT @cache EXECUTE dbo.usp_GetCount @Id=123
    SELECT @count = CountCol FROM @cache
    

    You can't assign a recordset from the stored proc directly to a scalar variable

    0 讨论(0)
  • 2020-12-14 11:28

    As usual many ways to do this but the easiest is:

    DECLARE @count int
    
    Execute @count =  dbo.usp_GetCount @Id=123
    
    0 讨论(0)
  • 2020-12-14 11:35

    You can use sp_executesql instead of exec to assign to scalar output parameters

    DECLARE @out int
    
    EXEC sp_executesql N'select @out_param=10',
                       N'@out_param int OUTPUT',
                         @out_param=@out OUTPUT
    
    SELECT @out
    

    For exec I'm only aware of how to do it using a table variable

    declare @out table
    (
    out int
    )
    
    insert into @out
    exec('select 10')
    
    select * 
    from @out
    

    For stored procedures you would also use an output parameter or a return code. The latter can return a single integer only and generally preferred for returning error codes rather than data. Both techniques are demonstrated below.

    create proc #foo 
    @out int output
    as
    set @out = 100
    return 99
    
    go
    
    declare @out int, @return int
    
    exec @return = #foo @out output
    
    select @return as [@return], @out as [@out]
    
    drop proc #foo
    
    0 讨论(0)
提交回复
热议问题