sql語言類別
數據定義語言(DDL Data Definition):create創建、alter更改、truncate截斷、drop刪除
數據操縱語言(DML Data Manipulation Language):insert插入、select選擇、delete刪除、update更新
事務控制語言(TCL Transaction Control Language):commit提交、savepoint保存點、rollback回滾
數據控制語言(DCL Data Control Language):grant授予、revoke回收
數據定義語言DDL:
1.create table命令:
create table [schema.]table_name
(
column_name datatype,
column_name datetype,
....
)
schema表示對象的所有者,即模式的名稱。如果用戶在自己的模式中創建表,則可以不指定所有者名稱。
table表示表的名稱。
column表示列的名稱。
datatype表示該列的數據類型及其寬度。
表名命名規則:
1)表名首字符應該為字母。
2)不能使用Oracle保留字來為表命名。
3)表各的最大長度為30個字符。
4)同一用戶模式下的不同表不能具有相同的名稱。
5)可以使用下劃線、數字、字母,但不能使用空格和單引號。
Oracel和SQL Server數據庫對象表之間的差異:
列數:Oracle,254; SQL Server,1024
行大小:Oracle沒有限制;SQL Server,8060字節,加16字節指向每個text或image列。
最大行數:Oracle沒有限制;SQL Server沒有限制
表命名規則:Oracle,[schema.]table_name; SQL Server,[[[server.]database.]owner.]table_name
2.truncate table命令:
可以只刪除表中的記錄而不刪除表結構,刪除表中的所有行而不記錄日誌。
truncate table <table_name>;
數據操縱語言DML:(insert,select,update,delete)
1.選擇無重復的行,在select命令中包含distinct子句。
select distinct stuName,stuAge from stuInfo;
2.使用列別名,列別名不會影響列的實際名稱。列別名位於列表達式後面。
select stuName as “姓 名”,stuAge as 年齡,stuNo 編號 from stuInfo;
如果列別名中指定有特殊字符(如空格)的列標題使用雙引號括起來。
3.利用現有表創建新表。
語法: create table <newTable_name>
as
select {* | column(s)} from <oldTable_name> [where <condition>];
復制表結構和記錄:
create table newStuInfo
as
select * from stuInfo;
復制表指定列和記錄:
create table newStuInfo
as
select stuName,stuAge,stuNo from stuInfo;
只復制表結構:
create table newStuInfo
as
select * from stuInfo where 1=2;
4.查看表中行數:
select count(1) from stuInfo; --1比*號效率較高
5.取出stuName,stuAge列不存在重復的數據記錄:
select stuName,stuAge from stuInfo
group by stuName,stuAge
having(count(stuName||stuAge));//“||”在這裏是連接操作符,類似於“+”,意思為將兩部分內容連接在
一起,因為count()裏面只能有一個列,所以連接起來。
6.刪除stuName、stuAge列重復的行(相同數據只保留一行)
delete from stuInfo where rowid not in(
select max(rowid) from stuInfo group by stuName,stuAge
having (count(stuName||stuAGe)>1)
union
select max(rowid) from stuInfo group by stuName,stuAge
having (count(stuName||stuAge)=1)
);
7.根據當前用戶所有數據量>100萬的表的信息
select tabke_name from user_all_tables a where a.num_rows>1000000;
--user_all_tables為系統提供的數據視圖,使用者可以通過查詢該視圖獲得當前用戶表中描述。
事務控制語言TCL:
1)commit:提交事務,提事務中對數據庫的修改進行永久保存。
2)rollback:回滾事務,即取消對數據庫所做的作何修改。
3)savepoint <savepoint_name>:在事務中創建存儲點。
4)rollback to savepoint <savepoint_name>:將事務回滾到存儲點。即savepoint 創建的存儲點
開啟事務:在Oracle中,上一次事務結束以後,數據第一次被修改時自動開啟。
結束事務: ①數據被提交:發出commit命令;執行DDL或DCL語句後,當前事務自動commit;與Oracle分離。
②數據被撤銷:發出rollback命令;服務器進程異常結束;DBA停止會話。
例: insert into dept values (10,’ACCOUNTING’,’NEW YORK’);
commit;
savepoint a;//a只是一個名稱
insert into dept values (20,’SALES’,’NEW YORK’);
rollback to savepoint a;
rollback;--結果只有第一條記錄插入成功
數據控制語言DCL:
數據控制語言為用戶提供權限控制命令。數據庫對象(如表)的所有者對這些對象擁有控制權限。所有者可以根據自己
的意願決定其他用戶如何訪問對象,授予其他用戶權限(insert,select,update,delete,....)
sql語言類別