当前位置: 代码迷 >> Sql Server >> 如何在SQL Server中添加一个判断条件的约束
  详细解决方案

如何在SQL Server中添加一个判断条件的约束

热度:419   发布时间:2016-04-25 01:19:52.0
怎么在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 code
CREATE TRIGGER tri_insertON tbINSTEAD OF INSERTASBEGIN   IF EXISTS (SELECT 1             FROM   inserted i,                    tb t             WHERE  i.rodno = t.rodno                    AND i.machineno <> t.machineno)BEGIN rasieerror ( '插入失败!插入数据不符合要求' ,16,1 )ENDEND
------解决方案--------------------
SQL code
CREATE TRIGGER tri_insertON tbINSTEAD OF INSERTASBEGIN   IF EXISTS (SELECT 1             FROM   inserted i,                    tb t             WHERE  i.rodno = t.rodno                    AND i.machineno <> t.machineno)BEGIN RAISERROR( '插入失败!插入数据不符合要求' ,16,1 )ENDEND
  相关解决方案