我想用check约束来限制身份征号只能是15或18位的数字,怎么搞?

解决方案 »

  1.   

    CREATE TABLE ta
    (
       id  smallint
          IDENTITY(1,1)
          PRIMARY KEY CLUSTERED,
       sfz varchar(18) NOT NULL
          CHECK (len(sfz) = 18 or len(sfz) = 15)
    )goinsert  ta(sfz) select 'adf'
    /*
    INSERT 语句与 COLUMN CHECK 约束 'CK__ta__sfz__7AA030EF' 冲突。该冲突发生于数据库 'CSDN_TEST',表 'ta', column 'sfz'。
    语句已终止。
    */
    insert  ta(sfz) select '123456789012345678'
    select * from ta
    /*
    id     sfz                
    ------ ------------------ 
    2      123456789012345678(所影响的行数为 1 行)
    */insert  ta(sfz) select '123456789012345'
    select * from ta/*
    id     sfz                
    ------ ------------------ 
    2      123456789012345678
    3      123456789012345(所影响的行数为 2 行)
    */drop table ta
      

  2.   

    create  table a(code varchar(20) 
    check(len(code)=15 and isnumeric(code)=1 and isdate(substring(code,7,6))=1 and (right(code,1)='0' or right(code,1)='1')
    or 
    len(code)=18 and isnumeric(left(code,17))=1 and isdate(substring(code,7,8))=1))
      

  3.   

    CREATE TABLE ta
    (
       id  smallint
          IDENTITY(1,1)
          PRIMARY KEY CLUSTERED,
       sfz varchar(18) NOT NULL
          CHECK (isnumeric(sfz) = 1 and (len(sfz) = 18 or len(sfz) = 15))
    )goinsert  ta(sfz) select 'adf'
    /*
    INSERT 语句与 COLUMN CHECK 约束 'CK__ta__sfz__7AA030EF' 冲突。该冲突发生于数据库 'CSDN_TEST',表 'ta', column 'sfz'。
    语句已终止。
    */
    insert  ta(sfz) select 'adfghjkl1234567890'
    /*
    INSERT 语句与 COLUMN CHECK 约束 'CK__ta__sfz__7AA030EF' 冲突。该冲突发生于数据库 'CSDN_TEST',表 'ta', column 'sfz'。
    语句已终止。
    */
    insert  ta(sfz) select '123456789012345678'
    select * from ta
    /*
    id     sfz                
    ------ ------------------ 
    2      123456789012345678(所影响的行数为 1 行)
    */insert  ta(sfz) select '123456789012345'
    select * from ta/*
    id     sfz                
    ------ ------------------ 
    2      123456789012345678
    3      123456789012345(所影响的行数为 2 行)
    */drop table ta
      

  4.   

    18位的加上校验位:
    create  table a(code varchar(20) 
    check(isnumeric(code)=1 and len(code)=15 and isdate(substring(code,7,6))=1 and (right(code,1)='0' or right(code,1)='1')
    or len(code)=18 and isnumeric(left(code,17))=1 and isdate(substring(code,7,8))=1 and patindex('%[X0-9]%',right(code,1))>0))
      

  5.   

    ALTER TABLE 表名 
    ADD CONSTRAINT CK_STUAGE CHECK(len(列名) in (15 ,18)) 如果列的数据类型为Char,以上可以实现你的功能,如果不是Char,则用:ALTER TABLE 表名 
    ADD CONSTRAINT CK_STUAGE CHECK( 列名 in (15 ,18))