sql中UNIQUE有用法?最好能举个例子!谢谢!!

sql中UNIQUE有用法?最好能举个例子!谢谢!!,第1张

UNIQUE 约束强制实施列集中值的唯一性。

根据 UNIQUE 约束,表中的任何两行都不能有相同的列值。另外,主键也强制实施唯一性,但主键不允许 NULL 作为一个唯一值。

以下示例强制的限制是,Product 表的 Name 列必须唯一。

Name nvarchar(100) NOT NULL

UNIQUE NONCLUSTERED

use SM

go

1.

//创建SC表

if exists(select * from sysobjects where name='sc') //判断数据中是否有该表,若有先删除再重建

drop table sc

create table sc

(

StudentNo varchar(20) not null,

CourseNo varchar(20) not null,

StudentResult int not null

)

go

//添加约束

2.

alter table Student add constraint PK_stuno primary key(StudentNo)

3.

alter table Student add constraint CK_sex check (sex='男' or sex='女')

4.

alter table Course add constraint PK_courseno primary key(CourseNo)

5.

alter table Course add constraint UQ_coursename unique (CourseName)

6.

alter table sc add constraint FK_studentno foreign key(StudentNo) references Student(StudentNo)

7.

alter table sc add constraint FK_courseno foreign key(CourseNo) references Course(CourseNo)

8.

alter table sc add constraint PK_stu primary key(StudentNo,CourseNo)

create table tableName(userid int not null primary key, userName nvarchar(50) not null)

alter table tableName Add Constraint user_name_uq Unique (userName)

你在企业管理业里生成表脚本对比一下,一定有不一样的


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11302955.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-15
下一篇 2023-05-15

发表评论

登录后才能评论

评论列表(0条)

保存