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

SqlServer中如何在同服务器中的不同数据库间建立约束
同一个sqlServer服务器,有两个库,
1、table1中表ProductType。字段(ID,TypeName)
2、table2中表Product。字段(ID,ProName,TypeNameID)

现在要在table1的ID,和Table2的TypeNameID间建立约束。即在table2中插入行时,要检查其中的TypeNameID在table1中是否存在。
Sql没有跨库间的外键约束。用触发器,检查到错误时,数据已经插入到数据库中了。

请教大家有没有什么好的方法(就在数据库中实现,不在外部的应用程序中实现)。

------解决方案--------------------
用触发器应该没有问题


CREATE TRIGGER iutrg_ProductType ON table2 FOR INSERT, UPDATE
AS
IF SELECT COUNT(*) FROM inserted <> ( SELECT COUNT(*) FROM table1.dbo.ProductType pt INNER JOIN inserted p ON pt.ID = p.TypeNameID )
ROLLBACK
GO
------解决方案--------------------

create table table1 (ID int, TypeName varchar(100))

create table table2 (ID int,ProName varchar(100),TypeNameID int)
go

create trigger tr_test on table2 
for insert, update 
as 
if exists (select * from inserted where TypeNameID not in (select id from 库1.dbo.table1))
begin
raiserror('输入的值不在table1中',16,1)
rollback 
end
go


insert into table2 select 1,'aa',10

select * from table2


drop table table1,table2