如何在SQL Server中添加一个判断条件的约束
怎么在SQL Server中添加一个判断条件的约束
sql server数据库表中有两个字段,一个rodNo一个machineNo,现在想添加一个判断约束,即为当rodNo相同时,machineNo必须也相同,不然不允许插入数据,
比如:
rodNo machineNo
a01 b01
a01 b01
可以
但是
rodNo machineNo
a01 b01
a01 b01
a01 b02
就不可以了
是否可以实现?
------解决方案--------------------
触发器
------解决方案--------------------
------解决方案--------------------
典型的用触发器来实现
------解决方案--------------------
create trigger tri_tbname_ins on tbname
instead of insert
as
begin
if exists(select 1 from inserted i
where exists(select 1 from tb where rodNo=i.rodNo and machineNo=i.machineNo))
begin
insert tb select * from inserted i
where exists(select 1 from tb where rodNo=i.rodNo and machineNo=i.machineNo)
end
end
------解决方案--------------------
------解决方案--------------------
sql server数据库表中有两个字段,一个rodNo一个machineNo,现在想添加一个判断约束,即为当rodNo相同时,machineNo必须也相同,不然不允许插入数据,
比如:
rodNo machineNo
a01 b01
a01 b01
可以
但是
rodNo machineNo
a01 b01
a01 b01
a01 b02
就不可以了
是否可以实现?
------解决方案--------------------
触发器
------解决方案--------------------
------解决方案--------------------
典型的用触发器来实现
------解决方案--------------------
create trigger tri_tbname_ins on tbname
instead of insert
as
begin
if exists(select 1 from inserted i
where exists(select 1 from tb where rodNo=i.rodNo and machineNo=i.machineNo))
begin
insert tb select * from inserted i
where exists(select 1 from tb where rodNo=i.rodNo and machineNo=i.machineNo)
end
end
------解决方案--------------------
------解决方案--------------------
- SQL code
CREATE TRIGGER tri_insert ON tb INSTEAD OF INSERT AS BEGIN IF EXISTS (SELECT 1 FROM inserted i, tb t WHERE i.rodno = t.rodno AND i.machineno <> t.machineno) BEGIN rasieerror ( '插入失败!插入数据不符合要求' ,16,1 ) END END
------解决方案--------------------
- SQL code
CREATE TRIGGER tri_insert ON tb INSTEAD OF INSERT AS BEGIN IF EXISTS (SELECT 1 FROM inserted i, tb t WHERE i.rodno = t.rodno AND i.machineno <> t.machineno) BEGIN RAISERROR( '插入失败!插入数据不符合要求' ,16,1 ) END END