Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Stored Procedure capture return value in T-SQL

I have a SQL Server stored procedure; I need to capture the return value from the stored procedure. Is this the correct way of doing this?

  declare valback varchar(30)
  set valback = exec storeproc1 

In this case, storeproc1 is my stored procedure.

like image 854
Nate Pet Avatar asked Dec 16 '11 21:12

Nate Pet


People also ask

Can procedure return a value?

A stored procedure does not have a return value but can optionally take input, output, or input-output parameters. A stored procedure can return output through any output or input-output parameter.

Does procedure returns a value in SQL?

Return Value in SQL Server Stored ProcedureIn 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.

How can I return multiple values from a stored procedure in SQL Server?

In order to fetch the multiple returned values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword. You can also make use of the Split function to split the comma separated (delimited) values into rows.


2 Answers

To start, use proper T-SQL syntax:

declare @valback int;
exec @valback = storeproc1;

The only return type allowed for a stored procedure is int. Stored procedures return status via the return statement.

I somehow have a feeling that you really want something else, namely: to have an OUTPUT parameter in the procedure:

declare @valback varchar(30);
exec storedproc1 @valback OUTPUT;

or capture the procedure result set via INSERT ... EXEC. See How to Share Data Between Stored Procedures.

like image 105
Remus Rusanu Avatar answered Sep 28 '22 14:09

Remus Rusanu


The correct syntax is:

DECLARE @valback VARCHAR(30) 
EXEC @valback = storeproc1  

As per the documentation:

http://msdn.microsoft.com/en-us/library/ms188332.aspx

like image 20
Martin Avatar answered Sep 28 '22 13:09

Martin