站点图标 IDC铺

关于讲解Oracle动态SQL

declare
  mysql varchar2(200);  -- 保存SQL语句(所谓的动态SQL,就是一个可变的变量)
begin
  mysql := \'select 1+1 from dual\';
  dbms_output.put_line(mysql);
end;
-----------
declare
  mysql varchar2(200);  -- 保存SQL语句(所谓的动态SQL,就是一个可变的变量)
begin
  mysql := \'create table aa(a1 varchar2(100))\';
  execute immediate mysql;
end;

drop table aa;
create table aa(a1 varchar2(100))
select * from aa
--------------------

begin
  create table aa_20180402(a1 varchar2(100));
end;
-------------------
declare
  mysql varchar2(200);  -- 保存SQL语句(所谓的动态SQL,就是一个可变的变量)
  today varchar2(8);
begin
  select to_char(sysdate,\'yyyyMMdd\') into today from dual;
  mysql := \'create table aa_\'|| today ||\'(a1 varchar2(100))\';
  dbms_output.put_line(mysql);  
  execute immediate mysql;
end;


select to_char(sysdate,\'yyyyMMdd\') from dual

-- 二、立刻执行SQL语句,并赋值给某个变量
select * from t_user5
select * from t_user6

create view t_user6 as select * from t_user5
select upper(\'t_user6\') from dual
select OBJECT_TYPE from dba_objects where object_name=upper(\'t_user6\');
select OBJECT_TYPE from dba_objects where object_name=upper(\'t_user5\');
-------------------------------------
select * from tt3
-------------
create or replace procedure p_a1(obj_name in varchar2)
is
  my_str1 varchar2(100);
  xxx tt3%rowtype;
begin
  -- 拼凑1条可执行的动态SQL ,保存sql语句到my_str1 这个变量中
  my_str1 := \'select * from tt3 where user_name=\';
  my_str1 := my_str1 || \'\'\'\';
  my_str1 := my_str1 || obj_name;
  my_str1 := my_str1 || \'\'\'\';
  --dbms_output.put_line(my_str1);  --调试用
  execute immediate my_str1 into xxx;
  dbms_output.put_line(xxx.city); 
end;
------------------------------
-- 三、带参数的动态SQL(可以把结果存储到某个变量)

create or replace procedure p_a1(obj_name in varchar2)
is
  my_str1 varchar2(100);
  xxx tt3%rowtype;
begin
  -- 拼凑1条可执行的动态SQL ,保存sql语句到my_str1 这个变量中
  my_str1 := \'select * from tt3 where user_name=:1\';
  --dbms_output.put_line(my_str1);  --调试用
  execute immediate my_str1 into xxx using \'小明\';
  dbms_output.put_line(xxx.city); 
end;
退出移动版