Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

oracle - SQL implement complex data validation?

I have a field which will contain a number, how can I do complex validation on that number on insertion?

I've got the validation algorithm implemented in java, just wondering how to "translate it" to SQL. Like I do some calculations with the inserted number and if the calculations don't match a predetermined result I want to reject that entry. How do I go about this?

I'm assuming I need to use a Check Constraint on the field, but how do I incorporate my validation algorithm in the constraint?

My algorithm looks like this

int s=0;
for (int i = 0; i < 10; i++)
    {
       s+=n%10;
       n/=10;
    }
if(n==s)
    //Good Value

Where n is initially my value to be inserted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since this check is complex you need to translate it in PL/SQL and add this logic in a BEFORE INSERT and/or a BEFORE UPDATE trigger.

Let's say you table is called MY_TABLE and contain a field MY_FIELD which as a NUMBER datatype :

CREATE OR REPLACE TRIGGER  TRIGGER_VALIDATE_N
BEFORE  
insert or update on MY_TABLE
for each row  
    s NUMBER := 0;
    n NUMBER;
begin  

    n := :OLD.MY_FIELD;

    FOR i IN 0..10 LOOP
        s := MOD(n,10);
        n := n/10;
    END LOOP;

    IF n = s THEN
        --Good Value
        null;
    ELSE
        --Wrong Value raise an error
        RAISE_APPLICATION_ERROR(-20000, TO_CHAR(:OLD.MY_FIELD)||' is a wrong value for MY_TABLE.MY_FIELD.');
    END IF;
end;  
/

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...