PL / SQL:在单个查询中选择多个变量

时间:2017-12-21 10:14:47

标签: oracle plsql

在oracle包的初始化部分,我尝试确定具有给定名称的某些对象的当前ID。 原因:该软件包用于多个数据库,这些对象的ID因名称不变而有所不同。

代码如下所示:

SELECT id INTO varCat FROM myTable WHERE Type = 'Object' AND Name = 'Cat';
SELECT id INTO varDog FROM myTable WHERE Type = 'Object' AND Name = 'Dog';
...
SELECT id INTO varMouse FROM myTable WHERE Type = 'Object' AND Name = 'Mouse';

有没有办法优化查询,也许在单个查询中执行?

4 个答案:

答案 0 :(得分:3)

您可以将它们与手动轴相结合:

select max(case when name = 'Cat' then id end),
  max(case when name = 'Dog' then id end),
  max(case when name = 'Mouse' then id end)
into varCat, varDog, varMouse
from mytable
where type = 'Object'
and name in ('Cat', 'Dog', 'Mouse');

快速演示:

create table mytable (id number, type varchar2(10), name varchar2(10));
insert into mytable (id, type, name) values (1, 'Object', 'Mouse');
insert into mytable (id, type, name) values (2, 'Object', 'Cat');
insert into mytable (id, type, name) values (3, 'Object', 'Dog');

set serveroutput on
declare
  varCat mytable.id%type;
  varDog mytable.id%type;
  varMouse mytable.id%type;
begin
  select max(case when name = 'Cat' then id end),
    max(case when name = 'Dog' then id end),
    max(case when name = 'Mouse' then id end)
  into varCat, varDog, varMouse
  from mytable
  where type = 'Object'
  and name in ('Cat', 'Dog', 'Mouse');

  dbms_output.put_line('varCat: ' || varCat);
  dbms_output.put_line('varDog: ' || varDog);
  dbms_output.put_line('varMouse: ' || varMouse);
end;
/

varCat: 2
varDog: 3
varMouse: 1

PL/SQL procedure successfully completed.

如果类型和名称的组合不唯一,那么您当前的代码会出错(太多行);这会沉默地选择最高的ID。

如果您还获取名称可能相同的其他类型的ID,您也可以在案例表达式中包含该类型:

select max(case when type = 'Object' and name = 'Cat' then id end),
  max(case when type = 'Object' and name = 'Dog' then id end),
  max(case when type = 'Object' and name = 'Mouse' then id end)
  -- , ... other combinations you want to get
into varCat, varDog, varMouse --, ... other variables
from mytable
where (type = 'Object' and name in ('Cat', 'Dog', 'Mouse'))
or ... ;

答案 1 :(得分:2)

可能使用数据透视查询:

select cat, dog, mouse
  into varCat, varDog, varMouse
  from (select * from mytable where Type = 'Object')
 pivot (max(id) for name in ('Cat' cat, 'Dog' dog, 'Mouse' mouse))

此查询将为每个ID列返回最高name。如果您有更多名称,请将它们添加到查询的最后一行的列表中。此外,您可以选择其他聚合函数。

答案 2 :(得分:1)

您可以使用带有简单选择查询的循环。

   FOR rec IN (SELECT ID, NAME
                 FROM myTable
                WHERE TYPE = 'Object' AND name in ('Cat', 'Dog', 'Mouse'))
   LOOP
      IF rec.NAME = 'Cat'
      THEN
         varCat := rec.ID;
      ELSIF rec.NAME = 'Dog'
      THEN
         varDog := rec.ID;
         ..
         ..
      END IF;
  END LOOP;

答案 3 :(得分:-1)

INSERT INTO mytable   (varCat,varDog,varMouse)VALUES(   (SELECT id FROM Table1 where id),   (SELECT tax_status_id FROM tax_status WHERE tax_status_code =?),   (SELECT recipient_id FROM recipient WHERE recipient_code =?))