Oracle-12c

輸入以不同的輸出格式列印

  • February 7, 2020

我有一個值(例如 ORACLE),我想使用 Oracle 查詢在單獨的行上列印每個字母。

輸入值:

ORACLE

輸出:

O
R 
A
C
L
E

用 PL/SQL 先找到字元串的長度,用子字元串提取每個字元並用 dbms_output 列印

BEGIN
 FOR ctr in 1..LENGTH('ORACLE')
 LOOP
  DBMS_OUTPUT.PUT_LINE(SUBSTR('ORACLE',ctr,1));
 END LOOP;
END;

或聲明變數

DECLARE
l_str VARCHAR2(20):='ORACLE';
l_len INTEGER;
BEGIN
 l_len:=LENGTH(l_str);
 FOR ctr IN 1..l_len
  LOOP
   DBMS_OUTPUT.PUT_LINE(SUBSTR(l_str,ctr,1));
  END LOOP;
END;

這是在 sql*plus 中執行 pl/sql

SQL> set serveroutput on
SQL> DECLARE
 2  l_str VARCHAR2(20):='ORACLE';
 3  l_len INTEGER;
 4  BEGIN
 5    l_len:=LENGTH(l_str);
 6    DBMS_OUTPUT.PUT_LINE('Output:');
 7    FOR ctr IN 1..l_len
 8     LOOP
 9      DBMS_OUTPUT.PUT_LINE(SUBSTR(l_str,ctr,1));
10     END LOOP;
11  END;
12  /
Output:
O
R
A
C
L
E

PL/SQL procedure successfully completed.

SQL>

您可以使用分層查詢在 SQL 中執行此操作,例如:

WITH t AS (SELECT 'ORACLE' str FROM dual UNION ALL
          SELECT 'ROCKS' str FROM dual)
SELECT str,
      SUBSTR(str, LEVEL, 1) new_str
FROM   t
CONNECT BY PRIOR str = str
          AND PRIOR sys_guid() IS NOT NULL
          and LEVEL <= LENGTH(str);

STR    NEW_STR
------ -------
ORACLE O
ORACLE R
ORACLE A
ORACLE C
ORACLE L
ORACLE E
ROCKS  R
ROCKS  O
ROCKS  C
ROCKS  K
ROCKS  S

引用自:https://dba.stackexchange.com/questions/259005