Check constraint

  • Hello, I have this

    create table(

    a int,

    b int,

    c int )

    Only one column can have a value not null at same record,example if a=2 then b and c must be null; if b=3 then a and c must be null, so on, I want to use the check constraint but I don´t know how or maybe it doesnot, must i use another tool (trigger or sp )? thanks

  • You can use a check constraint for this...

    Hope that helps

    Billy

    /* -- cut here -- */

    begin tran

    set nocount on

    create table aaa(a int,b int,c int,constraint chk_aaa check((a is not null and b is null and c is null) or (a is null and b is not null and c is null) or (a is null and b is null and c is not null)));

    /* the following inserts will work */

    insert into aaa values(1,null,null)

    insert into aaa values(null,2,null)

    insert into aaa values(null,null,3)

    /* the following inserts will NOT work */

    insert into aaa values(null,null,null)

    insert into aaa values(1,2,null)

    insert into aaa values(null,2,3)

    insert into aaa values(1,null,3)

    insert into aaa values(1,2,3)

    select * from aaa

    set nocount off

    rollback;

    /* -- cut here -- */

  • Why not

    create table

    (

    type varchar(1),

    i int

    }

    where type = a,b,c.

    Cursors never.

    DTS - only when needed and never to control.


    Cursors never.
    DTS - only when needed and never to control.

  • Nigel is right - always.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply