October 9, 2022

How to create a TRIGGER function in SQL server to insert data from one table to another table

In this article we will see that how we can insert data from one table to another using ‘TRIGGER’ function in SQL server.

Create two Tables

i. customers

ii. orders

Table ‘customers’ —

create table customers(
customer_id int primary key,
first_name varchar(50)
)

Table ‘orders’ —

create table orders(
order_id int primary key identity,
price int,
customer_id int
)

Inserting data into table customers

insert into customers values(1,’John’),
(2,’Robert’),
(3,’David’),
(4,’John’),
(5,’Betty’)

Creating TRIGGER function

create trigger tri_ord
on customers
for insert
as
begin
Declare @customer_id int
select @customer_id = customer_id from inserted
insert into orders(customer_id) values(@customer_id)
print ‘Inserted successfully’
end
go
insert into customers values(10,’Amar’)

Sample Output

Output after performing TRIGGER function

Social Share Button :

Leave a Reply

Your email address will not be published. Required fields are marked *

chevron-down-circle
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram