题目:给一个整数,如何得到一个有规律的字符串。比如:2得到12;3得到123;4要得到1234;5得到12345,而6得到123456;当数值大于7时,大于7的数都为7。比如8得到12345677; 10得到1234567777等,整数值最大为24
下面是我的方法:
create or replace procedure SP_TEST(str_in in integer) is
output varchar2(200);
begin
select case when str_in > 7 then rpad('1234567',str_in,'7')
else substr('1234567',0,str_in) end into output
from dual;
DBMS_OUTPUT.put_line(output);
end SP_TEST;
测试结果:
以下为网友的代码:
VAR N NUMBER;
EXEC :N:=5;
SELECT LPAD(RPAD('1234567',30,'7'),:N) FROM DUAL;
测试结果:
分析:
我使用了Oracle中的case when 逻辑判断 以及rpad、substr函数来实现。而网友见使用了lpad和rpad来实现。
下面是lpad,rpad、substr,的用法:
http://www.techonthenet.com/oracle/functions/lpad.php
Oracle/PLSQL: Lpad Function
In Oracle/PLSQL, the lpad function pads the left-side of a string with a specific set of characters (whenstring1 is not null).
The syntax for the lpad function is:
lpad( string1, padded_length, [ pad_string ] )
string1 is the string to pad characters to (the left-hand side).
padded_length is the number of characters to return. If the padded_length is smaller than the original string, the lpad function will truncate the string to the size ofpadded_length.
pad_string is optional. This is the string that will be padded to the left-hand side ofstring1. If this parameter is omitted, the lpad function will pad spaces to the left-side ofstring1.
Applies To:
- Oracle 8i, Oracle 9i, Oracle 10g, Oracle 11g
For Example:
lpad('tech', 7); would return ' tech' lpad('tech', 2); would return 'te' lpad('tech', 8, '0'); would return '0000tech' lpad('tech on the net', 15, 'z'); would return 'tech on the net' lpad('tech on the net', 16, 'z'); would return 'ztech on the net'
Oracle/PLSQL: Rpad Function
In Oracle/PLSQL, the rpad function pads the right-side of a string with a specific set of characters (whenstring1 is not null).
The syntax for the rpad function is:
rpad( string1, padded_length, [ pad_string ] )
string1 is the string to pad characters to (the right-hand side).
padded_length is the number of characters to return. If the padded_length is smaller than the original string, the rpad function will truncate the string to the size ofpadded_length.
pad_string is optional. This is the string that will be padded to the right-hand side ofstring1. If this parameter is omitted, the rpad function will pad spaces to the right-side ofstring1.
Applies To:
- Oracle 8i, Oracle 9i, Oracle 10g, Oracle 11g
For Example:
rpad('tech', 7); would return 'tech ' rpad('tech', 2); would return 'te' rpad('tech', 8, '0'); would return 'tech0000' rpad('tech on the net', 15, 'z'); would return 'tech on the net' rpad('tech on the net', 16, 'z'); would return 'tech on the netz'