我是PL / SQL的新手,这里是我的代码函数,无论是否找到素数..
create or replace function f_chkPrime(v number)
return varchar2
declare number check;
as begin
for i 2..v loop
if mod(v,i)=0
then
check:=0;
exit;
else
check:=1;
end if;
end loop;
if(check=1)
then
return 'prime';
else
return 'not prime';
end if;
end f_chkPrime;
/
我在sql plus中遇到编译错误。哪里出错了?
答案 0 :(得分:1)
包含实际的错误消息总是有帮助的,这样我们就不必猜测了。我的假设是错误是你有一个你不想要的declare
。使用declare ... begin ... end
创建匿名PL / SQL块。在函数中,您可以在as|is
和begin
之间声明变量。变量名也出现在数据类型之前。
create or replace function f_chkPrime(v number)
return varchar2
as
check number;
begin
for i 2..v loop
if mod(v,i)=0
then
check:=0;
exit;
else
check:=1;
end if;
end loop;
if(check=1)
then
return 'prime';
else
return 'not prime';
end if;
end f_chkPrime;
答案 1 :(得分:1)
DECLARE
语句来表示某个功能。FOR
循环缺少IN
语句。v
的素数系数大于SQRT(v)
;如果您检查过它不是2的倍数,则无需检查所有偶数。MOD(v,v)=0
(这将始终为真),因此该函数将始终返回not prime
。EXIT
循环;相反,你可以在找到结果后立即返回结果。像这样:
CREATE OR REPLACE FUNCTION f_chkPrime(
v NUMBER
) RETURN VARCHAR2
AS
np CONSTANT CHAR(9) := 'Not Prime';
p CONSTANT CHAR(5) := 'Prime';
BEGIN
IF v = 2 THEN
RETURN p;
ELSIF v <= 1 OR MOD(v,2) = 0 THEN
RETURN np;
END IF;
FOR i IN 1 .. (SQRT(v)-1)/2 LOOP
IF MOD(v,i*2+1) = 0 THEN
RETURN np;
END IF;
END LOOP;
RETURN p;
END f_chkPrime;
/
<强>测试强>
SELECT LEVEL AS Value,
f_chkPrime( LEVEL ) AS is_prime
FROM DUAL
CONNECT BY LEVEL <= 30;
<强>结果
VALUE IS_PRIME
---------- ---------
1 Not Prime
2 Prime
3 Prime
4 Not Prime
5 Prime
6 Not Prime
7 Prime
8 Not Prime
9 Not Prime
10 Not Prime
11 Prime
12 Not Prime
13 Prime
14 Not Prime
15 Not Prime
16 Not Prime
17 Prime
18 Not Prime
19 Prime
20 Not Prime
21 Not Prime
22 Not Prime
23 Prime
24 Not Prime
25 Not Prime
26 Not Prime
27 Not Prime
28 Not Prime
29 Prime
30 Not Prime