如何防止无效数据插入SQL
在我的项目中,我需要动态地检查条件。要实现此目的,请按如下方式创建表如何防止无效数据插入SQL,sql,asp.net-mvc,oracle,sql-insert,Sql,Asp.net Mvc,Oracle,Sql Insert,在我的项目中,我需要动态地检查条件。要实现此目的,请按如下方式创建表 CREATE TABLE myconditions ( conditionid INT IDENTITY PRIMARY KEY CLUSTERED, minvalue INT, maxvalue INT, result INT ) 这些数据包括: insert into MyConditions (MinValue, MaxValue, Resul
CREATE TABLE myconditions
(
conditionid INT IDENTITY PRIMARY KEY CLUSTERED,
minvalue INT,
maxvalue INT,
result INT
)
这些数据包括:
insert into MyConditions (MinValue, MaxValue, Result)
values (10, 20, 1), (20, 30, 2), (null, 10, 3), (30, null, 3)
我用这个表格数据来检查年龄范围
declare @age int = 25 --this represents user age
select *
from MyConditions
where @age > isnull(MinValue, @age - 1)
and @age <= isnull(MaxValue, @age)
但是现在的问题是,假设有人插入了一个无效的范围,比如值5,25,4,我的意思是这是无效的,因为在数据库中已经有10,20,1这个值。当@age=15时,这两种情况都将通过。所以我需要防止5,25,4这个值相加。如果有人需要添加此5、25、4范围,则应删除此范围值10、20、1
我使用ASP.NET MVC应用程序将这些数据插入数据库。我该怎么做?在我的项目中,我使用的是Oracle。在这个问题中,我使用了MS SQL示例代码,但我需要oracle,您需要为此使用触发器或用户定义的函数 一个简单的检查约束只能在一次检查中检查值。坦率地说,我认为触发是更常见的方法
这两种方法的确切语法都取决于数据库,您已经指定了其中两种方法,因此更详细的答案是不可行的。这种数据完整性验证很难以一种健壮且高效的方式实现
首先,很大程度上取决于重叠范围的定义。例如,有人可能会争辩说,您的所有样本数据范围都是无效的:maxvalue=10与minvalue=10重叠,假设边界使用>=进行测试,先生,您能给我样本代码吗。请如何编写触发器或函数来实现这一点。如何使用OracleSql请帮助我,先生。求求你了:我真的受够了。如何编写的触发器或函数this@ErwinBrandstetter plz帮助me@APC非常抱歉,先生,在这个问题中,我使用了示例ms sql代码,但我计划使用oracle。所以请帮帮我,为我做错的事道歉谢谢你,先生。非常感谢你的努力
create or replace trigger myconditions_trg
for insert or update of minvalue, maxvalue
on myconditions
compound trigger
type condition_array is table of int
index by binary_integer;
conditions condition_array;
procedure validate_range (p_id in int) is
overlapping_range exception;
dummy char(1);
begin
begin
select null into dummy
from myconditions t1
, myconditions t2
where t1.conditionid = p_id
and t2.conditionid != p_id
and t1.minvalue != t2.minvalue
and (
t1.minvalue between t2.minvalue and t2.maxvalue
or
t1.maxvalue between t2.minvalue and t2.maxvalue
)
and rownum = 1;
raise overlapping_range;
exception
when no_data_found then
-- what we're hoping for, no overlaps found
null;
end;
exception
when overlapping_range then
raise_application_error(-20000,
'overlapping range for id #' || p_id);
end validate_range;
procedure validate_ranges is
l_id int;
begin
l_id := conditions.first;
loop
exit when l_id is null;
validate_range (l_id);
l_id := conditions.next(l_id);
end loop;
conditions.delete;
exception
when others then
conditions.delete;
raise;
end validate_ranges;
BEFORE EACH ROW is
begin
-- store id to validate
conditions(:new.conditionid) := 1;
end before each row;
AFTER STATEMENT is
begin
validate_ranges;
end after statement;
end myconditions_trg;