Oracle資料庫中動態執行SQL

2022-03-24 10:03:46 字數 1711 閱讀 5081

在oracle資料庫開發pl/sql塊中我們使用的sql

靜態sql: 在pl/sql塊中使用的sql語句在編譯時是明確的,執行的是確定物件。

動態sql: 在pl/sql塊編譯時sql語句是不確定的,如根據使用者輸入的引數的不同而執行不同的操作。

1、跟據動態條件獲得資料集

/*定義游標

*//*

定義儲存過程

*//*

實現儲存過程 查詢表 返回游標

*/32767

);condition varchar2(

32767

);begin

--動態條件

if p_where1  is not null then

condition :

=condition ||'

and t.where1 = 

'''||

p_where1 

||''''

;end if;

if p_where2  is not null then

condition :

=condition ||'

and t.where2 = 

'''||

p_where2 

||''''

;end if;

if p_where3  is not null then

condition :

=condition ||'

and t.where3 = 

'''||

p_where3 

||''''

;end if;

--動態語句

mainsql :='

select t.field1, t.field2, t.field3, t.field4  from table1 t '||

condition ||'

order by  t.fieldname desc';

--執行語名並返回游標

open p_outcursor for mainsql;

exception 

when others then 

null

;end;

注:定義部分應置於包頭,實現部分應置於包體

2、動態操作表資料

/*定義儲存過程

*//*

實現儲存過程 新增加資料 返回編碼

*/32767

);begin

select sequencename.nextval into i_id from dual;

p_field3 :

=i_id;

mainsql ='

insert into tablename values('||

i_id ||'

,:1,:2)';

--動態執行插入操作

execute immediate str_sql 

using

field1,field2; 

exception 

when others then 

null

;end;

注:定義部分應置於包頭,實現部分應置於包體

3、執行儲存過程

declare v_msg varchar2(20

);begin

dbms_output.put_line(v_msg);

end;

python中MySQL資料庫連線 執行sql語句

python 3.x版本中連線mysql資料庫使用第三方庫pymysql python 2.x版本中連線mysql資料庫使用第三方庫mysqldb 1 cmd命令下 com使用豆瓣映象源加快第三方庫的安裝速度。2 git命令下 git clone cd pymysql python3 setup.p...

python pycham,連線資料庫,執行sql

本地搭建的mysql的新建的表的資料如下 在pycham中連線mysql 執行sql 舉例編寫如下 import pymysqlif name main connect pymysql.connect host localhost port 3307,user root password 11111...

檢視Oracle資料庫中的執行計畫

1 set autotrace traceonly命令 2 explain plan for命令 1 explain plan for select from dual 2 select from table dbms xplan.display 3 10046檢視oracle資料庫中的執行計畫 能...