Oracle - 数字到 varchar

发布于 2024-08-08 09:33:43 字数 449 浏览 6 评论 0原文

我有一个包含 Number 类型列的表

create table tmp (
    /*other fields*/
    some_field Number
)

,在 PL SQL 脚本中,我想将该字段转换为 varchar。但是,我不知道它的长度,所以我得到了一个例外

异常消息是 ORA-06502: PL/SQL:数字或值错误: 字符串缓冲区太小

v_some_field varchar(21);
/*...*/
v_some_field := TO_CHAR(some_field,'999999999999999999999');

我应该如何声明v_some_field缓冲区?将其设置为 varchar(32767) 似乎很残酷,还有其他选择吗?

I have a table containing a column of type Number

create table tmp (
    /*other fields*/
    some_field Number
)

and in a PL SQL script, I want to convert that field to a varchar. However, i don't know its length, so I get an exception

Exception message is ORA-06502:
PL/SQL: numeric or value error:
character string buffer too small

v_some_field varchar(21);
/*...*/
v_some_field := TO_CHAR(some_field,'999999999999999999999');

How should i declare the v_some_field buffer? Setting it to varchar(32767) seems quite brute, is there any alternative?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不顾 2024-08-15 09:33:43

您收到错误不是因为数字太大,而是因为 to_char 的结果是 22 个字符长(21x"9"+ 一个符号字符):

SQL> DECLARE
  2     some_field   NUMBER := 123;
  3     v_some_field VARCHAR(21);
  4  BEGIN
  5     v_some_field := TO_CHAR(some_field, '999999999999999999999');
  6  END;
  7  /

ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 6

SQL> DECLARE
  2     some_field   NUMBER := 123;
  3     v_some_field VARCHAR(22);
  4  BEGIN
  5     v_some_field := TO_CHAR(some_field, '999999999999999999999');
  6  END;
  7  /

PL/SQL procedure successfully completed

you're getting an error not because the number is too large but because the result of your to_char is 22 characters long (21x"9"+one character for the sign):

SQL> DECLARE
  2     some_field   NUMBER := 123;
  3     v_some_field VARCHAR(21);
  4  BEGIN
  5     v_some_field := TO_CHAR(some_field, '999999999999999999999');
  6  END;
  7  /

ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 6

SQL> DECLARE
  2     some_field   NUMBER := 123;
  3     v_some_field VARCHAR(22);
  4  BEGIN
  5     v_some_field := TO_CHAR(some_field, '999999999999999999999');
  6  END;
  7  /

PL/SQL procedure successfully completed
聆听风音 2024-08-15 09:33:43

您可以通过用整数和小数位转换负值来确定转换后的 varchar2 的最大长度:

set serveroutput on
declare
   n number;
begin
   n := -4/3;
   dbms_output.put_line(length(to_char(n)));
end;
/

对我来说,输出是 41。

You could determine the maximum length of your converted varchar2 by converting a negative value with integral and fractional digits:

set serveroutput on
declare
   n number;
begin
   n := -4/3;
   dbms_output.put_line(length(to_char(n)));
end;
/

Output is 41 for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文