Limit SQL Server column to a list of possible values

前端 未结 3 1483
盖世英雄少女心
盖世英雄少女心 2021-02-05 00:52

How do I put a constraint on a column so that it can only contain the following values? What do you call this type of constraint?

Allowed values: \"yes\", \"no\"         


        
相关标签:
3条回答
  • 2021-02-05 01:28

    you can use a CHECK constraint

    ALTER TABLE <table>
    ADD CONSTRAINT chk_val CHECK (col in ('yes','no','maybe'))
    

    MSDN link

    0 讨论(0)
  • 2021-02-05 01:33

    Yes, check a constraint is it what you need. You can declare check constraint at the table declaration:

    CREATE TABLE test(
        _id BIGINT PRIMARY KEY NOT NULL,
        decision NVARCHAR(5),
        CHECK (decision in ('yes','no','maybe'))
    );
    
    0 讨论(0)
  • 2021-02-05 01:47

    Using enumeration table is a way to go.

    0 讨论(0)
提交回复
热议问题