--------------------------------创建表结构时创建约束--------------------------------
主键约束:
Id int identity(1,1) primary key not null
外键约束:
TypeId int not null foreign key references 主表(主键列)
Unique唯一约束:
DeviceNo varchar(50) unique not null
Default默认约束:
DeviceName varchar(100) default 'CT'
Check约束:
Price decimal(18,2) check(0<Price<10000) default(0) not null
--------------------------------创建表结构之后创建约束--------------------------------
主键:alter table 表名 add constraint pk_constraintname primary key(主键列)
外键:alter table 表名 add constraint fk_constraintname foreign key(从表列) references 主表(主表列)
Unique:alter table 表名 add constraint uk_constraintname unique(列名,列名)——可单例或多列
Check:alter table 表名 add constraint ck_constraintname check(0<Price<10000) ——check(逻辑表达式)
Default:alter table 表名 add constraint df_constraintname default(0) for Price
ALTER TABLE UserRIQC ALTER COLUMN id nvarchar(50) NOT NULL; if object_id(N'pk_id','PK') is null ALTER TABLE TableMutualRecognition ADD CONSTRAINT pk_id PRIMARY KEY (id); if object_id(N'pk_reportid','PK') is null ALTER TABLE TableMutualRecognitionReport ADD CONSTRAINT pk_reportid PRIMARY KEY (id); if object_id(N'pk_userid','PK') is null ALTER TABLE UserRIQC ADD CONSTRAINT pk_userid PRIMARY KEY (id); if object_id(N'pk_logid','PK') is null ALTER TABLE AuditLog ADD CONSTRAINT pk_logid PRIMARY KEY (id); if object_id(N'pk_expertgroupid','PK') is null ALTER TABLE DictExpertGroup ADD CONSTRAINT pk_expertgroupid PRIMARY KEY (id); if object_id(N'pk_qualityitemsid','PK') is null ALTER TABLE DictQualityItems ADD CONSTRAINT pk_qualityitemsid PRIMARY KEY (QualityItemsNo); if object_id(N'pk_reviewitemsid','PK') is null ALTER TABLE DictReviewItems ADD CONSTRAINT pk_reviewitemsid PRIMARY KEY (ReviewItemsNo); if object_id(N'pk_tbimgqaitemsid','PK') is null ALTER TABLE TableImageQualityItems ADD CONSTRAINT pk_tbimgqaitemsid PRIMARY KEY (QualityDescriptionNo); if object_id(N'pk_loginlogid','PK') is null ALTER TABLE LoginLog ADD CONSTRAINT pk_loginlogid PRIMARY KEY (id);