search
HomeDatabaseMysql TutorialSQL Server 2008 查看与创建约束图文教程

本文章以图文的方式给大家详细介绍SQL Server 2008 查看与创建约束过程,有需要学习sql约束的朋友可参考本文章哦。


约束主要有一下几种:

NOT NULL : 用于控制字段的内容一定不能为空(NULL)。

UNIQUE : 控件字段内容不能重复,一个表允许有多个 Unique 约束。

PRIMARY KEY: 也是用于控件字段内容不能重复,但它在一个表只允许出现一个。

FOREIGN KEY: FOREIGN KEY 约束用于预防破坏表之间连接的动作,FOREIGN KEY 约束也能防止非法数据插入外键列,因为它必须是它指向的那个表中的值之一。

CHECK: 用于控制字段的值范围。

DEFAULT: 用于设置新记录的默认值。

 

1. PRIMARY KEY约束

在表中常有一列或多列的组合,其值能唯一标识表中的每一行。这样的一列或多列成为表的主键(Primary Key)。一个表只能有一个主键,而且主键约束中的列不能为空值。

查看PRIMARY KEY约束可以在object explorer中依次展开Databases –> 选择你要查看的(在我的例子中是testdatabase) –> Tables –> 你要查看的表(在我的例子中是company)-> Columns

image

如上图所示,Primary Key 有一把金色的小钥匙。companyid 即为company表的primary key。

 

创建PRIMARY KEY约束可以右键点击表,然后选择Design,打开表设计器

image

选中column,点击上面的金色小钥匙,来创建Primary Key。

image

也可以右键点击column,然后选择Set Primary Key。

image

 

 

2. FOREIGN KEY约束

外键(Foreign Key)是用于建立和加强两个表(主表与从表)的一列或多列数据之间的连接的。创建约束的顺序是先定义主表的主键,再对从表定义外键约束。

查看FOREIGN KEY约束,展开Columns,可以看到灰色的小钥匙为Foreign Key;展开Keys,可以看到Foreign Key约束的名字为FK_contact_company。

image

在表设计器中,也可以点击上面的Relationshi按钮,这样就可以查看到所有的Foreign Key约束

image

image

上面的例子可以看到contact 表的companyid为外键,company 表的companyid为主键。

 

下面来演示一下如何创建的该Foreign Key约束。

同样是点击完Relationships按钮之后,在弹出的对话框中选择Add

image

然后点击下面的红色圆圈内的按钮:

image

按下图中那样设置主表、主键和从表、外键

image

然后点击 OK,不要忘记保存你的设计。

image

 

 

3. UNIQUE约束

UNIQUE约束用于确保表中的两个数据行在非主键中没有相同的列值。与PRIMARY KEY约束类似,UNIQUE约束也强制唯一性,但UNIQUE约束用于非主键的一列或多列组合,且一个表可以定义多个UNIQUE约束,另外UNIQUE约束可以用于定义多列组合。

 

还以company table为例,假设我们要约束company name为唯一的,点击Manage Indexes and Keys

image

然后点击Add来添加Unique约束

image

选择column为companyname, Is Unique为Yes。

image

关闭并保存你的设计,这样一个Unique约束就创建好了。

 

 

4. DEFAULT约束

若在表中某列定义了DEFAULT约束,用户在插入新的数据行时,如果该列没有指定数据,那么系统将默认值赋给该列,当然该默认值也可以是空值(NULL)。

 

以contact表为例,在表设计器中,为性别(sex)列填写属性默认值 (‘M’)。

image

 

 

5. CHECK约束

CHECK约束用于限制输入一列或多列的值的范围,通过逻辑表达式来判断数据的有效性。一个列的输入内容必须满足CHECK约束的条件,否则数据无法正常输入。

 

还以contact表为例, 我们要限制sex列的值只能为 ´M´ 或者 ´F´。在表设计器中点击Manage Check Constraints

image

点击Add添加新的constraint

image

点击红圈内的按钮,填写表达式。我们例子中用的表达式是 SEX='M' OR SEX='F'

image

关闭并保存设计。向contact表中插入一行数据,如果sex列的值不为´M´ 或 ´F´, 插入就会报错


删除:

 代码如下 复制代码

在Sql Server、Oracle、MS 删除 Unique 约束语法:drop constraint UniqueName;
在My Sql 删除 Unique 约束语法:drop index UniqueName;

修改:

 代码如下 复制代码
ALTER TABLE EPlatform
ADD CONSTRAINT Unique_EPlatform
unique ([UserId],[Platform]);
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools