日期:2014-05-18  浏览次数:20547 次

触发器语句
我用的是MSSQL2000   +   WIN2000

现在在同一个数据库中有2个表
TABLE1   ,TABLE2
其中TABLE1
          ID   ,   UID   ,   DESC
TABLE2
          UID   ,   NAME

现在想修改,删除,插入TABLE2-> UID,能联动TABLE1-> UID

比如:TABLE2
这样
UID           NAME
  2               JOB
  3               TOM
  4               BUSH
TABLE1
  ID         UID           DESC
  1             2               COM
  2             4               CN

插入TABLE2
UID           NAME
2                 JOB
3                 TOM
4                 NEWID
5                 BUSH

这时候TABLE1联动为
ID           UID           DESC
1               2               COM
2               5               CN       '继续与BUSH数据对应

不知道怎么写这个语句


------解决方案--------------------
CREATE TRIGGER [uid_i] ON [dbo].[TABLE2]
FOR INSERT
AS
update TABLE1 set UID= (select uid from inserted)
from TABLE1
where uid=(select uid from deleted)

------解决方案--------------------
create table TABLE1 (ID int identity(1,1),UID int null,[DESC] varchar(20) null)
create table table2(UID int identity(1,1) , NAME varchar(20) null)
go
create trigger it_table2 on table2
for insert
as
begin
insert into table1(uid,[desc]) select uid,name from inserted
end
go
create trigger dt_TABLE2 ON TABLE2
FOR DELETE
AS
BEGIN
DELETE FROM TABLE1 FROM TABLE1 JOIN DELETED ON TABLE1.UID=DELETED.UID
END
GO
create trigger Ut_TABLE2 ON TABLE2
FOR UPDATE
AS
BEGIN
UPDATE TABLE1 SET UID=INSERTED.UID, [DESC]= INSERTED.NAME FROM TABLE1 JOIN INSERTED ON TABLE1.UID=INSERTED.UID
END


SELECT * FROM TABLE1
SELECT * FROM TABLE2

INSERT INTO TABLE2(NAME) VALUES( 'EGG ')

INSERT INTO TABLE2(NAME) VALUES( 'APPLE ')

INSERT INTO TABLE2(NAME) VALUES( 'pear ')

INSERT INTO TABLE2(NAME) VALUES( 'banana ')

INSERT INTO TABLE2(NAME) VALUES( 'grape ')

update table2 set name= 'plum ' where name= 'egg '

delete from table2 where name= 'apple '

drop table table1
drop table table2