我想将查询的结果集存储到某个临时位置(光标所闻),然后使用循环针对值测试每一列。我尝试过
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列。
很抱歉无法正确发布我的问题。
答案 0 :(得分:2)
游标不存储结果,它实际上是一个指针,可让您遍历结果(如@Ted所示)。如果要将结果存储在PL / SQL块中,则可以使用a collection,可以将其声明为与表匹配的类型,以使其接近单行查询的记录类型;然后bulk-collect插入其中:
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'
值似乎将日期存储为字符串。您应该use the correct data type-将日期存储为实际日期。 (而且,如果该列是日期,那么您依赖于隐式转换,这也不是一个好主意...)
答案 1 :(得分:2)
这是遍历查询结果的非常简单的方法:
BEGIN
FOR rec IN (select col1, col2 from mytable where column = '20190103') LOOP
IF rec.col1 > rec.col2 THEN
...
END IF;
END LOOP;
END;
答案 2 :(得分:1)
以下是我认为可以帮助您的模板:
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;
答案 3 :(得分:0)
我修改了Search All Fields In All Tables For A Specific Value (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";