regular expressions inside a SQL IF statement
I know I can create basic comparison triggers (see below)
CREATE TRIGGER HospitalCheck
BEFORE INSERT ON Hospital
FOR EACH ROW
BEGIN
IF NEW.HospitalID > 9999 THEN
call fail('HOSPITAL CODE INVALID');
END IF;
END
How would I go about using a regular expression that only allowed numbers? (instead of the >9999) (the equivalent of SELECT string to check REGEXP '^[0-9]+$')
I tried:
IF NEW.HospitalID REGEX '^[0-9]+$' THEN
call fail('HOSPITAL CODE INVALID');
END IF;
But i get
: ERROR : --> #1064 - You have an error in your SQL syntax; check the manual that correspo开发者_开发知识库nds to your MySQL server version for the right syntax to use near 'REGEX '^[0-9]+$' THEN call fail('HOSPITAL CODE INVALID'); END IF' at line 5
NOT_REGEXP function - see the docs http://dev.mysql.com/doc/refman/5.1/en/regexp.html
IF colname NOT_REGEXP '^[0-9]+$' THEN
IF NOT column_name REGEXP '^[0-9]+$' THEN
Just change the regular expression
IF NEW.HospitalID REGEX '^[^0-9]+$' THEN
call fail('HOSPITAL CODE INVALID');
END IF;
Explaination
- The first caret character is for the start of the HospitalID.
- the square bracket [ is for the start of the character class
- The second caret character is the nagation of all charecter except zero to 9
- the end square bracket is for the end of character class
- plus sign character is for that the character class characters must be one or more
- the dollar character is for the end of the HospitalID variable.
So in short this regular expression checks the HospitalID variable and if it found that the HospitalID variable had other than numeric characters it call fail function.
精彩评论