我们可以在单个列上添加多个约束吗?
像-
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)
)
此查询返回错误 ora-00904: invalid identifier....
创建null_cons
约束时语法错误:
使用这个(表级检查约束):
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)
)
或者(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)
)
或者(使用列级检查约束):
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)
)
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)
)
如果 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
)
create table x(x varchar2(20) not null, y number(2) not null,
constraint fk_cons foreign key(x) references user_info(user_id)
)