How to return an id and use it directly in another stored procedure? - sql

I want his stored procedure to return the inserted id
ALTER PROCEDURE [dbo].[InsertAddress_DBO]
#Name VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[Address]([Address_Name])
OUTPUT INSERTED.Address_Id
VALUES (#Name)
END
This one the same
ALTER PROCEDURE [dbo].[InsertDocumentation_DBO]
#Texte VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[Documentation]([Documentation_Text])
OUTPUT inserted.Documentation_Id
VALUES (#Texte)
END
And this one to use them and return her own -
like using the inserted id to put it into the next stored procedure as a parameter
ALTER PROCEDURE [dbo].[InsertEstablishmentByStrings_DBO]
#Establishment_Name VARCHAR(50),
#Address_Name VARCHAR(50),
#Documentation_Text VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Address_ID INT ,
#Documentation_ID INT
EXEC #Address_ID = [dbo].[InsertAddress_DBO]
#Name = "rue de la banchiesserie 85 Golback"
EXEC #Documentation_ID = [dbo].[InsertDocumentation_DBO]
#Texte = "né en 55555 restaurant fabuleux"
INSERT INTO [dbo].[Establishment]([Establishment_Name],[Address_Id],[Documentation_Id])
OUTPUT inserted.Establishment_Id
VALUES (#Establishment_Name,#Address_ID,#Documentation_ID)
END
However, I always get an error, because the stored procedure doesn't return the id when I execute it.
What is wrong in my code?
I would like to get the code I could use again and again in each stored procedure I have to execute. I already tried ##Identity, indent, scoped,... nothing works.

If you want to return something from stored procedure to the context of SQL query execution you may use a return statement or an output parameter. I would suggest you to use the second option. The first one is generally intended to return status of procedure execution.
ALTER PROCEDURE [dbo].[InsertAddress_DBO]
#Name VARCHAR(50),
#Address_ID INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[Address]([Address_Name])
VALUES (#Name)
SET #Address_ID = SCOPE_IDENTITY()
END
Than you can use returned value in your outer procedure
ALTER PROCEDURE [dbo].[InsertEstablishmentByStrings_DBO]
#Establishment_Name VARCHAR(50),
#Address_Name VARCHAR(50),
#Documentation_Text VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Address_ID INT ,
#Documentation_ID INT
EXEC [dbo].[InsertAddress_DBO]
#Address_ID = #Address_ID OUTPUT,
#Name = "rue de la banchiesserie 85 Golback"
...
END
An OUTPUT INSERTED clause you used doesn't returns data to the query execution context but send them to the output stream.

Your stored procedures should look like this, using an OUTPUT parameter, not trying to consume a RETURN value (which should never contain data) using a resultset. Also [don't] [put] [everything] [in] [square] [brackets] [unless] [you] [have] [to], [because] [all] [it] [does] [is] [hamper] [readability], and don't surround string literals with "double quotes" because that means something else in T-SQL.
CREATE OR ALTER PROCEDURE dbo.InsertAddress_DBO
#Name varchar(50),
#Address_Id int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.Address(Address_Name)
VALUES (#Name);
SELECT #Address_Id = SCOPE_IDENTITY();
END
GO
CREATE OR ALTER PROCEDURE dbo.InsertDocumentation_DBO
#Texte varchar(50),
#Doc_Id int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.Documentation(Documentation_Text)
VALUES (#Texte);
SELECT #Doc_Id = SCOPE_IDENTITY();
END
GO
Now, your main procedure can do this:
CREATE OR ALTER PROCEDURE dbo.InsertEstablishmentByStrings_DBO
#Establishment_Name varchar(50),
#Address_Name varchar(50),
#Documentation_Text varchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Address_ID INT ,
#Documentation_ID INT
EXEC dbo.InsertAddress_DBO
#Name = #Address_Name,
#Address_Id = #Address_ID OUTPUT;
EXEC dbo.InsertDocumentation_DBO
#Texte = Documentation_Text,
#Doc_Id = #Documentation_ID OUTPUT;
INSERT dbo.Establishment
(Establishment_Name, Address_Id, Documentation_Id)
OUTPUT inserted.Establishment_Id,
inserted.Address_ID, inserted.Documentation_ID
VALUES (#Establishment_Name,#Address_ID,#Documentation_ID);
END
GO
And you call it like this:
EXEC dbo.InsertEstablishmentByStrings_DBO
#Establishment_Name = 'Gaston''s',
#Address_Name = 'rue de la banchiesserie 85 Golback',
#Documentation_Text = 'né en 55555 restaurant fabuleux';
And get results like this:
Establishment_Id
Address_ID
Documentation_ID
1
1
1
Fully working example on db<>fiddle

Related

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

Executing a statement within a stored procedure, out parameter always returns 0

I need to insert some values into a table and to do this I created a stored procedure. 4 values are passed. And two values can be inserted straight into the table, for two other values an ID needs to be found.
I have three stored procedures. When I execute the main stored procedure, I can see that the two called stored procedures are executed and come up with the correct value. However this value is not passed into the parameter.
Both parameters #uid and #did retrun 0 (zero) into the table.
What am I doing wrong??
Kind regards,
Clemens Linders
SP MES_D_GetUserID, Pass a name and you gat an ID as string
SP MES_D_GetDOrderID, Pass a name and you get an ID as integer
The main stored procedure:
USE [AddOn_DEV_HE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MES_D_Consumed]
#WERKS nvarchar(4), #USERNAME nvarchar(50), #MACHID int, #DRINKORDER nvarchar(50)
WITH EXEC AS CALLER
AS
BEGIN
SET NOCOUNT ON;
Declare #uid AS varchar(10)
Declare #did AS int
Declare #OUTUID AS varchar(10)
Declare #OUTDID AS int
exec #uid = MES_D_GetUserID #USERNAME, #OUTUID OUTPUT;
exec #did = MES_D_GetDOrderID #DRINKORDER, #OUTDID OUTPUT;
INSERT INTO Demo_D_Consumed (Werks, UserID, MachID, DrinkID, TimeDate) VALUES (#WERKS, #uid, #MACHID, #did, GETDATE());
END
and these are the two other stored procedures :
USE [AddOn_DEV_HE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MES_D_GetDOrderID]
#DRINK nvarchar(50), #OUTDID int OUTPUT
WITH EXEC AS CALLER
AS
BEGIN
SET NOCOUNT ON;
SELECT RecordNr FROM DEMO_D_ORDERS WHERE Drink = #DRINK
END
USE [AddOn_DEV_HE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MES_D_GetUserID]
#USERNAME nvarchar(50), #OUTUID nvarchar(50) OUTPUT
WITH EXEC AS CALLER
AS
BEGIN
SET NOCOUNT ON;
SELECT UserLan FROM sysUsernames WHERE UserName = #USERNAME
END
Change them to be
ALTER PROCEDURE [dbo].[MES_D_GetDOrderID]
#DRINK nvarchar(50), #OUTDID int OUTPUT
WITH EXEC AS CALLER
AS
BEGIN
SET NOCOUNT ON;
SELECT #OUTDID = RecordNr FROM DEMO_D_ORDERS WHERE Drink = #DRINK
END
And
exec MES_D_GetDOrderID #DRINKORDER, #OUTDID OUTPUT;
Your #OUTDID will have the return value. Same with the other SP.

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;

Execute a stored procedure in another stored procedure in SQL server

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

Store the result of a stored procedure without using an output parameter

I have 2 stored procedures: up_proc1 and up_proc2.
This is (a simplified version of) up_proc2:
CREATE PROCEDURE dbo.up_proc2
#id_campaign uniqueidentifier, #id_subcampaign uniqueidentifier,
#id_lead uniqueidentifier, #offer NVARCHAR(1000) = NULL
AS
SET NOCOUNT ON
DECLARE #id UNIQUEIDENTIFIER
SELECT #id = id FROM prospects WHERE id_lead = #id_lead
AND id_campaign = #id_campaign AND id_subcampaign = #id_subcampaign
IF #id IS NULL
BEGIN
SET #id = newid ()
INSERT INTO prospects (id, id_campaign, id_subcampaign, id_lead, offer)
values (#id, #id_campaign, #id_subcampaign, #id_lead, #offer)
END
ELSE
BEGIN
UPDATE prospects set offer = #offer WHERE id=#id
END
SELECT #id AS ID
GO
From up_proc1 I call up_proc2. What I would like to achieve is to store the #id of up_proc2 in a variable declared in up_proc1. Is this possible without using an output parameter?
This is how up_proc1 looks like:
CREATE PROCEDURE dbo.up_proc1
AS
SET NOCOUNT ON
DECLARE #fromProc2 UNIQUEIDENTIFIER
-- NOT WORKING
-- select #fromProc2 = exec up_insertProspects [snip]
-- ALSO NOT WORKING
-- exec #fromProc2 = up_insertProspects [snip]
What you could do is store the output into a table variable:
DECLARE #tmpTable TABLE (ID UNIQUEIDENTIFIER)
INSERT INTO #tmpTable
EXEC dbo.up_proc2 ..........
and then go from there and use that table variable later on.
You can certainly consume this as an output parameter in proc2 without affecting how your C# code retrieves the eventual resultset.
ALTER PROCEDURE dbo.up_proc2
#id_campaign uniqueidentifier,
#id_subcampaign uniqueidentifier,
#id_lead uniqueidentifier,
#offer NVARCHAR(1000) = NULL,
#fromProc2 UNIQUEIDENTIFER = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
...
C# can ignore the new parameter since it is nullable (but since a single output parameter is more efficient than a data reader, you may consider updating your C# code to take advantage of the output parameter later).
Now in proc1:
ALTER PROCEDURE dbo.up_proc1
AS
BEGIN
SET NOCOUNT ON;
DECLARE #fromProc2 UNIQUEIDENTIFIER;
EXEC dbo.up_proc2
--... other parameters ...,
#fromProc2 = #fromProc2 OUTPUT;
-- now you can use #fromProc2
END
GO