sql server新增 修改字段語句(整理)

2021-08-19 23:07:34 字數 2124 閱讀 5439

jcx5083761的專欄

:新增欄位的sql語句的寫法:

通用式: alter table [表名] add [欄位名] 字段屬性 default 預設值 default 是可選引數

增加字段: alter table [表名] add 欄位名 smallint default 0 增加數字字段,整型,預設值為0

alter table [表名] add 欄位名 int default 0 增加數字字段,長整型,預設值為0

alter table [表名] add 欄位名 single default 0 增加數字字段,單精度型,預設值為0

alter table [表名] add 欄位名 double default 0 增加數字字段,雙精度型,預設值為0

alter table [表名] add 欄位名 tinyint default 0 增加數字字段,位元組型,預設值為0

alter table [表名] add 欄位名 text [null] 增加備註型字段,[null]可選引數

alter table [表名] add 欄位名 memo [null] 增加備註型字段,[null]可選引數

alter table [表名] add 欄位名 varchar(n) [null] 增加變長文字型字段大小為n(1~255)

alter table [表名] add 欄位名 char [null] 增加定長文字型字段大小固定為255

alter table [表名] add 欄位名 datetime default 函式增加日期型字段,其中函式可以是 now(),date()等,表示預設值

(上面都是最常用的,還有其他的屬性,可以參考下面的資料型別描述)

刪除字段: alter table [表名] drop 欄位名

修改變長文字型字段的大小:alter table [表名] alter 欄位名 varchar(n)

刪除表: drop table [表名]

建立表:

sql="create table [表名] ([欄位1,並設定為主鍵] int identity

(1, 1) not null constraint primarykey primary key,"&

"[欄位2] varchar(50),"&

"[欄位3] single default 0,"&

"[欄位4] varchar(100) null,"&

"[欄位5] smallint default 0,"&

"[欄位6] int default 0,"&

"[欄位7] date default date(),"&

"[欄位8] int default 1)"

conn.execute sql

有null 的表示字段允許零長

2. 修改表:

a. 重新命名表:

exec sp_rename 'oldname','newname'

b. 修改列屬性:

alter table 學生資訊

alter column 姓名 varchar(20) not null

c. 新增列:

alter table 學生資訊

add 家庭住址 nvarchar(20) null

d. 刪除列:

alter table 學生資訊

drop column 家庭住址

d. 修改列名:

exec sp_rename '表名.[字段原名]','欄位新名','column'

3. 複製表:

a. 複製整張表:

select * into new_table from old_table

b. 複製表結構:

select * into new_table from old_table where 1=2

b. 複製表內容:

insert into new_tab select * from old_table

4. 修改identity列

自增列不能直接修改,必須將原有id列刪除,然後重新新增一列具有identity屬性的id欄位。比如你要修改的欄位名為id:

alter table 表名 drop column id

alter table 表名 add id int identity(1,1)

轉sql server新增 修改字段語句(整理)

新增欄位的sql語句的寫法 通用式 alter table 表名 add 欄位名 字段屬性 default 預設值 default 是可選引數 增加字段 alter table 表名 add 欄位名 smallint default 0 增加數字字段,整型,預設值為0 alter table 表名 ...

SQL server 新增字段問題

有些時候我們需要刪除或增加資料庫中有資料中表的列。總結一下列的刪除和增加。當表中存在資料時,刪除列後,資料也會被刪除。sql語句 alter table 表名 drop column 列名如果列存在約束,不能直接刪除列。此時需要先刪除約束 sql語句 alter table 表名 drop cons...

SQL server 新增字段問題

有些時候我們需要刪除或增加資料庫中有資料中表的列。總結一下列的刪除和增加。當表中存在資料時,刪除列後,資料也會被刪除。sql語句 alter table 表名 drop column 列名如果列存在約束,不能直接刪除列。此時需要先刪除約束 sql語句 alter table 表名 drop cons...