约æçç®çå°±æ¯ç¡®ä¿è¡¨ä¸çæ°æ®çå®æ´æ§ã
常ç¨ç约æç±»åå¦ä¸:
主é®çº¦æ:(Primary Key constraint) è¦æ±ä¸»é®åå¯ä¸ï¼å¹¶ä¸ä¸å
许为空
å¯ä¸çº¦æ:(Unique Constraint) è¦æ±è¯¥åå¯ä¸ï¼å
许为空ï¼ä½åªè½åºç°ä¸ä¸ªç©ºå¼
æ£æ¥çº¦æ:(Check Constraint) æååå¼èå´éå¶ãæ ¼å¼éå¶çãå¦æå
³å¹´é¾çéå¶
é»è®¤çº¦æ:(Default Constraint) æåçé»è®¤å¼ï¼å¦æ们çç·æ§å¦åæ¯è¾å¤ï¼æ§å«é»è®¤ä¸ºç·
å¤é®çº¦æ:(Foreign Key Constraint) ç¨äºå¨ä¸¤è¡¨ä¹é´å»ºç«å
³ç³»ï¼éè¦æå®å¼ç¨ä¸»è¡¨çåªä¸å
ä¸ãæ·»å 约æ
å¨å建表æ¶ï¼æ们å¯ä»¥å¨å段åæ·»å åç§çº¦æï¼ä½ä¸è¬ä¸è¿æ ·æ··ç¨ï¼æ¨èå°æ·»å 约æå建表çè¯å¥åå¼ç¼åã
æ·»å 约æçè¯æ³å¦ä¸:
Code:
Alter Table 表å
Add Constraint 约æå 约æç±»å å
·ä½ç约æç±»å
ä¸è¿°è¯æ³æ è¯ä¿®æ¹æ个表ï¼æ·»å æ个约æï¼å
¶ä¸çº¦æåçå½åè§åæ¨èéç¨"约æç±»å_约æå段"è¿æ ·çå½¢å¼ã
Code:
---æ·»å 主é®çº¦æ
Alter Table stuInfo
Add Constraint PK_stuNO primary Key(stuNo)
---æ·»å å¯ä¸çº¦æ
Alter Table stuInfo
Add Constraint UQ_stuID unique(stuID)
---æ·»å é»è®¤çº¦æ
Alter Table stuInfo
Add Constraint DF_stuAddress default('å°åä¸è¯¦') for stuAddress
---æ·»å æ£æ¥çº¦æ
Alter Table stuInfo
Add Constraint CK_stuAge check(stuAge between 15 and 40)
---æ·»å å¤é®çº¦æ
Alter Table stuMarks
Add Constraint FK_stuNo foreign key(stuNo) references stuInfo(stuNo)
äºãå é¤çº¦æ
å¦æé误çæ·»å äºçº¦æï¼åå¯ä»¥å é¤çº¦æ
å é¤çº¦æçè¯æ³å¦ä¸:
Code:
Alter Table 表å
Drop Constraint 约æå
éå ï¼å¨å建表çæ¶ååæ¶æ·»å 约æçåæ³:
Code:
use stuDB
go
if exists(select * from Sysobjects where name = 'stuInfo')
drop table stuInfo
go
create table stuInfo
(
stuName varchar(20) not null primary key(stuName)
ï¼stuID int not null unique(stuID)
ï¼stuAddress varchar(20) not null default('å°åä¸è¯¦')
ï¼stuAge int not null check(stuAge between 15 and 40)
)
温馨提示:答案为网友推荐,仅供参考