当前位置: 代码迷 >> Sql Server >> 怎么设置这两个表关联
  详细解决方案

怎么设置这两个表关联

热度:55   发布时间:2016-04-27 16:48:07.0
如何设置这两个表关联?
CREATE   TABLE   [NewProduct]   (
[FactoryID]   [nvarchar]   (50)   primary   key,
[CustomerID]   [nvarchar]   (50)   ,
[Comment]   [nvarchar]   (255),
)
GO

CREATE   TABLE   [OldProduct]   (
[FactoryID]   [nvarchar]   (50)   primary   key,
[CustomerID]   [nvarchar]   (50)   ,
[Comment]   [nvarchar]   (255),
)
GO

insert   newproduct   values( '95588 ', 'ICBC ', 'nothing ')
insert   OldProduct   values( '95599 ', 'ABC ', 'nothing ')

现在要把两个表关联,实现 新插入的FactoryID在两个表中都是唯一的)
例如:不允许以下语句执行?
insert   newproduct   values( '95599 ', 'ABC ', 'nothing ')

谢谢

------解决方案--------------------
create trigger tri_name
on NewProduct
instead of insert
as
if not exists (select * from newproduct a where exists(select 1 from inserted where FactoryID=a.FactoryID)) and exists(select * from OldProduct b where exists(select 1 from inserted where FactoryID=b.FactoryID))
begin
insert newproduct select * from inserted
insert OldProduct select * from inserted
end
  相关解决方案