How to pass values from SP to SP? - sql

I have a question, I have a Stored Procedure which returns a value. This Stored Procedure is being executed within another SP and I need to transfer the value into this SP. How can I accomplish this.
Any help will be appreciated.
Thank you
Example:
CREATE PROC [dbo].[isp_CREATE_CONFIG]
#CFG_KEY VARCHAR(15)
, #CFG_SHORTVALUE INT
, #CFG_LONGVALUE VARCHAR(200)
, #CFG_DESC VARCHAR(250)
, #CFG_SHORT_DESC VARCHAR(100)
, #CFG_MISC1 VARCHAR(50)
, #CFG_MISC2 VARCHAR(50)
, #CFG_MISC3 VARCHAR(50)
, #CFG_MISC4 VARCHAR(50)
, #CFG_MISC5 VARCHAR(50)
, #CFG_USER VARCHAR(20)
, #CFG_MSG VARCHAR(250) OUTPUT
AS
DECLARE
#c_ErrMsg VARCHAR(200)
, #c_ErrNum VARCHAR(5)
, #c_Continue INT
, #c_Date VARCHAR(20)
/* Assign value to local variables */
SET #c_Date = GETDATE()
SET #c_Continue = 0
/* Run Validations */
IF EXISTS (SELECT 1 FROM CONFIG(NOLOCK) WHERE cfg_key = #CFG_KEY)
BEGIN
SET #c_ErrNum = 60001
SET #c_ErrMsg = 'Configuration Key (' + #CFG_KEY + ') already exist. Please check System Configuration. Error: ' + #c_ErrNum
SET #CFG_MSG = #c_ErrMsg
SET #c_Continue = 1
END
/* Create Configuration */
SET #CFG_MSG = ''
IF #c_Continue = 0
BEGIN
IF NOT EXISTS(SELECT 1 FROM CONFIG(NOLOCK) WHERE cfg_key = #CFG_KEY)
BEGIN
INSERT INTO CONFIG
(
cfg_key , cfg_short_value , cfg_long_value , cfg_desc ,cfg_short_desc
, cfg_misc1 , cfg_misc2 , cfg_misc3 , cfg_misc4
, cfg_misc5 , cfg_add_who , cfg_edit_date , cfg_edit_who
)
VALUES
(
#CFG_KEY , #CFG_SHORTVALUE , #CFG_LONGVALUE , #CFG_DESC , #CFG_SHORT_DESC
, #CFG_MISC1 , #CFG_MISC2 , #CFG_MISC3 , #CFG_MISC4
, #CFG_MISC5 , #CFG_USER , #c_Date , #CFG_USER
)
SET #CFG_MSG = 'Configuration has been created.'
END
END
GO

Your stored procedure that returns the value has a parameter declared as OUTPUT, something like this:
CREATE PROCEDURE my_returning_proc (#ret VARCHAR(10) OUTPUT) AS
BEGIN .... END
If you want to use this value you need to call the STORED PROCEDURE like this:
DECLARE #var VARCHAR(10);
EXEC my_returning_proc #var OUTPUT;
PRINT #var
The key's here is to add OUTPUT into EXEC statement
EDIT: Thanks for providing example.
For your case you would call the stored procedure like this:
DECLARE #var_returned VARCHAR(250);
EXEC [dbo].[isp_CREATE_CONFIG] 'BLAH', 0, 'BLAH', 'BLAH', 'BLAH', ......, #var_returned OUTPUT

By return a value, I assume you mean using return. You can also declare output parameters for the stored procedure.
Here is how:
declare #retval int;
exec #retval = <stored procedure call>
Here is a simple code sample anyone can try:
create procedure dum as return 5
declare #retval int;
exec #retval = dum
select #retval
I use this technique all the time to return status from stored procedures.

Related

Get result parameter of stored procedure in exec clause

I have a stored procedure that returns multiple parameters:
CREATE PROCEDURE [dbo].[TestSP]
#Test1 INT
, #Test2 UNIQUEIDENTIFIER
--some inserts and alters here
SELECT TOP 1
#Parameter1 AS Design
, #Parameter2
, #Parameter3
FROM Table
I want to use EXEC into another stored procedure and get ONLY #Parameter1 (Design)
So I want to get #Parameter1 after EXEC stored procedure, so I think about OUTPUT, but it doesn't work, is there a way to achieve this?
CREATE PROCEDURE [dbo].[SecondStoredProcedure]
#Sender1 INT
, #Sender2 UNIQUEIDENTIFIER
DECLARE #ReturnedParameter1 INT
EXEC [dbo].[TestSP] #Test1 = #Sender1, #Test2 = #Sender2 OUTPUT [Design]
INTO #ReturnedParameter1
SELECT #ReturnedParameter1
That procedure creates a resultset, and has no output parameters. You can capture a resultset with insert into ... exec, like this:
use tempdb
go
CREATE PROCEDURE [dbo].[addDesign]
#Test1 INT
,#Test2 UNIQUEIDENTIFIER
as
begin
--some inserts and alters here
SELECT
1 AS Design
, 2 as Foo
, 3 as Bar
end
go
declare #rv table(Design int, Foo int, Bar int)
declare #test2 uniqueidentifier = newid()
insert into #rv
exec addDesign 1, #test2
declare #design int = (select Design from #rv)
select #design
I suggest using an output parameter as explained in the official docs.
Here is how your code might look in this case:
use tempdb
go
create procedure [dbo].[addDesign]
(
#Test1 int
, #Test2 uniqueidentifier
, #Design int out
)
as
begin
set nocount on;
--some inserts and alters here
-- Set the return parameter
set #Design = #Parameter1;
-- Select the return results
SELECT TOP 1
#Parameter1
, #Parameter2
, #Parameter3
FROM dbo.MyTable;
-- Return status code, proc ran OK
return 0;
end
go
create procedure [dbo].[SecondStoredProcedure]
(
#Sender1 int
, #Sender2 uniqueidentifier
)
as
begin
set nocount on;
declare #ReturnedParameter1 int;
exec dbo.TestSP #Test1 = #Sender1, #Test2 = #Sender2, #Design = #ReturnedParameter1;
select #ReturnedParameter1;
-- Return status code, proc ran OK
return 0;
end
go
Note: This demonstrates the 3 ways information can be returned from a stored procedure, the result code (only 1), output parameters (0-N) and result sets (0-N).

How To Declare Input-Output Parameters In SQL Server Stored Procedure/Function?

In Oracle,
We can declare an input-output parameters (not just input or output) like the following:
Create Or Replace Procedure USERTEST.SimpleInOutProcedure(
p_InputInt Int,
p_OutputInt out Int,
p_InputOutputInt in out Int
) AS
BEGIN
p_OutputInt := p_InputInt + 1;
p_InputOutputInt := p_InputOutputInt + p_InputOutputInt;
END;
However, as I try to declare such in SQL Server, the script would not compile:
create procedure SimpleInOutProcedure
#p_InputInt int, #p_OutputInt int input output
As
Begin
Select * from TestTableCommonA;
End
The word "input" is not expected, thus not blue-colored in the SQL Server Management Studio:
What's wrong with my script, how to declare input-output parameters in SQL Server Stored Procedure/Function?
I want to do this because I need to create "equivalent" reader for SQL Server DB which previously was created for Oracle DB and has the reader for in/out parameters.
If you declare a parameter as OUTPUT, it acts as Both Input and OUTPUT
CREATE PROCEDURE SimpleInOutProcedure
(
#p_InputInt INT,
#p_OutputInt INT OUTPUT
)
AS
BEGIN
SELECT
#p_OutputInt = #p_OutputInt
END
GO
DECLARE #p_OutputInt int = 4
EXEC SimpleInOutProcedure #p_InputInt = 1, #p_OutputInt = #p_OutputInt OUTPUT
SELECT #p_OutputInt
This is sample code for SQL Input & Output parameter.
CREATE PROCEDURE [dbo].[sample_Insert]
#name varchar(500),
#entryby int,
#RetVal INT = 0 OUT
AS
SET NOCOUNT ON
INSERT INTO dbo.Master
( name ,
entry_date ,
entry_by
)
VALUES ( #name , -- service_name - varchar(1000)
dbo.GetActDate() , -- entry_date - datetime
#entryby -- entry_by - int
)
IF ##ERROR = 0
BEGIN
SET #RetVal = 1 -- 1 IS FOR SUCCESSFULLY EXECUTED
End
ELSE
BEGIN
SET #RetVal = 0 -- 0 WHEN AN ERROR HAS OCCURED
End
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON

SQL Server stored procedure: verify CRUD operation success/failure using output variable

I am trying to create a SQL Server stored procedure to handle updates to a table using some dynamic SQL. The table name required for the update is stored in a table that correlates a table id to a category id. Once the table name is retrieved and the table id is not null, I update the table using a dynamic SQL query as shown below:
CREATE PROCEDURE [dbo].[SP_EBS_CustomForms_SetCategoryData]
(#flag int output,
#cat_id int,
#sort int,
#value varchar(50),
#active int,
#enum int)
AS
BEGIN
DECLARE #tbl as varchar(50)
DECLARE #tbl_id as int
DECLARE #sql nvarchar(max)
BEGIN TRY
SET #tbl_id = (SELECT [tbl_id]
FROM [demodata].[dbo].[ebscustomforms_cattable]
WHERE cat_id = #cat_id)
IF #tbl_id IS NOT NULL
BEGIN
SET #tbl = (SELECT table_name
FROM ebscustomforms_enumtable
WHERE tbl_id = #tbl_id)
SET #sql = 'UPDATE ' + #tbl + ' SET [sort_order] = #sort, [value] = #value, [active] = #active WHERE [enum_id] = #enum'
EXECUTE sp_executesql #sql, N'#sort int, #value varchar(50), #active int, #enum int', #sort, #value, #active, #enum
SET #flag = 0
RETURN #flag
END
END TRY
BEGIN CATCH
IF ##ERROR <> 0
BEGIN
SET #flag = 1;
RETURN #flag
END
END CATCH
END
I want this stored procedure to return an int value indicating whether the stored procedure was successful (0) or failed (1) updating the table.
Points of error are as follows:
#tbl_id variable is null
#tbl is either null or an empty varchar
The table to be updated does not have a record where [enum_id] = #enum
I have noticed that when I try to update a record that does not exist, the procedure seems to return as successful i.e. #flag = 0. However, I would imagine that an error should be thrown because the record does not exist.

How to use optional parameter in stored procedure

I have a stored procedure which looks like
CREATE PROCEDURE Update-all
( #RowID INT,
#Parameter1 NVARCHAR(50),
#Parameter2 INT
)
As
....
i will be passing #Parameter1 / #Parameter2 based on different conditions.
if i don't pass #Parameter1 / #Parameter2 ,i am getting a error the stored procedure expects #parameter1/#parameter1 which is not supplied . Any ideas how to fix this issue?
You need to supply default values for the parameters.
CREATE PROCEDURE Update-all
( #RowID INT,
#Parameter1 NVARCHAR(50) = NULL,
#Parameter2 INT = NULL
)
As
....
You need to provide defaults for your parameters. e.g.
create procedure Test1 (
#rowid int,
#Param1 nvarchar(50) = null,
#Param2 int = 0 )
as
print 'rowid=' + convert(varchar(20), #rowid)
print 'param1=' + #Param1
print 'param2=' + convert(varchar(20), #Param2)
exec Test1 5
exec Test1 5, 'testing'
exec Test1 5, 'testing', 198
Add some default values to parameters:
CREATE PROCEDURE Update-all
( #RowID INT,
#Parameter1 NVARCHAR(50) = '',
#Parameter2 INT = 0
)

SQL Server: Return uniqueidentifier from stored procedure

Can I return UNIQUEIDENTIFIER from a stored procedure using the RETURN statement or is it only by using the OUTPUT statement?
i.e to return the PersonID UNIQUEIDENTIFIER:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT
AS
DECLARE #Count INT
DECLARE #JobFileGUID UNIQUEIDENTIFIER
-- Check if job exists?
SET #Count = (SELECT COUNT(Name) AS Name FROM Person WHERE Name=#Name)
IF #Count < 1
BEGIN
SET #PersonGUID = NEWID();
INSERT INTO Person
(PersonID, Name, [Desc])
VALUES (#PersonGUID, #Name, #Desc)
END
SELECT #PersonGUID = Person.PersonID
FROM Person
WHERE Name = #Name
RETURN #PersonGUID
GO
Thanks
In stored procedure - only using the OUTPUT statement. In function - return.
Use:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT,
#PersonGUID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET #PersonGUID = ...
END
How to call:
DECLARE
#name NVARCHAR(255),
#desc TEXT,
#personGUID UNIQUEIDENTIFIER
SET #name = 'Bob'
SET #desc = 'One handsome man.'
EXEC [Database].[schema].CreatePerson #name, #desc, #personGUID OUTPUT
From the documentation you can actually see that a return in a stored procedure is actually used as a response code, hence you get the exception when trying to return a uniqueidentifier.
https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/return-data-from-a-stored-procedure?view=sql-server-ver16#return-data-using-a-return-code
How I solved it, is by just performing a SELECT after the insert of the generated unique identifier.
DECLARE #ReportId UNIQUEIDENTIFIER;
SET #ReportId = NEWID();
INSERT INTO [dbo].[Report]
([ReportId]
,[ReportName])
VALUES
(#ReportId
,#ReportName)
SELECT #ReportId as ReportIdInternal
You'll have to see how to perform that with multiple selects though.
CREATE TABLE [dbo].[tbl_Clients]( [ClientID] [uniqueidentifier] NULL, [ClientName] varchar NULL, [ClientEnabled] [bit] NULL ) ON [PRIMARY]
GO
CREATE PROCEDURE [dbo].[sp_ClientCreate] #in_ClientName varchar(250) = "New Client 123", #in_ClientEnabled bit, #out_ClientId uniqueidentifier OUTPUT AS
SET #out_ClientId = NEWID();
INSERT INTO tbl_Clients(ClientId, ClientName, ClientEnabled) VALUES( #out_ClientId, #in_ClientName, #in_ClientEnabled)
DECLARE #return_value int, #out_ClientId uniqueidentifier
EXEC #return_value = [dbo].[sp_ClientCreate] #in_ClientName = N'111', #in_ClientEnabled = 1, #out_ClientId = #out_ClientId OUTPUT
SELECT #out_ClientId as N'#out_ClientId'
SELECT 'Return Value' = #return_value
GO
Result:-59A6D7FE-8C9A-4ED3-8FC6-31A989CCC8DB