0

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?

Colin 't Hart
  • 7,372
  • 3
  • 28
  • 51
bicycle
  • 8,315
  • 9
  • 52
  • 72
  • Can you give us at least one example? (I'm not quite sure what you mean!) – Colin 't Hart Oct 26 '12 at 15:27
  • 2
    What defines a word? Can you simply look for the number of space characters? Do you need to use other delimiters? If so, what delimits a word? – Justin Cave Oct 26 '12 at 15:27
  • @Colin 't Hart Sorry about that, I know what you mean. I basically want a maximum number of 99 white spaces " " – bicycle Oct 26 '12 at 15:37
  • @Justin Cave Sorry about that, I know what you mean. I basically want a maximum number of 99 white spaces " " – bicycle Oct 26 '12 at 15:38
  • Do you mean total white space in the field or just leading/trailing? giving an example of what you are putting into the field will help people answer your question. – Joe W Oct 26 '12 at 15:44
  • @Joe W I basically want that one field to have a maximum number of 100 words. Since text strings don't start and end with a white space " ", 99 white spaces should therefore be all right – bicycle Oct 26 '12 at 15:48

2 Answers2

5

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)
Xophmeister
  • 8,884
  • 4
  • 44
  • 87
2

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.

Colin 't Hart
  • 7,372
  • 3
  • 28
  • 51