What is the best way to assign the returned value of a stored proc to a variable in SQL? - sql

I have a stored procedure that returns a valueI call it from other stored procedures that need to retrieve this value. The calling stored procedure is inside a transaction, the stored procedure that returns the value (and actually creates the value and stores it in a table that no other proc touches) is not inside its own transaction, but would be part of the caller's transaction.
The question is this, what is the most efficient way of retrieving the return value of the stored procedure and storing it in a variable in the calling proc?
Currently I have the following and I'm wondering if its very inefficient?
DECLARE #tmpNewValue TABLE (newvalue int)
INSERT INTO #tmpNewValue EXEC GetMyValue
DECLARE #localVariable int
SET #localVariable = (SELECT TOP 1 newvalue FROM #tmpNewValue )
Isn't there a more straight forward way of doing this? Isn't this an expensive (in terms of performance) way?
My stored proc doesn't have an output param, it just returns a value. Would using an output param be faster?
For what it's worth I'm using MS SQL Server 2005

If your getting a single return variable then yes this is innefficent you can do:
declare #localVariable int
exec #localVariable =GetMyValue
select #localVariable

See How to Share Data Between Stored Procedures
By some reasons 'exec #localVariable =GetMyValue' is not working for me (MS SQL 2005), it's always return 0 value (They have the same issue).
My opinion is:
if you can change stored procedure, add output parameter.
else if you can remove procedure, rewrite it as a function.
else use table variable, as you do.

Is this proc returning a rowset of 1 row and 1 column or no rowset at all and you just want to capture the returncode?
If you want just the returncode then use Josh's method otherwise use a OUTPUT parameter sicne it will be much faster than what you are doing now
To Explain what I mean run this code
use tempdb
go
create proc GetMyValue
as
select 1
go
create table #temp (id int)
declare #localVariable int
insert #temp
exec #localVariable =GetMyValue
select #localVariable,* from #temp

Try this:
create proc AvilableSeats
as
declare #v1 int,#v2 int
exec #v1= determinPath_Capacity 1,'Sat-Tue',32
exec #v2=Student_fGroup '6/12/2009'
select #v1-#v2

Related

Get first row, first column value from stored procedure

