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
Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.
Return Value in SQL Server Stored Procedure In default, when we execute a stored procedure in SQL Server, it returns an integer value and this value indicates the execution status of the stored procedure. The 0 value indicates, the procedure is completed successfully and the non-zero values indicate an error.
To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.
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
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
As usual many ways to do this but the easiest is:
DECLARE @count int
Execute @count = dbo.usp_GetCount @Id=123
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With