I have 3 insert stored procedures each SP inserts data in 2 different tables
Table 1 Table 2
idPerson idProduct
name productName
phoneNumber productdescription
FK-idProduct
SP for table 1 SP for table 2
create procedure test1 create procedure test2
WITH WITH
EXECUTE as caller EXECUTE as caller
AS AS
declare declare
#idPerson int, #idProduct int,
#name varchar(20), #productName varchar(50),
#phone varchar(20) #productoDescription varchar(50)
SET nocount on; SET nocount on;
Begin Begin
insert into table1( insert into table2(
idPerson, idProduct,
name, productName,
phone) productDescription)
values( values(
#idPerson, #idProduct,
#name, #productName,
#phone) #productDescription)
end end
I need to call stored procedure test 2 from stored procedure test 1 and insert the FK-ID in the table 1
Simply call test2 from test1 like:
EXEC test2 #newId, #prod, #desc;
Make sure to get #id using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:
SELECT #newId = SCOPE_IDENTITY()
You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:
SELECT #NewIdOutputParam = SCOPE_IDENTITY()
Then in test1, retrieve it like so:
DECLARE #NewId INTEGER
EXECUTE test2 #NewId OUTPUT
-- Now use #NewId as needed
First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table
SET IDENTITY_INSERT table2 ON;
before the insert.
So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID
EXEC test2 'productName', 'productDescription'
SET #newID = SCOPE_IDENTIY()
or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID
Related
Hi I have a store procedure which insert data into a table1 and there is another store procedure which insert data in table2 I need to insert table2.ID in table1 while updating I am calling second store procedure in first and it returns me the Id as an output parameter but it didn't get updated.
SP1 :
ALTER PROCEDURE [dbo].[updateSP]
#prm1 varchar(30),
#prm2 varchar(20),
#prm3 varchar(20),
#prm3 varchar(max)
AS
BEGIN
SET NOCOUNT OFF;
DECLARE #ID int
exec SPInsert #ID OUTPUT, #prm1, #prm2 , #prm3
update tbl1 set status = prm1, updated_by = prm2, updated_date = GETDATE(), reason_id = #ID where student_no = prm3
END
SP2 :
ALTER PROCEDURE [dbo].[SPInsert]
#prm1 varchar(30),
#prm2 varchar(20),
#prm3 varchar(20),
#prm3 varchar(max),
#ID output,
AS
BEGIN
Insert into tbl2 (student_no, reason_txt, created_by, created_date)Values(#prm1 ,#prm2 ,#prm3 , GETDATE())
Select #ID = Scope_Identity()
END
I have the following stored procedure
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
AS
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
SELECT #new_identity = SCOPE_IDENTITY()
SELECT * FROM NameAge where Id = #new_identity
Is there are a more efficient way to return the last inserted record complete with id and associated data?
Use Insertedwithin output clause,
As the follwoing:
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
AS
DECLARE #MyTableVar table(
Name varchar(50),
Identifier uniqueidentifier
;
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
OUTPUT INSERTED.Name, INSERTED.Identifier
INTO #MyTableVar
SELECt Name,Identifier from #MyTableVar
Refreance:
Best way to get identity of inserted row?
SCOPE_IDENTITY() is used to get the last generated Identity value in an identity column in your scope , For GUID values either you get the guid before you insert it like I have done in the code below , or you use OUTPUT clause to get the guid generated by the Insert statement.
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128)
AS
BEGIN
SET NOCOUNT ON;
Declare #NewID UNIQUEIDENTIFIER = NEWID();
insert into NameIdentifier ( Name, Identifier)
values( #name, #NewID);
SELECT * FROM NameAge where Id = #NewID;
END
This should give you your desired functionality.
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
#Ret int Output
AS
BEGIN
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
END
SET #Ret = ##IDENTITY
EDIT: This will return the id of your newly inserted row.
You can achieve this by using the output clause of SQL Server, you can read more about this here
if exists (select 1 from sys.tables where name = 'NameIdentifier ')
drop table NameIdentifier
create table NameIdentifier
(
id BIGINT IDENTITY(1,1)
,Name VARCHAR(100)
,Identifier uniqueidentifier
)
DECLARE #id TABLE
(
ID BIGINT
)
INSERT INTO NameIdentifier (Name,Identifier)
OUTPUT INSERTED.id INTO #id
VALUES('abcd',NEWID())
SELECT * FROM NameIdentifier N, #id I where N.id = I.id
I have a table Partners generated by
CREATE TABLE Partners (
id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID(),
name NVARCHAR(50) NOT NULL,
email NVARCHAR(254) NOT NULL, -- 254 is optimal length according to http://stackoverflow.com/questions/1199190/what-is-the-optimal-length-for-an-email-address-in-a-database
PRIMARY KEY (id)
);
and a attempt at a sproc for inserting a row and retrieving the id of the inserted row:
CREATE PROCEDURE AddPartner
#name NVARCHAR(50), #email NVARCHAR(254)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Partners (name,email)
OUTPUT INSERTED.id INTO #new_guid
VALUES (#name,#email)
SELECT #new_guid
END
Suppose I want to (1) call AddPartner with (name,email) equal ('some dude','dude192#gmail.com) and return the id (call it dude_id) so that I can later (2) use it when I insert another row:
INSERT INTO Answers (question_id,partner_id,val) VALUES (1,dude_id,24);
How exactly can I do that? And will having GO statements between (1) and (2) ruin everything?
Add Output Parameter to your procedure
CREATE PROCEDURE Addpartner (#name NVARCHAR(50),
#email NVARCHAR(254),
#new_guid UNIQUEIDENTIFIER output)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Partners
(name,email)
OUTPUT INSERTED.id INTO #new_guid
VALUES (#name,#email)
END
DECLARE #new_guid AS UNIQUEIDENTIFIER
EXEC Addpartner 'some dude', 'dude192#gmail.com', #new_guid output
INSERT INTO Answers
(question_id,partner_id,val)
VALUES (#output_identity,'dude_id',24);
I want to write a stored procedure to loop through the table which has membership id and person id details and pass it as variable to stored procedure.
Any thoughts on how to do it. Any help is highly appreciated.
DECLARE #membership NUMERIC(9)
DECLARE #person_id NUMERIC(9)
DECLARE #id_num INT
WHILE (
set #id_num=id_num+1
SELECT membership_id,person_id FROM [dbo].[reb] WHERE id_num <1160
EXEC p_get_details #membership_id, person_id
You have two options. first one is to pass two parameters to procedure p_get_details , each parameter being a comma separated string containing concatenated values of membership_id and person_id columns.
Other is to pass the whole resultset from SELECT query as a Table Valued Parameter to the procedure.
If you need to call the proc again and again for different table values then u can create a temp table which has all the membership and personids
See If this code works for you:-
DECLARE #membership_id NUMERIC(9)
DECLARE #person_id NUMERIC(9)
if(OBJECT_ID('tempdb..#tempids') is not null)
drop table #tempids
SELECT membership_id,person_id
into #tempids
FROM [dbo].[reb]
WHERE id_num <1160
while exists(select 1 from #tempids)
begin
-- select 1 row which will be called by proc
select top 1 #membership_id=membership_id
#person_id =person_id
from #tempids
EXEC p_get_details #membership_id, #person_id
--delete the ids which have been called by proc
delete from #tempids
where
membership_id=#membership_id
person_id =#person_id
end
I have created a stored procedure to Move all items from IDx to IDz and as it does that it has to log some data of each row it moves. The procedure moves rows from ID< to IDz without any problems. But when it has to log the information it only logs the last row that is moved. What am i doing wrong?
this is my code:
USE [TrackIT_Test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MoveCustIDAndAlias]
-- Add the parameters for the stored procedure here
#SourceAdrID int,
#TargetAdrID int,
#Username varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #custID varchar(50)
set #custID = ''
declare #alias varchar(50)
set #alias = ''
-- Insert statements for procedure here
Select #custID = (CustID), #alias = (Alias) from dbo.Alias where AdrID = #SourceAdrID;
Insert into dbo.AliasMoveLog (CustID, Alias, Username) VALUES (#custID, #alias, #Username);
UPDATE dbo.Alias SET AdrID = #TargetAdrID WHERE AdrID = #SourceAdrID;
Can anyone help ?
Yes, I see your problem.
When you're using variable and set the variable value with select, it will store only the value in the last row.
You can try this to prove it:
CREATE TABLE tbl
(
col1 INT
);
INSERT INTO tbl VALUES (1);
INSERT INTO tbl VALUES (2);
INSERT INTO tbl VALUES (3);
DECLARE #x int
SELECT #x = col1 FROM tbl
PRINT #x -- will print 3
For your sp, try to change this line:
Select #custID = (CustID), #alias = (Alias) from dbo.Alias where AdrID = #SourceAdrID;
Insert into dbo.AliasMoveLog (CustID, Alias, Username) VALUES (#custID, #alias, #Username);
to:
Insert into dbo.AliasMoveLog (CustID, Alias, Username)
Select CustID, Alias, #Username from dbo.Alias where AdrID = #SourceAdrID;
More detail: SELECT #local_variable
Well you cannot bulk insert values once you declare the variable like that.
Simple way is to do it this way:
INSERT INTO dbo.AliasMoveLog (CustID, Alias, Username)
SELECT CustID, Alias, #Username FROM dbo.Alias WHERE AdrID = #SourceAdrID;