I am calling a stored procedure (that I can't modify) that returns a single value via a SELECT at the end of the procedure. I need to use that value in my own procedure. How can I get that value?
Here is an example of the procedure I am calling that I can not modify:
CREATE PROCEDURE [dbo].[SP_poorlywritten] (
....
)
BEGIN
....
SELECT #lastkey;
RETURN (0);
END
And here is what I am trying to do, but it doesn't work because this gets the return value, and what I need is that SELECT value:
exec #next_key = SP_poorlywritten 'tablename',1;
How can I store the first column, first row value from a store procedure?
If you cannot modify the existing stored procedure, you will not be able to utilize the RETURN as you would like to.
An alternative may be to insert the output of the procedure's select statement into a temp table, and then query that directly to populate a variable.
That would look like this.
CREATE TABLE #tmp
(
LastKey INT
)
INSERT INTO #tmp
EXEC [dbo].[SP_poorlywritten]
See this existing post for more details on how you might accomplish this.
As Aaron Bertrand pointed out, RETURN is for error/status. If you were able to modify the stored procedure, you would want to utilize an output parameter instead of RETURN. This is how you would do that.
CREATE PROCEDURE proc_name
#Output int OUTPUT
AS
<do some stuff>
SET #Output = <some_value>
GO
DECLARE #Output int
EXEC proc_name #Output = #Output

What is the use of an OUTPUT parameter in SQL?

In an SQL Stored Procedure/Function, we can return multiple values. Then what is the use of an OUTPUT parameter? I wonder why they have introduced it? Can anyone explain?
OUTPUT clause returns the values of each row that was affected by an INSERT, UPDATE or DELETE statement.
If you are referring to RDBMS like SQL Server then output parameters are used to capture the result set of execution in a scalar variable.
Example:
Create procedure dbo.sp_square #inputparam int
as
declare #outputparam int
select #outputparam = #inputparam * #inputparam
Return #outputparam
Execution to get and store the output value of a sp
Declare #result int
exec #result = dbo.sp_square 5
select #result
Result
25
If you are not returning the output in the stored procedure you will still get the result after the execution but you cannot store it in a variable or use it later in your code.

How to use a variable from one stored procedure in a different stored procedure (SQL)

I have written a stored procedure as follows (this is a simplified version - the SP does a lot of other things but these are the key parts):
CREATE PROCEDURE [dbo].[_uspCustomSP]
AS
BEGIN
CREATE TABLE #custno(custno int)
INSERT INTO #custno
EXEC usp_GetCustomerNo
DECLARE #custnumber nvarchar(5)
SET #custnumber = (SELECT custno FROM #custno)
DROP TABLE #custno-- drop table so fresh each time
END
This SP works as I want it to. However, I want to be able to refer to the value of #custnumber in a different stored procedure. Is there any way of persisting the value of #custnumber but without rerunning usp_GetCustomerNo (as every time it is run, the value of #custnumber changes - I want to be able to use the exact number as stored in the variable.)
EDIT: I've had a really helpful response below suggesting I include an output parameters. I have thought about this but I'm not sure how to refer to this output elsewhere (in a different SP) without re-running the entire SP at the same time.
Apologies if I've not included enough information.
Many thanks,
Helen
You can have the stored procedure return the value:
CREATE PROCEDURE [dbo].[_uspCustomSP] (
#custnumber nvarchar(5) OUTPUT
) AS
BEGIN
CREATE TABLE #custno(custno int) ;
INSERT INTO #custno (custno)
EXEC usp_GetCustomerNo;
SELECT #custnumber = custno FROM #custno ;
DROP TABLE #custno-- drop table so fresh each time
END;
Having said that, I have some comments on the stored procedure:
There is no need to drop the temporary table. I prefer table variables, because it is obvious they go out of scope.
I think it is dangerous to return a single value in a table. Why not use a scalar function or OUTPUT parameter for usp_GetCustomerNo?
You should get in the habit of putting semicolons at the end of statements and always using a column list with INSERT.
You would call the stored procedure as:
declare #custnumber nvarchar(5);
exec sp_executesql _uspCustomSP,
N'#custnumber nvarchar(5) output',
#custnumber=#custnumber output;

SQL return the output of SELECT and not the output of another stored procedure

How do I return the result of the SELECT as the output of the stored procedure? Sorry I'm new to stored procedures!
In this query below I'm calling stored procedure spCuExt_ExtractLog and assigning the result to variable #StartDate. I then use this variable within the main stored procedure, in a SELECT statement. I need to return only the result of the SELECT statement from the main stored procedure:
-- Main stored procedure
BEGIN
DECLARE #StartDate DATETIME
EXEC #StartDate = spCuExt_ExtractLog 'Customers'
SELECT Id, [Name], LogoPath, IsDeleted
FROM dbo.Customers
WHERE RecordCreatedDateUTC>= #StartDate
END
This returns the result of the call to spCuExt_ExtractLog as well as the result of the SELECT statement but I want to output the result of the SELECT only.
How do I do this?
Put the results into a table variable instead:
create procedure dbo.usp_Child
as
begin
select N'Hello world!' as [message];
end;
go
create procedure dbo.usp_Main
as
begin;
declare #results table ([message] nvarchar(max));
insert into #results
execute dbo.usp_Child;
select N'success';
end;
go
execute dbo.usp_Main;
Here's a link to a pretty good document explaining all the different ways to solve your problem (although a lot of them can't be used since you can't modify the existing stored procedure.)
http://www.sommarskog.se/share_data.html

SQL INSERT INTO calling Stored Procedure instead

I would like to do something like this in SQL
Insert Into storedproc2
SELECT column1, column2 from Tablename
My goal is to have each row of data in tablename processed using the storedproc2 stored procedure, which itself handles any insertion necessary in the logic flow.
Well as others said, you can't do that on a single statement. (that's just the way things work)
If what you wan't is to call a proc with the results you can first select and then call the proc using a cursor.
The cursor would perform a row by row code and you would be able to call the proc passing the correct values. But beware cursors are slow use Flags like FAST_FORWARD.
The other way would be to change your proc to accept a whole table, as a table valued parameter, if that is possiblel, that would perform really better.
Hope this helps.
DECLARE CallingProcCursor CURSOR
FAST_FORWARD
FOR
SELECT database_id,name from sys.databases
DECLARE #database_id int, #name sysname
OPEN CallingProcCursor
FETCH NEXT FROM CallingProcCursor INTO #database_id, #name
WHILE (##fetch_status <> -1)
BEGIN
IF (##fetch_status <> -2)
BEGIN
EXEC PROCX #database_id, #name
END
FETCH NEXT FROM CallingProcCursor INTO #database_id, #name
END
CLOSE CallingProcCursor
DEALLOCATE CallingProcCursor
GO
You can't insert into a stored procedure. You can only insert into a table (and in some cases a view, depending on the DB platform and whether the view is updateable.)
You can use a stored procedure to insert data as shown here: http://www.codeproject.com/KB/cs/tariqaziz.aspx
This is NOT meant to be insulting, but rather helpful...
It sounds like you need to go read up on stored procedures, since your question shows that you don't get the basics.
http://databases.about.com/od/sqlserver/a/storedprocedure.htm
As David said, you can't do this the way you want.
What you CAN do is feed the stored proc a table as a parameter, and have it perform it's logic on each row in that table. It will involve some Dynamic SQL but it is doable.
you can put insert statement inside stored proc and pass the values as parameters e.g.
following is just an example, on each row you can call your stored proc and it should be fine
CREATE PROC BDD_AddMessageLogItem(
#BusinessDevelopmentItemId INT,
#MessageLog NVARCHAR(MAX),
#PostedBy SMALLINT,
#PostedOfficeId TINYINT,
#PostedDepartmentId TINYINT,
#PostedMessageLogType TINYINT)
AS
BEGIN
DECLARE #BusinessDevelopmentMessageLogId SMALLINT
INSERT INTO dbo.BusinessDevelopmentItemMessageLogs
( BusinessDevelopmentItemId ,
MessageLog ,
DatePosted,
PostedBy,
PostedOfficeId,
PostedDepartmentId,
PostedMessageLogType,
BusinessDevelopmentMessageLogId
)
VALUES ( #BusinessDevelopmentItemId , -- BusinessDevelopmentItemId - int
#MessageLog , -- Message - nvarchar(100)
GETDATE(),
#PostedBy,
#PostedOfficeId,
#PostedDepartmentId,
#PostedMessageLogType,
#BusinessDevelopmentMessageLogId
)
END
You can't pass data sets to stored procedures, only parameters. You could:
Pass the table name to the stored procedure and then construct the select.
Pass the whole query as a parameter.
And then execute it with sp_executesql. If you use this method you should read The Curse and Blessings of Dynamic SQL.