用于检查两个大写字母后跟数值的sql约束

时间:2010-07-16 17:41:39

标签: sql database sql-server-2008 case-sensitive

我有以下sql检查,它接受应该是两个大写字母后跟3个数字值的值。


CREATE TABLE Project(
projectID       NCHAR(5)         NOT NULL       PRIMARY KEY,
                                       CHECK(projectID LIKE '[A-Z][A-Z][0-9][0-9][0-9]'),
projectName   NVARCHAR(20)  NOT NULL        UNIQUE,
budget      MONEY           NOT NULL)

如何制作它以便它只接受大写字母后跟3个数字作为projectID? ex。 它应该拒绝像'au123'这样的值并接受像'AU123'这样的值。

2 个答案:

答案 0 :(得分:3)

您需要在CHECK约束中声明区分大小写的排序规则:

Create Table Project    
    (
    ProjectId nchar(5) not null Primary Key
    , ProjectName nvarchar(20) not null Unique
    , Budget money not null
    , Constraint CK_Project 
         Check ( ProjectId Like '[A-Z][A-Z][0-9][0-9][0-9]' Collate Latin1_General_CS_AS )
    )

答案 1 :(得分:1)

Oracle 10g:

SQL> CREATE TABLE CHECK_CHECK (PROJECT_ID NCHAR(5) NOT NULL);

Table created.

SQL> ALTER TABLE CHECK_CHECK ADD CONSTRAINT CHECK_CHECK_CK01
  2   CHECK (REGEXP_LIKE(PROJECT_ID, '[A-Z][A-Z][0-9][0-9][0-9]', 'c'));

Table altered.

SQL> insert into check_check values ('au123');
insert into check_check values ('au123')
*
ERROR at line 1:
ORA-02290: check constraint (MED_AUDIT.CHECK_CHECK_CK01) violated

SQL> insert into check_check values ('AU123');

1 row created.