简体   繁体   中英

How can I create a REGEXP constraint on a column?

I am trying to put a regexp constraint on a field "StaffAdress" such that it should only end with " street".

This is my attempt, but it still doesn't seem to be valid. I tried regexp '.*street$' and regexp 'street$' but both did not let me add "test street" in the table.

CREATE TABLE MsStaff (
   `StaffId` CHAR(4) PRIMARY KEY CHECK (`StaffId` regexp 'S[0-9][0-9][0-9]'),
    `StaffName` VARCHAR(100) NOT NULL,
    `StaffGender` VARCHAR(6) NOT NULL,
    `StaffAddress` VARCHAR(100) NOT NULL CHECK ('StaffAddress' regexp '.*street$')
)

I'm using 10.4.19-MariaDB

I think your problem is that you are comparing a literal string, not a column, to your regex.

...CHECK ('StaffAddress' regexp '.*street$')

should be (don't forget the space)

...CHECK (StaffAddress regexp '.* street$')

'StaffAddress' regexp '.*street$' will always return false. Column names have to be quoted in backticks, not in single quotes.

Correct would be:

`StaffAddress` VARCHAR(100) NOT NULL CHECK (`StaffAddress` regexp '\w*\ street$')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM