Get scalar value from SELECT statement in stored proc, from within a stored proc - sql

I know the preferred method for returning scalar values from stored procs is either using RETURN or an OUTPUT parameter. But lets say that I have a stored proc that returns the value using a select statement:
CREATE PROC spReturnNumber AS
SELECT 1
Is it possible to get this value from within another stored proc?
CREATE PROC spCheckNumber AS
EXEC spReturnNumber -- <-- get the return value here?
Clarification: I need a solution that doesn't require using an OUTPUT parameter, or using RETURN to return the value.
Thanks in advance.

You could use insert-exec to store the result of a stored procedure in a table:
declare #t table (col1 int)
insert #t exec spReturnNumber
return (select col1 from #t)
The definition of the table has to match the result set of the stored procedure.

Use an OUTPUT parameter instead of (or in addition to, if this procedure is used by other applications) the SELECT.
ALTER PROCEDURE dbo.spReturnNumber
#Number INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #Number = 1;
SELECT #Number;
END
GO
CREATE PROCEDURE dbo.spCheckNumber
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Number INT;
EXEC dbo.spReturnNumber #Number = #Number;
SELECT #Number;
END
GO
If you can't change the original procedure, but you know its output will remain static, you could use a #temp table.
CREATE PROCEDURE dbo.spCheckNumber
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #n(i INT);
INSERT #n(i) EXEC dbo.spReturnNumber;
DECLARE #Number INT;
SELECT #Number = i FROM #n;
END
GO

You can't get the SELECT value from "parent" procedure but you can get the return value like this:
CREATE PROC A AS
BEGIN
DECLARE #ret int
EXEC #ret = spReturnNumber
RETURN #ret
END

If you are unable to change the proc being called .. place the result set in a temp table [or table variable]:
CREATE TABLE #results (val INT)
DECLARE #someval int
INSERT #results
EXEC dbo.spCheckNumber
SELECT #someval =val from #results

Related

How to use stored procedure return value into an insert statement?

I have a stored procedure like
CREATE PROCEDURE GetSerial (#param1 int, #param2 int)
AS
BEGIN
-- do some insert/updates, so I can't use function
DECLARE #value AS int;
SET #value = 3;
return #value;
END
Now I declare a table variable
DECLARE #Serials AS TABLE
(
ID int,
Value int
)
Now I wanna fill this table like
INSERT INTO #Serials (ID, Value)
SELECT 1, GetSerial(1,2) -- *How can I call this?
So, can anyone help me how can i call the GetSerial stored procedure inside the SELECT statement to fill my table?
I recommend you avoid getting into this pattern/thinking, because stored procedures only return INTs, and those ints are really intended to describe how well the operation went, not a result/data from the operation. Example: 0 => failed, 1=> succeeded. Not GetAgeInYears() => 29
https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/return-data-from-a-stored-procedure?view=sql-server-2017 has a lot of info and concrete examples but in your specific case you'd need to execute the procedure and capture the result code into a variable then insert that:
DECLARE #ret INT;
EXEC #ret = GetSerial(1,2);
INSERT INTO #Serials VALUES(1, #ret);
Really you'd be better off using an output parameter or resultset if you have many values to return. See the above link for more

Stored procedure returns 0 instead of value

There is a stored procedure that can return top 1 result as
USE [DB]
GO
.....
CREATE PROCEDURE [dbo].[GET]
(#in VARCHAR(10), #Out VARCHAR(10) OUTPUT)
AS
SELECT top 1 #Out = tab.Col
FROM table tab
RETURN
GO
When I call it in main query
DECLARE #output VARCHAR(10)
DECLARE #in VARCHAR(10)
DECLARE #Out VARCHAR(10)
EXECUTE dbo.GET #in = 'table', #Out = #output
It prints #output as 0;
but if I do
EXECUTE dbo.GET #in = 'table', #Out = #Out
And print #out, I get the correct value.
Why could this happen?
I did pass output #Out to pre-defined variable #output
Assuming SQLS due to presence of 'dbo' and sqlserver tag
Your query in the procedure doesn't assign a value to the out parameter (called #out) it assigns to some other variable called #outpk. Resolve the naming mismatch and make them the same
Sqlserver does not support LIMIT. To limit result set size use SELECT TOP 1 *. Using TOP (or any similar result set restrictor) without ORDER BY is illogical. Specify an ORDER BY
In sqlserver, output parameters must be passed with the OUTPUT keyword when calling the procedure:
EXEC sprocname #inputparameter ='value', #outputparameter = #variableToSet OUTPUT;
Use semicolons; omitting them is deprecated
Example
USE [DB]
GO
CREATE PROCEDURE [dbo].[GET]
(#in VARCHAR(10), #OutPk VARCHAR(10) OUTPUT)
AS
SELECT #OutPK = tab.Col
FROM table tab
ORDER BY tab.Col;
GO
DECLARE #output VARCHAR(10);
EXECUTE dbo.GET #in = 'table', #OutPK = #output OUTPUT
SELECT #output;
If its MySql (Limit is in mySql), you can simply call:
Call dbo.GET('table', #out);
No need to have separate variable #output.

Must declare scalar variable in sql....with input and output parameters

I got SP that gets USER_ID as input and fetches GROUP_ID from the table, but it shows error when I'm trying to run it:
must declare scalar variable #Group_i
My stored procedure:
Alter PROCEDURE [dbo].[DisplayDetails]
#User_Id int,
#Group_Id int OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Begin
-- Insert statements for procedure here
SELECT
#Group_Id=(select distinct(Group_Id) from input_files_updated)
from INPUT_FILES_updated where [User_Id]=#User_Id
END
END
GO
Query to execute SP:
Declare #Group_I int
Execute [dbo].[DisplayDetails] #User_Id='3',
#Group_Id=#Group_I out
Why I'm getting this error?
A little bit fixed query of yours:
Alter PROCEDURE [dbo].[DisplayDetails]
#User_Id int,
#Group_Id int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #Group_Id = (
select top 1 Group_Id
from INPUT_FILES_updated
where [User_Id]=#User_Id
)
RETURN
END
As I remember there must be a word RETURN in SP. Then try:
Declare #Group_I int
Execute [dbo].[DisplayDetails] #User_Id=3, #Group_Id=#Group_I output
SELECT #Group_I

Calling stored procedure from other stored procedure

This is stored procedure #1:
ALTER PROCEDURE [dbo].[sp1]
AS
BEGIN
DECLARE #test varchar(255)
exec #test = dbo.sp2
SET NOCOUNT ON;
SELECT
CMS_ORG.description, #test
FROM
CMS_ORG
END
This is stored procedure #2:
ALTER PROCEDURE [dbo].[sp2]
AS
BEGIN
SET NOCOUNT ON;
SELECT
CMS_MAS.description + '' + CONVERT(varchar(50),
CAST(CMS_ORG.amount AS money), 1)
FROM
CMS_ORG
INNER JOIN
CMS_MAS = CMS_ORG.GUID = CMS_MAS.GUID
END
The problem is here is I was not able to execute #test in stored procedure #1 by calling the stored procedure #2. When I execute sp1, I got a null values instead but when I execute the query of sp2 in sp1, I got a correct value. May I know what is the possible solution or similar examples which can solve the issue?
Your stored proc sp2 outputs the result of a SELECT, but like all stored procs, it returns an integer using the return statement. You don't have a return statement, so Sql Server generates one for you: return 0. The purpose of the return code is to give feedback on whether it ran as expected. By convention, a return code of 0 means no errors.
This shows the difference between the return code and the output of a stored proc. Create a temp table #output to capture the rows of the SELECT that the stored proc outputs.
DECLARE #return_code int
-- capture the output of the stored proc sp2 in a temp table
create table #output( column_data varchar(max) )
insert #output( column_data )
exec #return_code = dbo.sp2 -- returns 0 because you have no RETURN statement
-- extract column_data from #output into variable #test
-- if there is more than one row in #output, it will take the last one
DECLARE #test varchar(255)
select #test = column_data from #output
Create a table variable & Use it like this :
create proc test55
as
select 55
declare #test table (Value Varchar(255))
insert into #test
exec test55
Select * from #test
Your sp2 stored procedure will return table, not varchar(255).
If you want to get a varchar(255) from sp2 you should be using function.
You can view in my example:
Define a function:
CREATE FUNCTION dbo.function1()
RETURNS varchar(255)
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE #returnVal varchar(255);
SET #returnVal = (SELECT top 1 [ProductName]
FROM [dbo].[Products])
RETURN(#returnVal);
END;
And alter SP1 like this:
ALTER PROCEDURE [dbo].[sp1]
#SMonth As Integer,
#SYear As Integer
AS
BEGIN
DECLARE #test varchar(255)
set #test = dbo.function1()
SET NOCOUNT ON;
SELECT [ProductId], #test
FROM [LearningKO].[dbo].[Products]
END

SQL Server Stored Procedure store return value

Helo,
My question is I have one Stored Procedure in SQL Server that returns counts of a field. I want to store the results of this Stored Procedure in a variable (scalar?) of a different stored procedure.
sp_My_Other_SP:
CREATE PROCEDURE [dbo].sp_My_Other_SP
#variable int OUTPUT -- The returned count
AS
BEGIN -- SP
SET NOCOUNT ON;
SET #SQL = "SELECT COUNT(*) FROM blah"
EXEC(#SQL)
END -- SP
I currently do it like:
DECLARE #count int
EXEC sp_My_Other_SP #count OUTPUT
Then I use it like
IF (#count > 0)
BEGIN
...
END
However its returning the other Stored Procedure results as well as the main Stored Procedure results which is a problem in my .NET application.
-----------
NoColName
-----------
14
-----------
MyCol
-----------
abc
cde
efg
(Above is an attempted representation of the results sets returned)
I would like to know if there is a way to store the results of a Stored Procedure into a variable that doesn't also output it.
Thanks for any help.
You can capture the results of the stored procedure into a temp table so it is not returned by the calling stored procedure.
create table #temp (id int, val varchar(100))
insert into #temp
exec sp_My_Other_SP #value, #value, #value, #count OUTPUT
Well, the easiest way to fix this is to recode the stored proc so that the select statement that returns the 'other' result set you don't want in this case is conditionally extecuted, only when you are NOT asking for the count
Add another parameter called #GetCount
#GetCount TinyInt Defualt = 0 // or
#GetCount Bit Default = 0
Then
instead of just
Select ...
write
If #GetCount = 1
Select ...
Have you tried changing
SET #SQL = "SELECT COUNT(*) FROM blah"
EXEC(#SQL)
to
SELECT #variable = COUNT(*) FROM blah"
-- don't do EXEC(#SQL)
?
THE FIRST PROCEDURE:
CREATE PROC DD43
#ID INT OUTPUT AS
(SELECT #ID=COUNT(*) FROM CS2)
SECOND PROCEDURE:
CREATE PROC DD45 AS
DECLARE #COUNT INT
DECLARE #COUN INT
EXEC DD43 #COUN OUT --CALLING THE FIRST PROCEDURE
SET #COUNT= (SELECT #COUN)
SELECT #COUNT
EXEC DD45