我有一個表,如果存在資料,我必須使用 dbms_output 顯示資料。如果表是空的,我必須寫一條訊息“表是空的”。
我想使用游標,但我不知道當表為空時條件應該如何。
這很好用:
declare
cursor cursor_name is select nr, name from branch;
begin
for i in cursor_name
loop
dbms_output.put_line('Number: ' || to_char(i.nr) || ' Name: ' || i.name);
end loop;
end;
/
uj5u.com熱心網友回復:
只需使用一個變數來存盤一個標志,如果找到行,您可以設定該標志:
DECLARE
CURSOR cursor_name IS
SELECT nr, name FROM branch;
no_rows BOOLEAN := TRUE;
BEGIN
FOR i IN cursor_name LOOP
DBMS_OUTPUT.PUT_LINE('Number: ' || to_char(i.nr) || ' Name: ' || i.name);
no_rows := FALSE;
END LOOP;
IF no_rows THEN
DBMS_OUTPUT.PUT_LINE('Table is empty');
END IF;
END;
/
或者:
DECLARE
CURSOR cursor_name IS
SELECT nr, name FROM branch;
cursor_row cursor_name%ROWTYPE;
BEGIN
OPEN cursor_name;
FETCH cursor_name INTO cursor_row;
IF cursor_name%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('Table is empty');
END IF;
LOOP
EXIT WHEN cursor_name%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(
'Number: ' || to_char(cursor_row.nr) || ' Name: ' || cursor_row.name
);
FETCH cursor_name INTO cursor_row;
END LOOP;
CLOSE cursor_name;
END;
/
其中,對于樣本資料:
CREATE TABLE branch (nr, name) AS
SELECT 1, 'Aspen' FROM DUAL UNION ALL
SELECT 2, 'Beech' FROM DUAL UNION ALL
SELECT 3, 'Cedar' FROM DUAL;
兩個輸出:
Number: 1 Name: Aspen Number: 2 Name: Beech Number: 3 Name: Cedar
之后:
DELETE FROM branch;
兩個輸出:
Table is empty
db<>在這里擺弄
uj5u.com熱心網友回復:
你可以使用這樣一個簡單的代碼塊
SQL> SET serveroutput ON
SQL> DECLARE
v_mes VARCHAR2(50);
BEGIN
SELECT DECODE(COUNT(*),0,'Table is empty')
INTO v_mes
FROM t;
DBMS_OUTPUT.PUT_LINE(v_mes);
END;
/
如果您的目標僅在表格沒有資料的情況下顯示
uj5u.com熱心網友回復:
如果您想使用游標,那么這可能是一種選擇:
SQL> set serveroutput on;
創建一個空表:
SQL> create table branch (nr number, name varchar2(20));
Table created.
匿名 PL/SQL 塊:宣告游標及其變數,獲取,檢查是否找到任何內容:
SQL> declare
2 cursor c1 is select nr, name from branch;
3 c1r c1%rowtype;
4 begin
5 open c1;
6 fetch c1 into c1r;
7 if c1%notfound then
8 dbms_output.put_line('Table is empty');
9 end if;
10 close c1;
11 end;
12 /
Table is empty --> as expected
PL/SQL procedure successfully completed.
SQL>
uj5u.com熱心網友回復:
綜合使用的解決方案資料庫視圖-在使用游標和dbms_output你喜歡:
create view v_branch as
select nr, name from branch
union all
select null, 'Table is empty' name from dual
where 0 = (select count(*) from branch);
select * from v_branch;
NR NAME
---------- --------------
1 x
delete from branch;
select * from v_branch;
NR NAME
---------- --------------
Table is empty
您不會希望將它用于非常大的表格 - 但它適用于您打算使用 列印每一行的表格put_line。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/408201.html
標籤:
