SQL Advanced - Implementation of Triggers

/*

1. Trigger syntax:

Create Trigger Name
    on table name
    for [insert| update | delete] -- choose one of three
    as
    
    --Logical statement
    
    go
    
2. There are two virtual tables in the trigger, and the table structure of the two virtual tables is consistent with the structure of the operating table
Inserted table, deleted table respectively

*/


Create Trigger [dbo].[tri_Student_i]
On [dbo].[Student]
for insert
As
 declare @id int
 declare @name varchar(50)
 declare @age int


 select @id=studentid,@name=name ,@age=age from Inserted;


 update Student1 set studentid=@id,name=@name,age=@age  where name =@name and age =@age

 if @@rowcount=0
  begin
    insert into Student1 values (@id,@name,@age)

  end

GO



 

 

 

Attach the demo table structure:

CREATE TABLE [dbo].[Student](
    [StudentID] [int] NOT NULL,
    [name] [varchar](50) NULL,
    [age] [int] NULL
)
CREATE TABLE [dbo].[Student1](
    [StudentID] [int] NOT NULL,
    [name] [varchar](50) NULL,
    [age] [int] NULL
)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324934606&siteId=291194637