我需要 SQL*Plus 的 PL/SQL 代码。
我得到:
1
2 2
3 3 3
4 4 4 4
输出应该是:
1
2 2
3 3 3
4 4 4 4
代码:
SET SERVEROUTPUT ON SIZE 1000000
DECLARE
i NUMBER;
j NUMBER;
total_lines NUMBER := 4; -- Number of lines for the pyramid
leading_ spaces NUMBER;
line_output VARCHAR2(100); -- Variable to hold each line's output
BEGIN
-- Loop through each line to create the pyramid
FOR i IN 1..total_lines LOOP
-- Calculate leading spaces for centering the line
leading_spaces := total_lines - i;
-- Initialize the line output with leading spaces
line_output := LPAD(' ', leading_spaces);
-- Append numbers to the line output
FOR j IN 1..i LOOP
line_output := line_output || i || ' ';
END LOOP;
-- Print the line output
DBMS_OUTPUT.PUT_LINE(line_output);
END LOOP;
END;
/
代码没有给出正确的输出,但是:
1
2 2
3 3 3
4 4 4 4
PL/SQL procedure successfully completed.
SQL>
应该是:
1
2 2
3 3 3
4 4 4 4
但之间没有空格。
你正在做:
SET SERVEROUTPUT ON SIZE 1000000
你需要做:
SET SERVEROUTPUT ON SIZE 1000000 FORMAT WRAPPED
如果没有
format wrapped
,您生成的前导空格将被丢弃。
文档对此不是很清楚,但它确实说明了
word_wrapped
:
启用 WORD_WRAPPED 后,服务器输出的每一行都会在 SET LINESIZE 指定的行大小内换行。字边界处断线。 SQL*Plus 左对齐每行,跳过所有前导空格。
“跳过所有前导空格”仅适用于
word_wrapped
,不适用于 wrapped
。
似乎并没有说
word_wrapped
是默认的,但是如果你开始一个新会话并执行show serveroutput
你可以看到它是默认的。
它与工具无法正确显示您想要的内容有关。 这是 SQL*Plus;我使用的是
non-breakable space (chr(160)
) 而不是 ordinary 空格字符,结果是
SQL> SET SERVEROUTPUT ON SIZE 1000000
SQL> DECLARE
2 i NUMBER;
3 j NUMBER;
4 total_lines NUMBER := 4; -- Number of lines for the pyramid
5 leading_spaces NUMBER;
6 line_output VARCHAR2 (100); -- Variable to hold each line's output
7 BEGIN
8 -- Loop through each line to create the pyramid
9 FOR i IN 1 .. total_lines
10 LOOP
11 -- Calculate leading spaces for centering the line
12 leading_spaces := total_lines - i;
13
14 -- Initialize the line output with leading spaces
15 line_output := LPAD (chr(160), leading_spaces, chr(160));
16
17 -- Append numbers to the line output
18 FOR j IN 1 .. i
19 LOOP
20 line_output := line_output || i || chr(160);
21 END LOOP;
22
23 -- Print the line output
24 DBMS_OUTPUT.PUT_LINE (line_output);
25 END LOOP;
26 END;
27 /
1
2 2
3 3 3
4 4 4 4
PL/SQL procedure successfully completed.
SQL>
相同的代码在 TOAD 和 SQL Developer 中会产生这样的结果:DECLARE
total_lines CONSTANT NUMBER := 4; -- Number of lines for the pyramid
BEGIN
FOR i IN 1..total_lines LOOP
DBMS_OUTPUT.PUT_LINE(
LPAD(' ', total_lines - i, ' ')
|| RPAD(i, 2*i - 1, ' ' || i)
);
END LOOP;
END;
/
哪个输出:
1
2 2
3 3 3
4 4 4 4
如果你想整齐地格式化超过 9 行:
DECLARE
total_lines CONSTANT PLS_INTEGER := 10; -- Number of lines for the pyramid
term_width CONSTANT PLS_INTEGER := LENGTH(total_lines);
padding_char CONSTANT CHAR(1) := ' ';
BEGIN
FOR i IN 1..total_lines LOOP
DBMS_OUTPUT.PUT_LINE(
LPAD(padding_char, term_width * (total_lines - i), padding_char)
|| RPAD(
LPAD(i, term_width, padding_char),
(2 * i - 1)*term_width,
LPAD(i, 2 * term_width, padding_char)
)
);
END LOOP;
END;
/
哪个输出:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10