简体   繁体   English

插入触发器以更新第二张表

[英]Insert trigger to update second table

I am trying to write an insert trigger that performs the following 我正在尝试编写执行以下操作的插入触发器

I have a member table T1(ID, score, sex) and a matching table T2(ID1,ID2,Dscore). 我有一个成员表T1(ID,分数,性别)和一个匹配表T2(ID1,ID2,Dscore)。 These two tables are initially empty. 这两个表最初是空的。 When an insert is made on T1, a trigger will fire such that it will insert information into table T2 depending on the row that was inserted in T1. 在T1上进行插入时,将触发触发器,从而根据在T1中插入的​​行将信息插入表T2中。 If the insert on T1 is the first row then nothing will be inserted into T2. 如果T1上的插入是第一行,则不会将任何内容插入T2。 If a subsequent row is inserted into T1 then the difference in scores (absolute value) between the inserted row and any previously rows in T1 will be inserted in T2 provided it is of different sex (male=1 and female=0).Below are a few examples 如果将下一行插入到T1中,则插入的行与T1中任何先前行之间的得分差异(绝对值)将插入T2中,前提是其性别不同(男性= 1和女性= 0)。一些例子

insert into member values(1,5,1) 插入成员值(1,5,1)

ID         score       sex
 1            5           1

First row so no action on table T2 第一行,因此对表T2无效

ID1        ID2        Dscore

insert into member values(2,6,0) 插入成员值(2,6,0)

 ID         score       sex
    1           5               1
    2           6               0

Second row and opposite sex type, so insert all the possible differences
ID1        ID2        Dscore
2            1             1

insert into member values(3,7,1) 插入成员值(3,7,1)

ID         score       sex
    1           5           1
    2           6           0
    3           7           1


ID1        ID2        Dscore
    2             1          1
    3             2          1

I am stuck on the part where I can insert ID2 and Dscore into t2. 我被困在可以将ID2和Dscore插入t2的部分。 This is what I've written so far 这是我到目前为止写的

   CREATE TRIGGER MEMBER_INSERT_TRI
ON Employee.Dbo.T_1 
After INSERT AS 
Declare @ID int 
Select @ID = (Select ID from inserted)
IF @ID > 1
Begin 
Declare @ID2 as int 
Set @ID2 = @ID2 +1
Insert into Employee.dbo.T_2 
(
    ID1,
    ID2,
    Score
)

Select 
ID,
@ID2,
Score
From 
    Inserted
END

Thank you 谢谢

You can use INSERTED view to get inserted/updated row in trigger, If you are talking about MS SQL Server. 如果您正在谈论MS SQL Server,则可以使用INSERTED视图在触发器中获取插入/更新的行。 Then you can call a stored procedure to make it happen. 然后,您可以调用存储过程来实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM