tags:

views:

36

answers:

3

... for strings, it's easy... LENGTH(attribute), but for ints, LENGTH always returns "4" for ints, "8" for bigints, etc etc.

So given a statement like this:

create table EMPLOYEE (employeeno bigint NOT NULL PRIMARY KEY);

How could I add a CHECK clause that'll check to see whether an inserted employeeno is exactly 6 digits?

+1  A: 

Convert it or Cast it as varchar first then use length.

Eric
"A value with data type "SYSIBM.INTEGER" cannot be CAST to type "SYSIBM.VARCHAR"", quoth DB2...
Julian H. Lam
+1  A: 

Use a check constraint to check for val >= 100000 and val <= 999999.

If you need to, you can change this to val >= 0 and val <= 999999. Note that int types do not contain any information about leading zeroes, so that information is already lost by the time it hits the database.

recursive
Would work, yes - but not if 000000 is a legitimate six-digit entry :)
Julian H. Lam
Julian you couldn't catch that anyway - at least not in a trigger or a check constraint - not with the current table definition. By the time you get to test the value it is already an int, and you can't figure out anyway whether the user entered 0, 00, 000, etc.
Roland Bouman
@Julian: In the int type, the value 000000 is just 0. No leading zeroes. I've updated my answer with this information.
recursive
Thanks Roland - I guess I just needed someone to tell me it wasn't possible :)
Julian H. Lam
recursive: that's quite true, thanks for the update - problem solved.
Julian H. Lam
+1  A: 

Personally, I would prefer to check integers using numeric constraints. So this begs the question, do you really want to look at the characlter length of the string representation of the integer? For example, should -100000 be allowed? I am assuming that is not the case, and suggest something like:

create table EMPLOYEE (
    employeeno integer
        CHECK (employeeno BETWEEN 1000000 AND 999999)
        NOT NULL PRIMARY KEY
);

Note I changed bigint to integer since the constraint necessarily prevents values from being added that are beyond the precision of an integer

Roland Bouman