create or replace procedure proc_test ( table_name in varchar2, --表名 field1 in varchar2, --字段名 datatype1 in varchar2, --字段类型 field2 in varchar2, --字段名 datatype2 in varchar2 --字段类型 ) as str_sql varchar2(500); begin str_sql:=’create table ’||table_name||’(’||field1||’ ’||datatype1||’,’||field2||’ ’||datatype2||’)’; execute immediate str_sql; --动态执行DDL语句 exception when others then null; end ; |
SQL> execute proc_test(’dinya_test’,’id’,’number(8) not null’,’name’,’varchar2(100)’); PL/SQL procedure successfully completed SQL> desc dinya_test; Name Type Nullable Default Comments ---- ------------- -------- ------- -------- ID NUMBER(8) NAME VARCHAR2(100) Y SQL> |
create or replace procedure proc_insert ( id in number, --输入序号 name in varchar2 --输入姓名 ) as str_sql varchar2(500); begin str_sql:=’insert into dinya_test values(:1,:2)’; execute immediate str_sql using id,name; --动态执行插入操作 exception when others then null; end ; |
SQL> execute proc_insert(1,’dinya’); PL/SQL procedure successfully completed SQL> select * from dinya_test; ID NAME 1 dinya |
declare p_id number:=1; v_count number; begin v_string:=’select count(*) from table_name a where a.id=:id’; execute immediate v_string into v_count using p_id; end ; |
create or replace procedure proc_dbms_sql ( table_name in varchar2, --表名 field_name1 in varchar2, --字段名 datatype1 in varchar2, --字段类型 field_name2 in varchar2, --字段名 datatype2 in varchar2 --字段类型 )as v_cursor number; --定义光标 v_string varchar2(200); --定义字符串变量 v_row number; --行数 begin v_cursor:=dbms_sql.open_cursor; --为处理打开光标 v_string:=’create table ’||table_name||’(’||field_name1||’ ’||datatype1||’,’||field_name2||’ ’||datatype2||’)’; dbms_sql.parse(v_cursor,v_string,dbms_sql.native); --分析语句 v_row:=dbms_sql.execute(v_cursor); --执行语句 dbms_sql.close_cursor(v_cursor); --关闭光标 exception when others then dbms_sql.close_cursor(v_cursor); --关闭光标 raise; end; |
SQL> execute proc_dbms_sql(’dinya_test2’,’id’,’number(8) not null’,’name’,’varchar2(100)’); PL/SQL procedure successfully completed SQL> desc dinya_test2; Name Type Nullable Default Comments ---- ------------- -------- ------- -------- ID NUMBER(8) NAME VARCHAR2(100) Y SQL> |
SQL> select * from dinya_test2; ID NAME 1 Oracle 2 CSDN 3 ERP SQL> |
create or replace procedure proc_dbms_sql_update ( id number, name varchar2 )as v_cursor number; --定义光标 v_string varchar2(200); --字符串变量 v_row number; --行数 begin v_cursor:=dbms_sql.open_cursor; --为处理打开光标 v_string:=’update dinya_test2 a set a.name=:p_name where a.id=:p_id’; dbms_sql.parse(v_cursor,v_string,dbms_sql.native); --分析语句 dbms_sql.bind_variable(v_cursor,’:p_name’,name); --绑定变量 dbms_sql.bind_variable(v_cursor,’:p_id’,id); --绑定变量 v_row:=dbms_sql.execute(v_cursor); --执行动态SQL dbms_sql.close_cursor(v_cursor); --关闭光标 exception when others then dbms_sql.close_cursor(v_cursor); --关闭光标 raise; end; |
SQL> execute proc_dbms_sql_update(2,’csdn_dinya’); PL/SQL procedure successfully completed SQL> select * from dinya_test2; ID NAME 1 Oracle 2 csdn_dinya 3 ERP SQL> |