資料庫常用sql

2021-05-26 14:18:29 字數 2532 閱讀 1435

1.oracle.檢視儲存過程:

select *  from user_objects where object_type ='procedure';

2.oracle.檢視儲存過程源**:

select text from user_source where  name='cal_bjchmiddata';

3.oracle.分頁查詢:(rownum)

從資料庫表中第m條記錄開始檢索n條記錄

select * 

from (select rownum r,t1.* from 表名稱 t1 where rownum < m + n) t2

where t2.r >= m

對於rownum來說它是oracle系統順序分配為從查詢返回的行的編號,返回的第一行分配的是1,第二行是2,

依此類推,這個偽欄位可以用於限制查詢返回的總行數,而且rownum不能以任何表的名稱作為字首。

oralce是邊執行笛卡爾集運算,邊應用選擇條件,所以rownum>n(n>1=)永遠不成立

4.oracle,隨機查詢20條

select * from( select * from 表名 order by dbms_random.value)

where rownum <= 20;

5.刪除重覆記錄: (rowid)

select *  from test  t1 where  rowid <> (select  max(rowid) from test t2  where t1.col1=t2.col1 );

在oracle中,每一條記錄都有乙個rowid,rowid在整個資料庫中是唯一的,rowid確定了每條記錄是oracle中的哪乙個資料檔案、塊、行上。在重複的記錄中,

可能所有列的內容都相同,但rowid不會相同。

6.外連線

left outer join:左外關聯 , 條件用on //左表的所有記錄都顯示,而用(+)時恰好在顯示在右邊,要注意區分。

right outer join:右外關聯 條件用on  //右表的所有記錄都顯示,而用(+)時恰好在顯示在左邊,要注意區分。

full outer join:全外關聯 條件用on   //顯示左表對應右表的所有記錄

7.分組統計

select f.name ,

sum(case when f.type='0'  then  1  end )  as jztotal, 

sum(case when f.type='1'  then  1  end )  as kctotal, 

sum(case when f.type='2'  then  1  end )  as jwtotal,

count(f.type)  as total 

from r_test f  group by  f.name ;

8.查詢每個月的最大值

統計每個月***x最大的前三條記錄

select  id,yearmonth,***x

from (

select  r.id,r.yearmonth,r.csn  ,

row_number() over (partition by r.yearmonth order by r.csn  desc )   aaa  

from ***x  r 

)  ds

where ds.aaa <=3

9.oracle樹型結構查詢

樹型表結構:

節點id  上級id  節點名稱

公式: 

select 節點id,節點名稱,level

from 表

connect by prior 節點id=上級節點id

start with 上級節點id=節點值

10.decode函式

decode函式的作用:它可以將輸入數值與函式中的引數列表相比較,根據輸入值返回乙個對應值

語法如下:

decode(control_value,value1,result1[,value2,result2…][,default_result]);

select decode( x , 1 , 『x is 1 』, 2 , 『x is 2 』, 『others』) from dual

當x等於1時,則返回『x is 1』。

當x等於2時,則返回『x is 2』。

否則,返回others』。

11.複製表

只複製表結構的sql

create table b as select * from a where 1<>1 

即複製表結構又複製表中資料的sql

create table b as select * from a 

複製表的制定欄位的sql

create table b as select row_id,name,age from a where 1<>1 

insert into 會將查詢結果儲存到已經存在的表中

insert into t2(column1, column2, ....)

select column1, column2, .... from t1 

資料庫常用SQL

1 檢視鎖定對像 select a.owner 方案名,a.object name 表名,b.xidusn 回滾段號,b.xidslot 槽號,b.xidsqn 序列號,b.session id 鎖表session id,b.oracle username 鎖表使用者名稱,decode d.type...

ORACLE資料庫常用SQL

1.新增乙個表,通過另乙個表的結構和資料 create table product bak as select from product2.如果表存在 insert into product bak select from product 3.同乙個表中,將a欄位的指賦給b欄位 update pro...

Oracle資料庫常用SQL

oracle ora 00984 column not allowed here ora 00984錯誤 列在此處不允許 當資料以char的形式存在時,應加單引號,則插入資料庫就不會出現類似錯誤.oracle實現select的結果集隨機展示 select from tablename order b...