Question

I want to add a check constraint that checks whether a field has a maximum number of X white spaces " ". I couldn't find anything about it on the oracle website. Anybody knows whether that's possible? Maybe through a PL/SQL function?

Was it helpful?

Solution

If you're defining a word by counting the number of spaces, then you could probably do something like this:

constraint check_ws_count check (length(regexp_replace(field,'[^ ]','')) <= 99)

However, this doesn't take into account double spacing, etc. Maybe you can tweak it to be more robust, but it doesn't seem like a good idea!


EDIT Using regexp_count and taking multiple spacing into account:

constraint check_ws_count check (regexp_count(field, '\s+') <= 99)

OTHER TIPS

Probably something like this should do the trick:

check (length(field) - length(replace(field, ' ', '')) <= 99)

This approach will also work for those stuck on Oracle 9i or older databases without the regexp_ family of functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top