set @var = exec stored_procedure

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

Something like

DECLARE @count int
SET @count = Execute dbo.usp_GetCount @Id=123

Answers


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

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


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

DECLARE @count int

Execute @count =  dbo.usp_GetCount @Id=123

Need Your Help

Preserve new lines in YAML

yaml pyyaml

How do I format a YAML document like this so that PyYAML can parse it properly?

Sort list by given order of indices

python sorting list

I have a list of lines read from a file. I need to sort the list by time stamp. I have parsed out the time stamp using regular expressions and place them into a separate list. The indices of the two