sql 表結構操作

2021-06-04 17:01:37 字數 2801 閱讀 7218

新建表:

create table [表名]

([自動編號字段] int identity (1,1) primary key ,

[欄位1] nvarchar(50) default '預設值' null ,

[欄位2] ntext null ,

[欄位3] datetime,

[欄位4] money null ,

[欄位5] int default 0,

[欄位6] decimal (12,4) default 0,

[欄位7] image null ,

)刪除表:

drop table [表名]

批量刪除表

declare

@sql

varchar

(max)

select

@sql='

drop table

'select

@sql

=@sql+'

['+name+'

]'+'

,'from

sys.tables

where

create_date

<

'2012-1-1

'print

(@sql)

exec

(@sql

)

插入資料:

insert into [表名] (欄位1,欄位2) values (100,'51windows.net')

insert into [表名] (欄位1,欄位2)  select 100,'51windows.net'

刪除資料:

delete from [表名] where [欄位名]>100

使用truncate table 刪除表中的所有行(清空),而不記錄單個行刪除操作。

truncate table 在功能上與不帶 where 子句的 delete 語句相同:二者均刪除表中的全部行。但 truncate table 比 delete 速度快,且使用的系統和事務日誌資源少。

delete 語句每次刪除一行,並在事務日誌中為所刪除的每行記錄一項。truncate table 通過釋放儲存表資料所用的資料頁來刪除資料,並且只在事務日誌中記錄頁的釋放。

truncate table 刪除表中的所有行,但表結構及其列、約束、索引等保持不變。新行標識所用的計數值重置為該列的種子。如果想保留標識計數值,請改用 delete。如果要刪除表定義及其資料,請使用 drop table 語句。

對於由 foreign key 約束引用的表,不能使用 truncate table,而應使用不帶 where 子句的 delete 語句。由於 truncate table 不記錄在日誌中,所以它不能啟用觸發器。

truncate table 不能用於參與了索引檢視的表。

更新資料:

update [表名] set [欄位1] = 200,[欄位2] = '51windows.net' where [欄位三] = 'haiwa'

update的格式是

update t1 set t1.name=』liu』from t1inner join t2 on t1.id = t2.tid

delete 語句也是類似

delete from t1from t1inner join t2 on t1.id = t2.tid

新增字段:

alter table [表名] add [欄位名] nvarchar (50) null

刪除字段:

alter table [表名] drop column [欄位名]

修改字段:

alter table [表名] alter column [欄位名] nvarchar (50) null

重新命名表:(access 重新命名表,請參考文章:在access資料庫中重新命名表)

sp_rename '表名', '新錶名', 'object'

新建約束:

alter table [表名] add constraint 約束名 check ([約束字段] <= '2000-1-1')

刪除約束:

alter table [表名] drop constraint 約束名

新建預設值

alter table [表名] add constraint 預設值名 default '51windows.net' for [欄位名]

刪除預設值

alter table [表名] drop constraint 預設值名

另外以上的只是sql的語法在 access 下大部份也都是一樣的

項一項查閱,並經自己使用驗證,確認在access 資料庫中新增自動編號字段使用以下方法比較合適:

create table 資料表名稱 (id counter constraint primarykey primary key) 需要注意的地方是:第二個primary中間有空格,

另外,關鍵字不區分大小寫.

另外自己最近發現的一種方法是: sql="create table mytb (id autoincrement(25,1) primary key,age int)"

sql2="create table testtb (id autoincrement,age int,email char, primary key (id))"

其中在access中,autoincrement為自動編號型別字段,(25,1)分別為初始值及步長值,如果不寫的話,預設是1,1,primary key指定了主鍵,

以上示例,兩種指定方法都可以

SQL表結構操作語句

遷移資料,可以複製自動編號啦!set identity insert data on insert into data id,a1,a2 select id,username,email from olddata a.重新命名表 下例將表 customers 重新命名為 custs。exec sp ...

使用SQL語句操作表結構

刪除員工表 drop table db user 刪除角色表 drop table db role 清空 站 recycle bin purge recyclebin 建立角色資訊表 create table db role roleid varchar2 8 not null primary ke...

SQL資料庫的表結構操作

更改資料庫中物件屬性雖然很多時候是不必要的。假如在建立表時,表名,列名 字段資料型別拼寫錯誤。在插入資料操作時發現物件 資料型別不一致,要檢查插入資料與資料庫是否匹配,也可以更改表結構。只能更改當前資料庫中的物件名稱或資料型別名稱。大多數系統資料型別和系統物件的名稱都不能更改。要修改資料庫中指定的物...