我对触发器很新(在上个月之前从未使用它们)。
如何测试是否在一个具有唯一标识符的表中插入行并更新另一个表?
例如:
1 table 1
2 id 1 name max last: headroom
3 id 2 name john last: sewer<-- newly inserted
4
5 updated table 2
6 id 1 address: hhhhhhh initials: m.h.
7 id 2 address: gggggggg initials: <--update this
这是我更新的方式:
01 CREATE TRIGGER Alabama_ID_UPDATE_USERRWAY ON USERRWAY
02 FOR UPDATE
03 AS
04 BEGIN
05 SET NOCOUNT ON
06 IF (UPDATE(ST_LOCL_ID))
07 BEGIN
08 DECLARE @BRKEY VARCHAR(15)
09 SET @BRKEY = (SELECT BRKEY FROM inserted)
10 DECLARE @ALABAMA_ID VARCHAR(20)
11 SET @ALABAMA_ID = (SELECT ALABAMA_ID FROM USERBRDG WHERE USERBRDG.BRKEY = @BRKEY)
12
13 BEGIN
14 DECLARE @ST_LOCL_ID VARCHAR(4)
15 SET @ST_LOCL_ID = (SELECT SUBSTRING(USERRWAY.ST_LOCL_ID,1,4)FROM USERRWAY WHERE USERRWAY.BRKEY = @BRKEY AND ON_UNDER = '1')
16 END
17 BEGIN
18 IF(@ALABAMA_ID IS NOT NULL)
19 BEGIN
20 SET @ALABAMA_ID = STUFF(@ALABAMA_ID, 15, 4, @ST_LOCL_ID)
21 UPDATE USERBRDG SET USERBRDG.ALABAMA_ID = @ALABAMA_ID WHERE USERBRDG.BRKEY = @BRKEY
22 END
23 ELSE
24 BEGIN
25 SET @ALABAMA_ID = ('XXXXXXXXXXXXXXXXXXX')
26 SET @ALABAMA_ID = STUFF(@ALABAMA_ID, 15, 4, @ST_LOCL_ID)
27 UPDATE USERBRDG SET USERBRDG.ALABAMA_ID = @ALABAMA_ID WHERE USERBRDG.BRKEY = @BRKEY
28 END
29 END
30 END
31 END
32 GO
我想做的一个例子是:
如果有人在结构单元中插入一行,我需要更新:
UPDATE USERBRDG
SET USERBRDG.ALABAMA_ID = @ALABAMA_ID
WHERE USERBRDG.BRKEY = @BRKEY