[英]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.