[英]Storing Select result and using loop to test in PL/SQL block
我想将查询的结果集存储到某个临时位置(游标所闻),然后使用循环针对值测试每一列。 我试过了
Declare r_rec mytable%ROWTYPE;
BEGIN
select * into r_rec from mytable where column='20190103';
/*IF need to test certain condition for each column.
Then
V_C:=V_C+1;
end if; */
end;
/
如果您感到困惑,我很抱歉。 我的要求是检查一组记录中的任何列是否包含0(如果需要的话),我需要对其进行递增以获取在任何列中具有0的行的计数。 我可以查询它,但是我必须键入所有200列,而且我正在寻找一种替代方法,可以在该方法中测试选择查询的每个记录,以检查提取的任何记录中的任何列是否为0。
很抱歉无法正确发布我的问题。
游标不存储结果,它实际上是一个指针,可让您遍历结果(如@Ted所示)。 如果要将结果存储在PL / SQL块中,则可以使用collection ,可以将其声明为与表匹配的类型,以使其接近单行查询的记录类型; 然后批量收集到:
declare
type t_tab is table of mytable%ROWTYPE;
v_tab t_tab;
v_c pls_integer := 0;
begin
select *
bulk collect into v_tab
from mytable
where col1='20190103';
for i in 1..v_tab.count loop
if v_tab(i).col2 = 'Y' then -- whatever you need to test
v_c := v_c + 1;
end if;
end loop;
dbms_output.put_line(v_c);
end;
/
但是除非您对匹配的行和不匹配您的条件的行进行其他操作,否则可以将其作为测试添加到主查询中:
declare
type t_tab is table of mytable%ROWTYPE;
v_tab t_tab;
v_c pls_integer := 0;
begin
select *
bulk collect into v_tab
from mytable
where col1='20190103'
and col2='Y'; -- whatever you need to test
for i in 1..v_tab.count loop
v_c := v_c + 1;
end loop;
dbms_output.put_line(v_c);
end;
/
如果只计算匹配的行,则不需要游标或集合,只需使用聚合函数即可:
declare
v_c pls_integer;
begin
select count(*)
into v_c
from mytable
where col1='20190103'
and col2='Y'; -- whatever you need to test
dbms_output.put_line(v_c);
end;
/
或完全不使用PL / SQL:
select count(*)
from mytable
where col1='20190103'
and col2='Y'; -- whatever you need to test
顺便说一句,您的'20190103'
值看起来像是将日期存储为字符串。 您应该使用正确的数据类型 -将日期存储为实际日期。 (如果列是日期,那么您将依赖于隐式转换,这也不是一个好主意...)
这是一种遍历查询结果的非常简单的方法:
BEGIN
FOR rec IN (select col1, col2 from mytable where column = '20190103') LOOP
IF rec.col1 > rec.col2 THEN
...
END IF;
END LOOP;
END;
这是我认为可以帮助您的模板:
DECLARE
cursor c1 is
select column1, column2 ... etc from mytable where column='20190103';
BEGIN
FOR r_rec in c1
LOOP
if r_rec.column_XYZ = something then
do_something;
end if;
END LOOP;
END;
我修改了“在所有表的所有字段中搜索特定值”的答案(Oracle)
做计数。 它将对包含0的表中每个字段的记录计数。用您的表名替换我的表名。
SELECT count(*),
SUBSTR (table_name, 1, 30) "Table",
SUBSTR (column_name, 1, 30) "Column"
FROM cols,
TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '
|| column_name
|| ' from '
|| table_name
|| ' where upper('
|| column_name
|| ') like upper(''%'
|| 0
|| '%'')' ).extract ('ROWSET/ROW/*') ) ) t
where table_name = 'INVENTORY_LINE'
group by SUBSTR (table_name, 1, 30) ,
SUBSTR (column_name, 1, 30)
ORDER BY "Table";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.