How To Insert Multiple Values In Multiple Table Using Stored Procedure

In this blog, you will learn how to insert multiple values in the multiple tables, using stored procedure. You have inserted multiple values in the multiple tables one by one in SQL Server. Today, you will learn how to insert multiple values in multiple tables, using stored procedure. I have shared below queries and screenshots. You can follow them and you will easily understand how to insert multiple values in the multiple tables as well.
 
First, you make table  in SQL Server. I have made a table and named it as Empl. You can see SQL query, given below-
  1. create table Empl(E_ID int primary key identity(1,1), Name varchar(50), Designation varchar(50))  
I have made the second table and named it as Location and made relationship with Empl table. You can see SQL query, given below-
  1. create table Location(L_ID int primary key identity(1,1), Location varchar(50), E_ID int foreign key references Empl(E_ID))  
Now, I have made the third table and named it as Contact Emp and made relationship with Location table. You can see SQL query, given below-
  1. create table Contact_Emp (C_ID int primary key identity(1,1), Contact_Number varchar(50), Lo_ID int foreign key references Location(L_ID))  
These are three tables. Now, you will make a stored procedure and pass the parameters.Use @@identity, which is used to get the last inserted value, given below. You can see SQL query,  given below-
  1. create proc InsertMultiplevalue  
  2. (  
  3. @Name varchar(50),  
  4. @Designation varchar(50),  
  5. @Location varchar(50),  
  6. @Contact varchar(50)  
  7. )  
  8. as  
  9. begin  
  10.         insert into Empl values(@Name, @Designation)  
  11.         declare @Employee_ID int = @@identity  
  12.         insert into Location values(@Location,@Employee_ID)  
  13.         declare @Cot_ID int = @@identity  
  14.         insert into Contact_Emp values(@Contact,@Cot_ID)  
  15. end  
Finally, simply execute stored procedures and insert values in a single SQL query, given below-
  1. exec InsertMultiplevalue 'Asif Ali','Programmer','Hyderabad','[email protected]' 
Ebook Download
View all
SQL Jobs
Read by 0 people
Download Now!
Learn
View all