关于动态SQL


http://tom7758.itpub.net/post/6024/49678

目前在ORACLE开发过程中,我所用到的动态SQL的一点心得。 我把它分为FORM级、TABLE级和pl/sql级。
1》FORM级 方法一:
FORMS_DDL:支持pl/sql和部分ddl 建表:Forms_DDL('create table temp(n NUMBER)'); 删表:Forms_DDL('drop table temp'); 删除记录:Forms_DDL('delete from temp'); 执行PL/SQL:Forms_ddl('begin '||过程名||'; End;');

**注意判断是否执行成功,通过FORM_SUCCESS or FORM_FAILURE来判断。


2》table级别 方法一:dbms_sql. 建表,删表,更新记录等操作,基本类似,我举一个建表的例子:
Declare
cursor_name integer;
ret INTEGER;
begin
cursor_name:=dbms_sql.open_cursor;
DBMS_SQL.PARSE(cursor_name, 'create table test_2(name varchar2(8))', DBMS_SQL.native);
ret := DBMS_SQL.EXECUTE(cursor_name);
DBMS_SQL.CLOSE_CURSOR(cursor_name);
END; 查询数据:
Declare
cursor_name integer;
ret integer;
V_1 varchar2(10);
V_2 number;
begin
cursor_name:=dbms_sql.open_cursor;
DBMS_SQL.PARSE(cursor_name, 'select ''test'' ,783426 from dual', DBMS_SQL.native);
DBMS_SQL.DEFINE_COLUMN(cursor_name, 1, V_1,10);
DBMS_SQL.DEFINE_COLUMN(cursor_name, 2, v_2);
ret := DBMS_SQL.EXECUTE(cursor_name);
IF DBMS_SQL.FETCH_ROWS(cursor_name)>0 THEN
DBMS_SQL.COLUMN_VALUE(cursor_name, 1, v_1);
DBMS_SQL.COLUMN_VALUE(cursor_name, 2, v_2);
dbms_output.put_line('第一个值:'||v_1);
dbms_output.put_line('第二个值:'||to_char(v_2));
end if;
Dbms_sql.close_cursor(cursor_name);
end ;

***最简单的判断执行是否成功,利用trap exception.
方法二:execute immediate
8版以上数据库,相当好用的一个东东,我常用。 建表,删表类似:
declare
begin
EXECUTE IMMEDIATE 'drop table temp_1';
EXECUTE IMMEDIATE 'create table temp_1(name varchar2(8))';
end ; 增加数据
declare
v_1 varchar2(8);
v_2 varchar2(10);
str varchar2(50);
begin
v_1:='测试人员';
v_2:='北京';
str := 'INSERT INTO test (name ,address) VALUES (:1, :2)';
EXECUTE IMMEDIATE str USING v_1, v_2;
commit;
end;
查询数据:
declare
str varchar2(500);
c_1 varchar2(10);
r_1 test%rowtype;
begin
c_1:='测试人员';
str:='select * from test where name=:c WHERE ROWNUM=1';
execute immediate str into r_1 using c_1;
DBMS_OUTPUT.PUT_LINE(R_1.NAME||R_1.ADDRESS);
end ;


3》pl/sql级别 我仅仅用于查询。 例:
DECLARE
TYPE mycursor IS REF CURSOR;
cursor_1 mycursor;
r_1 test%ROWTYPE;
str VARCHAR2(100);
BEGIN
str := 'select * from test';
OPEN cursor_1 FOR str;
LOOP
FETCH cursor_1 INTO r_1;
EXIT WHEN emp_cv%NOTFOUND;
dbms_output.put_line(r_1.name);
END LOOP;
CLOSE cursor_1;
END;

你可能感兴趣的:(oracle,sql,C++,c,C#)