我不能保证这遵循了我刚刚了解到的最佳实践,但是我不时会遇到这种需求,我一直想学习这一点,所以我认为这是使用而不是触发器。
create table Country (
id int primary key not null identity(1,1)
,name varchar(10)
)
go
create table Item (
id int primary key not null identity(1,1)
,country_id int references Country(id)
,data varchar(100)
)
go
create view ItemView as
select C.name, I.data
from Item I inner join Country C on I.country_id = C.id
go
create trigger tr_Item_IOI on ItemView
instead of insert as begin
set nocount on
-- add the country if it does not exist
if(not exists (select C.id from Country C inner join inserted I on C.name = I.name))
insert into Country select distinct name from inserted
-- insert an item using the country id for the inserted country name
insert into Item (country_id, data)
select C.id, I.data
from Country C inner join inserted I on C.name = I.name
end
go
insert into ItemView values
('USA', '123')
,('Canada', '4545')
,('Mexico', '4363')
,('USA', '3434')
go
select * from ItemView
select * from Country
select * from Item