2

我需要帮助。我在构建 PL/SQL 块时遇到问题。在游标中,我构造了一个查询,我想在游标上插入一个过滤器。下面是一个例子:

DECLARE 
code NUMBER;
parameters_amb myOthertable%ROWTYPE;

CURSOR test is SELECT id from mytable
 if parameters_amb.test2 is not null  then
    where mytable.name = 'NAMETABLE'
 else
    where mytable.name = 'NAMETABLE2';

任何人都可以帮助我进行这个建设吗?

4

4 回答 4

5

您可以使用参数化游标:

DECLARE 
code NUMBER;
parameters_amb myOthertable%ROWTYPE;
param mytable.name%TYPE;

CURSOR test (p_name VARCHAR2) is 
  SELECT id 
    FROM mytable
   WHERE mytable.name = p_name;
BEGIN
  if parameters_amb.test2 is not null  then
    param := 'NAMETABLE'
  else
    param := 'NAMETABLE2';
  end if;

  OPEN test(param);

  -- Add code to fetch and read from cursor
END;
于 2012-10-09T14:22:35.633 回答
0
DECLARE
 stmt varchar2(1000);
 code NUMBER;
 parameters_amb myOthertable%ROWTYPE;
BEGIN
 stmt := 'SELECT id from mytable';
 if parameters_amb.test2 is not null  
 then
    stmt := stmt||' where mytable.name = ''NAMETABLE''';
 else
    stmt := stmt||' where mytable.name = ''NAMETABLE2''';
 end if;

 OPEN test FOR stmt;
...
...
END;
于 2012-10-09T14:18:10.140 回答
0

你可以这样尝试:

DECLARE  
  code NUMBER; 
  parameters_amb myOthertable%ROWTYPE;  
  CURSOR test is SELECT id 
                 from mytable  
                 WHERE (parameters_amb.test2 is not null AND mytable.name = 'NAMETABLE' )
                   OR (parameters_amb.test2 is null AND mytable.name = 'NAMETABLE2' );

或者像这样:

DECLARE  
  code NUMBER; 
  parameters_amb myOthertable%ROWTYPE;  
  CURSOR test is SELECT id 
                 from mytable  
                 WHERE mytable.name = 
                       CASE WHEN parameters_amb.test2 is not null THEN 'NAMETABLE'
                            WHEN parameters_amb.test2 is null THEN 'NAMETABLE2' END
于 2012-10-09T14:26:42.657 回答
0

这是一个简单的解决方案:

声明代码号;参数_amb myOthertable%ROWTYPE;

CURSOR 测试是 SELECT id from mytable where mytable.name = NVL2(parameters_amb.test2, 'NAMETABLE', 'NAMETABLE2');

于 2014-09-09T22:12:42.617 回答