update触发器 实现两张表外键的级联,,怎么实现?
update是怎么个原理啊,,比如说我有两张表,员工人事表employee和销售表sales;员工表的主码emp_no作为sales的外码,sales的主码为sale_id,要保证修改emp_no时sales的sale_id也要改变;这里肿么用触发器实现呢,,,,
[最优解释]
--像这种不用触发器的,确实主键除了一些特殊情况外,一般也不会更新的,下面只是个示例。。。
if exists (select 1 from sysobjects where name='FK_sales_employee_emp_no')
alter table sales drop constraint FK_sales_employee_emp_no
if objectproperty(object_id('employee'),'IsTable')=1 drop table employee
if objectproperty(object_id('sales'),'IsTable')=1 drop table sales
create table employee(
emp_no nvarchar(20) not null constraint [PK_emp_no] primary key clustered
)
go
create table sales(
sale_id int not null constraint [PK_sales] primary key clustered,
emp_no nvarchar(20) not null
)
go
alter table sales add constraint [FK_sales_employee_emp_no] foreign key(emp_no)
references employee(emp_no)
on update cascade
on delete cascade
go
insert into employee
select 'e1'
insert into sales
select 1,'e1'
go
select * from sales--更新前
update employee set emp_no='e2' where emp_no='e1'
select * from sales--更新后
go