Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

plsql - Simple PL/SQL function to test if a string is a number

I'm experienced with T-SQL from SQL Server, but have recently begun working on a project utilizing an Oracle database (11g) and am having some issues writing what seems to be basic code.

I need to test whether a set of values are numeric, and only insert them into a table if they are. PL/SQL doesn't seem to have an is_number function, so I wrote my own based on an AskTom question.

create or replace 
function          IS_NUMBER(str in varchar2) return boolean
IS
  n number;
BEGIN
  select to_number(str) into n from dual;
  return (true);
EXCEPTION WHEN OTHERS THEN
  return (false);
END;

Eventually, I'd like to use this function in a WHERE clause, but for now I'm just trying to get it to run at all:

declare
  str varchar2(1);
  n boolean;
begin
  str := '0';
  select ca_stage.is_number(str) into n from dual;
end;

In SQL Developer, trying to run this gives me the following error report:

Error report:
ORA-06550: line 6, column 39:
PLS-00382: expression is of wrong type
ORA-06550: line 6, column 19:
PLS-00382: expression is of wrong type
06550. 00000 -  "line %s, column %s:
%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

The error report is straight-forward, but doesn't make sense. The function accepts a varchar2, and that's what I'm using as an input variable. It returns a boolean and again, that's what I'm using.

As I said, this is basic code, so I assume that I'm missing something fundamental.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Return a SQL datatype, e.g. VARCHAR2. Also, I'd recommend against using WHEN OTHERS. Also, you don't need a query on dual:

create or replace 
function IS_NUMBER(str in varchar2) return varchar2
IS
  n number;
BEGIN
  n := to_number(str);
  return 'Y';
EXCEPTION WHEN VALUE_ERROR THEN
  return 'N';
END;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...