SQL 的常用更改表約束

2021-07-13 17:18:19 字數 1530 閱讀 4645

sql 的常用更改表約束

一、修改字段預設值

alter table 表名 drop constraint 約束名字 ------說明:刪除表的字段的原有約束

alter table 表名 add constraint 約束名字 default 預設值 for 欄位名稱 -------說明:新增乙個表的字段的約束並指定預設值

alter table [aemployer] add transactiondate datetime default '1900-1-1' ----異動時間

------刪除約束------

use [dchrinf]

goalter table [dbo].[amenuswitch] drop constraint [fk__amenuswit__menun__3e082b48]

go二、修改欄位名:

alter table 表名 rename column a to b

三、修改字段型別:

alter table 表名 alter column unitprice decimal(18, 4) not null

三、修改增加字段:

alter table 表名 add 字段 型別 not null default 0

四. 主鍵

alter table 表名 add constraint pk_表名 primary key( autoid )

---兩個字段一起做為主鍵

alter table hremplyertime add constraint pk_gonghao_employdtim primary key(employdtim,gonghao);

五. 外來鍵

alter table aemployer add constraint fk_aemployer_dptid foreign key(dptid) references dbo.adepartinf( dptid)

六.唯一

將兩個字段合在一起約束成乙個唯一鍵

create unique index [索引名] on 軟體資訊表(s_sname,s_edition)

或alter table 軟體資訊表 add constraint s_sname_edition unique(s_sname,s_edition)

create unique index [workdate_gonghaounique] on aexcrptofday1(workdate,gonghao)

t-sql 寫法

alter table hremplyerrest with nocheck add

constraint [uniqgonghaomonthid] unique nonclustered

( [gonghao] asc,

[monthid] asc

)七. 索引

create index inx_supno on asupport( supno );

更改具有Foreign key約束的表

1 foreign key 說明 foreign key 外來鍵 建立起了表與表之間的約束關係,讓表與表之間的資料更具有完整性和關聯性。設想,有兩張表a b,a表中儲存了許多電腦製造商的資訊,比如聯想 戴爾 惠普和華碩,b表中儲存了許多多型號的電腦,比如lenovo1,lenovo2,hp1,hp2...

SQL表的約束

create table students s char 8 not null unique,sname char 10 s char 2 constraint cts check s 男 or s 女 sage integer check sage 1 and sage 150 d char 2 ...

SQL實現新增表,表名更改,列名更改,約束更改等

新建表 create table tablename id int identity 1,1 primary key name varchar 50 default hello null job ntext null creationdt datetime,column4 money null co...