动态选择查询

时间:2015-11-19 05:16:42

标签: oracle plsql oracle10g

我想在oracle中运行动态 SELECT sql。

在Sql server中它很简单

  declare @a int,@b int,@c int;

   set @a=1;
   set @b=2;
   set @c=3;

   drop table empl
   create table empl (id int,name nvarchar(100))
   insert into empl values (1,'name1'),(2,'name2'),(3,'name3'),(4,'name4'),(5,'name4')

  select * from empl
  where id=@a or id= @b or id=@c

结果:

1   name1
2   name2
3   name3

但是当我尝试使用EXECUTE IMMEDIATE在oracle中执行此操作时,我遇到的问题是它不支持select语句而不支持。

如何在Oracle中实现此声明?

1 个答案:

答案 0 :(得分:1)

在使用SQL Server语法的示例中,您所做的只是投影三个值,102030。我在那里看不到任何动态

SQL> SELECT 10 a, 20 b, 30 c FROM dual;

         A          B          C
---------- ---------- ----------
        10         20         30

PL / SQL 中,您只需声明变量指定值

SQL> set serveroutput on
SQL> DECLARE
  2    a     NUMBER;
  3    b     NUMBER;
  4    c     NUMBER;
  5    var_a NUMBER;
  6    var_b NUMBER;
  7    var_c NUMBER;
  8  BEGIN
  9    a :=10;
 10    b := 20;
 11    c := 30;
 12    SELECT A,b,c INTO var_a, var_b, var_c FROM DUAL;
 13    DBMS_OUTPUT.PUT_LINE('Values are '||var_a||' '||var_b||' '||var_c);
 14  END;
 15  /
Values are 10 20 30

PL/SQL procedure successfully completed.

更新根据OP的更新问题:

您不需要显式游标,只需使用游标进行循环

例如,使用SCOTT模式中的标准EMP表:

SQL> set serveroutput on
SQL> DECLARE
  2    a     NUMBER;
  3    b     NUMBER;
  4    c     NUMBER;
  5  BEGIN
  6    a := 10;
  7    b := 20;
  8    c := 30;
  9    FOR i IN (SELECT empno FROM emp WHERE deptno IN (a, b, c))
 10    LOOP
 11    DBMS_OUTPUT.PUT_LINE('Employee number is '||i.empno);
 12    END LOOP;
 13  END;
 14  /
Employee number is 7369
Employee number is 7499
Employee number is 7521
Employee number is 7566
Employee number is 7654
Employee number is 7698
Employee number is 7782
Employee number is 7788
Employee number is 7839
Employee number is 7844
Employee number is 7876
Employee number is 7900
Employee number is 7902
Employee number is 7934

PL/SQL procedure successfully completed.