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

问题描述 投票:0回答:4

在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';

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

oracle plsql
4个回答
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,则也可以在case表达式中包含该类型:

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 ... ;

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。如果您有更多名称,请将它们添加到查询的最后一行的列表中。此外,您可以选择其他聚合函数。


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;

-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 =?))

© www.soinside.com 2019 - 2024. All rights reserved.