SQL 单列上的多重约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15446379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:18:15  来源:igfitidea点击:

Multiple constraints on single column

sqloracle10g

提问by Anu

Can we add multiple constraints on a single column?

我们可以在单个列上添加多个约束吗?

like-

喜欢-

create table x(x varchar2(20), y number(2) not null,
constraint fk_cons foreign key(x) references user_info(user_id),
constraint null_cons not null(x)
)

this query is returning error ora-00904: invalid identifier....

此查询返回错误 ora-00904: invalid identifier....

回答by Iswanto San

You have wrong syntax when create null_consconstraint:

创建null_cons约束时语法错误:

Use this (table level check constraint):

使用这个(表级检查约束):

CREATE TABLE x(
    x VARCHAR2(20), 
    y NUMBER(2) NOT NULL,
    CONSTRAINT fk_cons FOREIGN KEY(x) REFERENCES user_info(user_id),
    CONSTRAINT null_cons CHECK(x IS NOT NULL)
)

Or (use NOT NULLconstraint on column):

或者(NOT NULL对列使用约束):

CREATE TABLE x(
    x VARCHAR2(20) NOT NULL, 
    y NUMBER(2) NOT NULL,
    CONSTRAINT fk_cons FOREIGN KEY(x) REFERENCES user_info(user_id)
)

Or (Use column level check constraint):

或(使用列级检查约束):

CREATE TABLE x(
    x VARCHAR2(20) CHECK (X IS NOT NULL), 
    y NUMBER(2) NOT NULL,
   CONSTRAINT fk_cons FOREIGN KEY(x) REFERENCES user_info(user_id)
)

回答by ljh


    create table x(x varchar2(20), y number(2) not null,
    constraint fk_cons foreign key(x) references user_info(user_id),
    constraint null_cons check(x is not null)
    )

回答by Saurabh

create table x(x varchar2(20) not null, y number(2) not null,
    constraint fk_cons foreign key(x) references user_info(user_id)
)

回答by Allen Underwood

If the RDBMS is SQL Server, you can define multiple constraints at the column by doing this (I changed some of the column names to make the constraint naming strategy more obvious - naming is subjective):

如果 RDBMS 是 SQL Server,您可以通过这样做在列上定义多个约束(我更改了一些列名以使约束命名策略更明显 - 命名是主观的):

CREATE TABLE SomeTable(
    User_Id VARCHAR(20) CONSTRAINT FK_SomeTable_User_Id FOREIGN KEY REFERENCES dbo.User_Info(User_Id) CONSTRAINT UIX_NC_SomeTable_User_id  NONCLUSTERED NOT NULL, 
    SomeOtherColumn DECIMAL(2, 0) NOT NULL
)