Execute a stored procedure in another stored procedure in SQL server - sql

How can i execute a stored procedure in another stored procedure in SQL server?
How will I pass the parameters of the second procedure.?

If you only want to perform some specific operations by your second SP and do not require values back from the SP then simply do:
Exec secondSPName #anyparams
Else, if you need values returned by your second SP inside your first one, then create a temporary table variable with equal numbers of columns and with same definition of column return by second SP. Then you can get these values in first SP as:
Insert into #tep_table
Exec secondSPName #anyparams
Update:
To pass parameter to second sp, do this:
Declare #id ID_Column_datatype
Set #id=(Select id from table_1 Where yourconditions)
Exec secondSPName #id
Update 2:
Suppose your second sp returns Id and Name where type of id is int and name is of varchar(64) type.
now, if you want to select these values in first sp then create a temporary table variable and insert values into it:
Declare #tep_table table
(
Id int,
Name varchar(64)
)
Insert into #tep_table
Exec secondSP
Select * From #tep_table
This will return you the values returned by second SP.
Hope, this clear all your doubts.

Suppose you have one stored procedure like this
First stored procedure:
Create PROCEDURE LoginId
#UserName nvarchar(200),
#Password nvarchar(200)
AS
BEGIN
DECLARE #loginID int
SELECT #loginID = LoginId
FROM UserLogin
WHERE UserName = #UserName AND Password = #Password
return #loginID
END
Now you want to call this procedure from another stored procedure like as below
Second stored procedure
Create PROCEDURE Emprecord
#UserName nvarchar(200),
#Password nvarchar(200),
#Email nvarchar(200),
#IsAdmin bit,
#EmpName nvarchar(200),
#EmpLastName nvarchar(200),
#EmpAddress nvarchar(200),
#EmpContactNo nvarchar(150),
#EmpCompanyName nvarchar(200)
AS
BEGIN
INSERT INTO UserLogin VALUES(#UserName,#Password,#Email,#IsAdmin)
DECLARE #EmpLoginid int
**exec #EmpLoginid= LoginId #UserName,#Password**
INSERT INTO tblEmployee VALUES(#EmpName,#EmpLastName,#EmpAddress,#EmpContactNo,#EmpCompanyName,#EmpLoginid)
END
As you seen above, we can call one stored procedure from another

Yes, you can do that like this:
BEGIN
DECLARE #Results TABLE (Tid INT PRIMARY KEY);
INSERT #Results
EXEC Procedure2 [parameters];
SET #total 1;
END
SELECT #total

Your sp_test: Return fullname
USE [MY_DB]
GO
IF (OBJECT_ID('[dbo].[sp_test]', 'P') IS NOT NULL)
DROP PROCEDURE [dbo].sp_test;
GO
CREATE PROCEDURE [dbo].sp_test
#name VARCHAR(20),
#last_name VARCHAR(30),
#full_name VARCHAR(50) OUTPUT
AS
SET #full_name = #name + #last_name;
GO
In your sp_main
...
DECLARE #my_name VARCHAR(20);
DECLARE #my_last_name VARCHAR(30);
DECLARE #my_full_name VARCHAR(50);
...
EXEC sp_test #my_name, #my_last_name, #my_full_name OUTPUT;
...

You can call User-defined Functions in a stored procedure alternately
this may solve your problem to call stored procedure

Yes ,
Its easy to way we call the function inside the store procedure.
for e.g. create user define Age function and use in select query.
select dbo.GetRegAge(R.DateOfBirth, r.RegistrationDate) as Age,R.DateOfBirth,r.RegistrationDate from T_Registration R

Procedure example:
Create PROCEDURE SP_Name
#UserName nvarchar(200),
#Password nvarchar(200)
AS
BEGIN
DECLARE #loginID int
--Statements for this Store Proc
--
--
--
--execute second store procedure
--below line calling sencond Store Procedure Exec is used for execute Store Procedure.
**Exec SP_Name_2 #params** (if any)
END

Related

Set variable with Scope Identity after executing different stored proc

I am trying to set a declared variable in a stored procedure after making use of another stored procedure to INSERT a 'Case' first.
The pseudo code looks like this:
DECLARE #CaseId variable
INSERT Case into Case table
SET #CaseId using SCOPE_IDENTITY
IF Case.CaseID = #CaseId
--rest of script
The below script works as expected for me:
INSERT INTO Case (CaseRef, [Source], DateCreated, CaseType)
VALUES (#caseRef, #source, #dateCreated, #caseType)
SET #caseID = SCOPE_IDENTITY();
I've tried with the below script but it doesn't seem to set the variable. Is this possible? Or must I set it the way I'm doing in the above script?
EXEC sp_InsertCase #caseRef, #source, #dateCreated, #caseType
SET #caseID = SCOPE_IDENTITY();
scope_identity() does what it says on the tin - it gives you the last identity value generated in the current scope. A stored procedure defines a scope. So when the stored procedure that causes the identity value to be generated exits, you're no longer in the scope where the value was generated, so scope_identity() can't tell you anything.
What you can do is capture the scope_identity() value into a variable inside the stored procedure, and return it as an output parameter:
create table t(i int identity(1,1), j int);
go
create proc insert_and_get_scope #scopeid int = null output as
begin
insert t(j) values (1);
set #scopeid = scope_identity();
end
go
declare #scopeid int;
exec insert_and_get_scope #scopeid output;
select #scopeid;
You can see from the example below:
DROP TABLE IF EXISTS [dbo].[StackOverflow];
CREATE TABLE [dbo].[StackOverflow]
(
[RowID] INT IDENTITY(1,1) NOT NULL
);
GO
CREATE OR ALTER PROCEDURE [dbo].[sp_StackOverflow]
AS
BEGIN;
INSERT INTO [dbo].[StackOverflow]
DEFAULT VALUES;
END;
GO
EXEC [dbo].[sp_StackOverflow];
SELECT SCOPE_IDENTITY();
it is not working, because it is not in the current scope:
Returns the last identity value inserted into an identity column in
the same scope. A scope is a module: a stored procedure, trigger,
function, or batch. Therefore, if two statements are in the same
stored procedure, function, or batch, they are in the same scope.
but you can try this:
DROP TABLE IF EXISTS [dbo].[StackOverflow];
CREATE TABLE [dbo].[StackOverflow]
(
[RowID] INT IDENTITY(1,1) NOT NULL
);
GO
CREATE OR ALTER PROCEDURE [dbo].[sp_StackOverflow]
(
#RowID BIGINT OUTPUT
)
AS
BEGIN;
INSERT INTO [dbo].[StackOverflow]
DEFAULT VALUES;
SET #RowID = SCOPE_IDENTITY()
END;
GO
DECLARE #RowID BIGINT;
EXEC [dbo].[sp_StackOverflow] #RowID = #RowID OUTPUT;
SELECT #RowID;

How to initialize values to two or more variables by calling another procedure using sql server?

say this procedure have to be called
select #className = Name
from dbo.ClassNames
where id=#classId
select #sectionName = SectionName
from dbo.ClassSections
where id=#sectionId
select #className as 'Class Name',#sectionName as 'Section Name'
the other procedure is:
declare #className nvarchar(50),
#sectionName nvarchar(50)
EXEC [dbo].[testAll]
#regNo=#regNo
so how to assing value to #className and #classSection by calling the above procedure???
create procedures using OUTPUT
https://technet.microsoft.com/en-us/library/ms187004(v=sql.105).aspx
create procedure spOne (#param1 int OUTPUT, #param2 varchar(20) OUTPUT)
as
select #param1= x from table
create procedure spTwo (#param1 int, #param2 varchar(20))
as
select x from table where y=#param1
Declare variables
declare #param1 int
declare #param2 varchar(20)
exec procedure using OUTPUT
exec spOne #param1 OUTPUT, #param2 OUTPUT
Now those variables holds values generated inside spOne
exec spTwo #param1, #param2
I think you missed something. You can't actually use the return of the proc like that or assign a variable in another procedure, they are out of context.
I would solve this in one of the 2 ways:
Define a View returning the 2 fields you need, that way you could filter the results by #regNo and return its results in another procedure, just like a normal table.
Use the return as a OUTPUT field in the procedure. That could be a table or simple 1 of the fields.
Hope it helps...

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

how to pass parameter that I get from one Stored Procedure to another Stored Procedure?

I need to execute stored procedure that his ID will be the execute of another stored procedure. how can I do this?
ALTER PROCEDURE [dbo].[spABC]
#ID INT
,#TypeString nvarchar(50)
AS
BEGIN
--exec SECOND_SP
INSERT INTO dbo.abc (Id, TypeString)
VALUES (#"result from the second sp.", #TypeString)
END
As Gordon wrote in the comments, You could have an output parameter on the second stored procedure. another option would be to use rahul's example (if the second stored procedure simply returns a scalar value)
here is a quick example:
CREATE PROCEDURE Second_SP
(
#InParam varchar(10),
#OutParam int OUTPUT -- note the OUTPUT directive
)
AS
-- do stored procedure stuff here
-- set a value to the output parameter:
SET #OutParam = 1234
GO
in the first stored procedure you should use the output directive when executing the second procedure:
ALTER PROCEDURE [dbo].[spABC]
#ID INT
,#TypeString nvarchar(50)
AS
BEGIN
DECLARE #InParam varchar(10),
#OutParam int
-- set parameters values before executing...
exec SECOND_SP #InParam, #OutParam OUTPUT -- note the output directive
INSERT INTO dbo.abc (Id, TypeString)
VALUES (#OutParam, #TypeString)
END
Not sure why all the down votes on the question. English may be a little weak, but stored procedure parameters are arcane.
You must define the procedure AND the EXEC as passing the parameter and expecting OUTPUT. Stored procedure can include a RETURN, but I am pretty sure that value is always an INTEGER, and OP wants a string.
For example:
BEGIN TRANSACTION
GO
CREATE PROCEDURE dbo.SECOND_SP (#ID INT, #Type VARCHAR(9) OUTPUT)
AS
-- totally arbitrary, pretend logic for second sp for illustrative purposes
SET #Type = CASE WHEN #ID > 90000 THEN 'ADMIN'
WHEN #ID > 9000 THEN 'MANAGER' ELSE 'USER' END
GO
CREATE PROCEDURE [dbo].[spABC]
#ID INT
AS
BEGIN
DECLARE #TypeString VARCHAR(9)
exec SECOND_SP #ID, #Type = #TypeString OUTPUT
SELECT #ID, #TypeString
-- INSERT INTO dbo.abc (Id, TypeString) VALUES (#"result from the second sp.", #TypeString)
END
GO
--TEST IT .....
EXEC [dbo].[spABC] 1111
EXEC [dbo].[spABC] 9123
EXEC [dbo].[spABC] 99543
ROLLBACK
--- RESULTS:
1111 USER
----------- ---------
9123 MANAGER
----------- ---------
99543 ADMIN
If you cannot update SECOND_SP to return the value as an OUTPUT parameter, and that stored procedure returns a single row, you can insert that into a Temporary Table (i.e. #Table) or a Table Variable (i.e. #Table) and then get the value from that table. Something along the lines of:
DECLARE #TempProcResult TABLE (ID INT, OtherField VARCHAR(50));
INSERT INTO #TempProcResult (ID, OtherField)
EXEC SECOND_SP #ID;
INSERT INTO dbo.abc (Id, TypeString)
SELECT tmp.ID, #TypeString
FROM #TempProcResult tmp;
Per your post, Considering that your second procedure SECOND_SP needs the #ID parameter and you want to have the return value of second procedure to the INSERT statement. you can do that like
ALTER PROCEDURE [dbo].[spABC]
#ID INT
,#TypeString nvarchar(50)
AS
BEGIN
declare #var int;
exec #var = SECOND_SP #ID;
INSERT INTO dbo.abc (Id, TypeString)
VALUES (#var, #TypeString)
END
EDIT:
Per comment from #srutzky. Try the below and see if works or not
create procedure test
as
begin
return 1009;
end
declare #var int;
exec #var = test;
select #var;

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

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