日期:2014-05-19  浏览次数:20655 次

2表间,某字段不能有相同记录,应该建立点什么关系来实现呢?
比如2表:user和admin表.
user有username,admin也有username
不能让他们有相同的username记录
应该建立什么来实现呢?

------解决方案--------------------
create trigger ti_user on [user]
for insert
as
if exists(select 1 from inserted i,admin where i.username=admin.username)
begin
raiserror( '用户名重复! ',16,1)
rollback tran
return
end
go
create trigger ti_admin on admin
for insert
as
if exists(select 1 from inserted i,[user] where i.username=[user].username)
begin
raiserror( '用户名重复! ',16,1)
rollback tran
return
end
go
------解决方案--------------------
晕哦,设计有问题

用触发器吧

create trigger tr_user
on user
for insert,update
as
if exists (select 1 from inserted i,admin a
where i.username=a.username)
begin
RAISERROR ( '不能有相同的username ', 16, 1)
ROLLBACK TRANSACTION
end
go

create trigger tr_admin
on admin
for insert,update
as
if exists (select 1 from inserted i,user a
where i.username=a.username)
begin
RAISERROR ( '不能有相同的username ', 16, 1)
ROLLBACK TRANSACTION
end
go