PL/SQL Function to check whether a number is prime or not - sql

Please find the error and rectify this code
This is a PL/SQL function to check whether a number is prime or not
By using the flag method instead of using count to check the requirement, it's working perfectly but not for this method.
create or replace function isprime(x in number)
RETURN number
IS
i int;
count int;
BEGIN
count:=0;
for i in 2..x/2 LOOP
if mod(x,i)=0 then
count:=count+1;
end if;
end loop;
return count;
end;
/
Warning: Function created with compilation errors.
DECLARE
n int;
c int;
BEGIN
n:=&n;
c:=isprime(n);
if c=0 then
dbms_output.put_line(n||'is a prime number');
else
dbms_output.put_line(n||'is not prime');
end if;
end;
/
Enter value for n: 5
old 5: n:=&n;
new 5: n:=5;
c:=isprime(n);
*
ERROR at line 6:
ORA-06550: line 6, column 4:
PLS-00905: object SYSTEM.ISPRIME is invalid
ORA-06550: line 6, column 1:
PL/SQL: Statement ignored
Here is the error list:
SQL> show errors
Errors for FUNCTION ISPRIME:
LINE/COL ERROR
-------- -----------------------------------------------------------------
10/1 PL/SQL: Statement ignored
10/8 PLS-00204: function or pseudo-column 'COUNT' may be used inside a
SQL statement only
13/1 PL/SQL: Statement ignored
13/8 PLS-00204: function or pseudo-column 'COUNT' may be used inside a
SQL statement only

COUNT is reserve sql word, have a look at this as an alternative solution for this task.
DECLARE
value_ NUMBER default :A;
i NUMBER DEFAULT 5;
is_prime VARCHAR2(5 CHAR);
BEGIN
IF value_ = 2 OR value_ = 3 THEN
is_prime := 'TRUE';
ELSIF MOD(value_,2)=0 OR MOD(value_,3)=0 OR value_ <= 1 THEN
is_prime := 'FALSE';
END IF;
WHILE POWER(i,2) <= value_ LOOP
IF MOD(value_,i)=0 OR MOD(value_,i + 2)=0 THEN
is_prime := 'FALSE';
exit;
END IF;
i := i + 6;
end loop;
is_prime := nvl(is_prime,'TRUE');
DBMS_Output.Put_Line(is_prime||' IT IS '||CASE is_prime WHEN 'FALSE' THEN 'NOT' END||'A PRIME NUMBER');
END;

Related

Function returning error texts in Oracle APEX

I am trying to take a count of the records in the interactive grid and based on that I am trying to pass a message to the user. However, I am getting error : ORA-06550: line 1, column 141: PLS-00103: Encountered the symbol "NUMBER" when expecting one of the following: := . ( # % ; The symbol "." was substituted for "NUMBER" to continue.Following is my code in the validation. Validation Type is : Function Returning Error Text.
l_count NUMBER := 0;
BEGIN
SELECT COUNT(1)
INTO l_count
FROM ugh
WHERE ugh.pre = :PRE
AND ugh.APP1 = :APP1
AND ugh.APP2 = :APP2
AND ugh.APP3 = :APP3
AND ugh.FINL_APP = :FINL_APP;
IF l_count > 1 THEN
IF END_DATE IS NULL THEN
RETURN 'Error Message to be displayed.';
ELSE
RETURN NULL;
END IF;
ELSE
RETURN NULL;
END IF;
END;
Can anyone please help ?
Looks like you're missing the DECLARE keyword:
DECLARE --> this
l_count NUMBER := 0;
BEGIN
SELECT COUNT (1)
INTO l_count
FROM ugh
Also, what is END_DATE? You never declared it. If it is a page item, then precede it with a colon, :END_DATE

Error in return of PLSQL ORACLE Not Working

This Code is:
CREATE OR REPLACE
PROCEDURE Actualiza_Saldo(fecha_ini IN DATE, fecha_fin IN DATE) RETURN NUMBER
AS
fechaTemp DATE;
diasTotales NUMBER := fecha_fin- fecha_ini;diasLaborables NUMBER;
sab VARCHAR2(10) := 'SÁBADO';dom VARCHAR2(10) := 'DOMINGO';diasTemp VARCHAR2(10);
BEGIN
diasLaborables:= diastotales;
FOR i IN 0..diasTotales LOOP
fechaTemp := fecha_ini + i;
DBMS_OUTPUT.PUT_LINE(to_char(fechaTemp));
diasTemp := TO_CHAR(fechaTemp, 'DAY', 'NLS_DATE_LANGUAGE=SPANISH');
IF (TRIM(diasTemp)=sab or TRIM(diasTemp)=dom) THEN
diaslaborables := diaslaborables-1;
END IF;
END LOOP;
dbms_output.put_line(diaslaborables);
RETURN diasLaborables;
END Actualiza_Saldo;
If I execute without returning it works, if I try to return a value it fails, I do not know what could be happening.
The error of oracle is:
Warning: la ejecución ha terminado con advertencias
PROCEDURE Actualiza_Saldo(fecha_ini Compilado.
Error que empieza en la línea 1 del comando:
EXEC Actualiza_Saldo();
Informe de error:
ORA-06550: línea 1, columna 7:
PLS-00905: el objeto HR.ACTUALIZA_SALDO no es válido
ORA-06550: línea 1, columna 7:
PL/SQL: Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:
The code with constant value:
CREATE OR REPLACE
PROCEDURE Actualiza_Saldo(fecha_ini IN DATE DEFAULT '10/08/2018', fecha_fin IN DATE DEFAULT '30/08/2018')
AS
fechaTemp DATE;
diasTotales NUMBER := fecha_fin- fecha_ini;diasLaborables NUMBER;
sab VARCHAR2(10) := 'SÁBADO';dom VARCHAR2(10) := 'DOMINGO';diasTemp VARCHAR2(10);
BEGIN
diasLaborables:= diastotales;
FOR i IN 0..diasTotales LOOP
fechaTemp := fecha_ini + i;
DBMS_OUTPUT.PUT_LINE(to_char(fechaTemp));
diasTemp := TO_CHAR(fechaTemp, 'DAY', 'NLS_DATE_LANGUAGE=SPANISH');
IF (TRIM(diasTemp)=sab or TRIM(diasTemp)=dom) THEN
diaslaborables := diaslaborables-1;
END IF;
END LOOP;
dbms_output.put_line(diaslaborables);
END Actualiza_Saldo;
EXEC Actualiza_Saldo();
And the exit of the code without the returns and the test values ​​is a route from the start date and the final date subtracting the days Saturday and Sunday.
PROCEDURE Actualiza_Saldo(fecha_ini Compilado.
anonymous block completed
10/08/18
11/08/18
12/08/18
13/08/18
14/08/18
15/08/18
16/08/18
17/08/18
18/08/18
19/08/18
20/08/18
21/08/18
22/08/18
23/08/18
24/08/18
25/08/18
26/08/18
27/08/18
28/08/18
29/08/18
30/08/18
14
But if I try to return the value the algorithm dies.
I have no idea what I am doing wrong or where is the fault, if you could help me I would greatly appreciate it.
Procedures cannot return a value, in Oracle, You can have out-parameters which would be visible after the procedure runs.
But here is another option you can try, instead of writing code to generate dates between two, try to do it using a single select query and open a out cursor to have the values populated after the proc completes
An example as follows
create or replace procedure generate_dates(start_date in date, end_date in date, result_set out sys_refcursor)
as
begin
open result_set for
select trunc(start_date)+level as output_dates
from dual
connect by level<=trunc(end_date)-trunc(start_date);
end;
if you are using sqlplus to connect to your database
you would call the proc as follows
var x refcursor
begin
generate_dates(date '2018-01-01',date '2018-12-31',:x);
end;
print x;
My mistake was that I was not doing a function but a procedure solved.
CREATE OR REPLACE
FUNCTION HR.Actualiza_Saldo(fecha_ini IN DATE/* DEFAULT '10/08/2018'*/, fecha_fin IN DATE/* DEFAULT '30/08/2018'*/) RETURN NUMBER
AS

Why am i getting this: PLSQL String length constraint Error

i have being working on this code for a while now and have tried everything i can think of.
This is the code block:
CREATE OR REPLACE PROCEDURE ADD_LOCATION_TO_DB (ploccode VARCHAR2, pminqty
NUMBER, pmaxqty NUMBER)AS
Err_Locode_Length EXCEPTION;
Err_Minqty_Range EXCEPTION;
Err_Maxqty_Range EXCEPTION;
Err_Maxqty_Greater_Minqty EXCEPTION;
BEGIN
IF LENGTH(ploccode) != 5 THEN
RAISE Err_Locode_Length;
ELSE IF pminqty > 10 OR pminqty < 0 THEN
RAISE Err_Minqty_Range;
ELSE IF pmaxqty > 10 OR pmaxqty < 0 THEN
RAISE Err_Maxqty_Range;
ELSE IF pminqty > pmaxqty THEN
RAISE Err_Maxqty_Greater_Minqty;
END IF;
END IF;
END IF;
END IF;
INSERT INTO LOCATION
VALUES (ploccode, pminqty, pmaxqty);
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
RAISE_APPLICATION_ERROR(-20081,'Duplicate Location ID');
WHEN Err_Locode_Length THEN
RAISE_APPLICATION_ERROR(-20082,'Location Code Lenght invalid');
WHEN Err_Minqty_Range THEN
RAISE_APPLICATION_ERROR(-20083,'Minium Qty is out of range');
WHEN Err_Maxqty_Range THEN
RAISE_APPLICATION_ERROR(-20084,'Maximum Qty is out of range');
WHEN Err_Maxqty_Greater_Minqty THEN
RAISE_APPLICATION_ERROR(-20086,'Minium Qty is Lager than Maximum Qty');
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20000,'Use Value of SQLERRM');
END;
/
CREATE OR REPLACE PROCEDURE ADD_LOCATION_VIASQLDEV AS
Dis_Msg VARCHAR2;
ploccode VARCHAR2;
pminqty NUMBER;
pmaxqty NUMBER;
BEGIN
dbms_output.put_line('--------------------------------------------------');
dbms_output.put_line('Adding location LocCode: ' || ploccode || ' MinQty: ' || pminqty || 'MaxQty' || pmaxqty);
ADD_LOCATION_TO_DB(ploccode, pminqty, pmaxqty);
dbms_output.put_line(Dis_Msg);
END;
/
When i run this set of procedures i get an error in the compiler stating:
Error(1,13): PLS-00215: String length constraints must be in range (1 .. 32767)
Error(2,14): PLS-00215: String length constraints must be in range (1 .. 32767)
I have tried adding constraints to the code that calls the main Procedure:
CREATE OR REPLACE PROCEDURE ADD_LOCATION_VIASQLDEV AS
Dis_Msg VARCHAR2(40);
ploccode VARCHAR2(5);
pminqty NUMBER(2);
pmaxqty NUMBER(2);
BEGIN
dbms_output.put_line('--------------------------------------------------');
dbms_output.put_line('Adding location LocCode: ' || ploccode || ' MinQty: ' || pminqty || 'MaxQty' || pmaxqty);
ADD_LOCATION_TO_DB(ploccode, pminqty, pmaxqty);
dbms_output.put_line(Dis_Msg);
END;
/
Adding these constrains does remove the errors with the compiler however i still revive errors when executing this testing code:
Error starting at line : 48 in command -
begin
dbms_output.put_line('Student ID: 1234567');
dbms_output.put_line('==========PART 3 TEST LOCATIONS==========================');
ADD_LOCATION_VIASQLDEV ('AF201',1,2);
ADD_LOCATION_VIASQLDEV('AF202',-3,4);
ADD_LOCATION_VIASQLDEV ('AF203',5,1);
ADD_LOCATION_VIASQLDEV ('AF204',6,7000);
ADD_LOCATION_VIASQLDEV ('AF20111',8,9);
end;
Error report -
ORA-06550: line 4, column 1:
PLS-00306: wrong number or types of arguments in call to 'ADD_LOCATION_VIASQLDEV'
ORA-06550: line 4, column 1:
PL/SQL: Statement ignored
ORA-06550: line 5, column 1:
PLS-00306: wrong number or types of arguments in call to 'ADD_LOCATION_VIASQLDEV'
ORA-06550: line 5, column 1:
PL/SQL: Statement ignored
ORA-06550: line 6, column 1:
PLS-00306: wrong number or types of arguments in call to 'ADD_LOCATION_VIASQLDEV'
ORA-06550: line 6, column 1:
PL/SQL: Statement ignored
ORA-06550: line 7, column 1:
PLS-00306: wrong number or types of arguments in call to 'ADD_LOCATION_VIASQLDEV'
ORA-06550: line 7, column 1:
PL/SQL: Statement ignored
ORA-06550: line 8, column 1:
PLS-00306: wrong number or types of arguments in call to 'ADD_LOCATION_VIASQLDEV'
ORA-06550: line 8, column 1:
PL/SQL: Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:
Can some one please tell me what i'm doing wrong.
Apologies if this is to much information or my formating is wrong.
You are confused between the declaration section and arguments sections of the procedure.
Your first error is due to the fact that you placed your supposedly arguments in the declaration section. then when you tried to add length to it, it compiled, but you left the procedure without arguments. then you run it with four arguments which caused the error since the procedure is created accepting no arguments.
create or replace procedure_name(
parameter1 datatype, --arguments section
parameter2 datatype
) AS
/*declaration section*/
variable1 datatype(length);
variable2 datatype(length);
BEGIN
/*your code here*/
END;
try this revise script
CREATE OR REPLACE PROCEDURE ADD_LOCATION_VIASQLDEV (Dis_Msg VARCHAR2,
ploccode VARCHAR2,
pminqty NUMBER,
pmaxqty NUMBER ) AS
BEGIN
dbms_output.put_line('--------------------------------------------------');
dbms_output.put_line('Adding location LocCode: ' || ploccode || ' MinQty: ' || pminqty || 'MaxQty' || pmaxqty);
ADD_LOCATION_TO_DB(ploccode, pminqty, pmaxqty);
dbms_output.put_line(Dis_Msg);
END;
In your first set of errors, you declared the function as using a VARCHAR2 variable, but didn't state a length in brackets after it. State a length
In your second set of errors you called the function add_location_viasqldev which takes 0 arguments, but you provided 3. Provide another argument or call a different function
Also, you can make your if/else a bit neater by doing:
IF test
ELSIF test
ELSIF test
ELSE
END IF;

Invalid Identifier When Trying to Use Package Function in Summation Expression

I'm trying to use the sum function with a package function but running into an "invalid identifier" bug. Here's some example code with the error causing function commented
create or replace type numType as object
(
myNum number
)
;
/
create or replace type numTypes is table of numType;
/
create or replace package testNumberPackage as
function ReturnNum(in_numType numType) return number;
end;
/
create or replace package body testNumberPackage as
function ReturnNum(in_numType numType) return number is
begin
return in_numType.myNum;
end;
end;
/
declare l_numTypes numTypes;
l_count number;
begin
l_numTypes := numTypes();
for i in 1 .. 100 loop
l_numTypes.extend(1);
l_numTypes(l_numTypes.last) := numType(i);
end loop;
select sum(n.myNum) into l_count from table(l_numTypes) n;
select sum(testNumberPackage.ReturnNum(n)) into l_count from table(l_numTypes) n; --causes the error
dbms_output.put_line(l_count);
end;
/
The exact error for this code is
ORA-06550: line 11, column 42
PL/SQL: ORA-00904: "N": invalid identifier
ORA-6550: line 11, column 3:
PL/SQL: SQL Statement ignored
Thanks for any help.
The first issue is that you can't pass a table into a parameter by using its alias. It doesn't even make sense to try doing that.
The next issue is how to get the column mynum that is returned from the table(l_numTypes) into the correct format to pass into testNumberPackage.ReturnNum, since it's of NUMBER datatype, and the function is expecting a numtype parameter.
To do that, you need to pass in an object with that column, like so: numtype(n.mynum).
The following works for me:
declare
l_numTypes numTypes;
l_count number;
begin
l_numTypes := numTypes();
for i in 1 .. 100 loop
l_numTypes.extend(1);
l_numTypes(l_numTypes.last) := numType(i);
end loop;
select sum(n.myNum) into l_count from table(l_numTypes) n;
select sum(testNumberPackage.ReturnNum(numtype(n.mynum))) into l_count from table(l_numTypes) n; --causes the error
dbms_output.put_line(l_count);
end;
/
5050
Clear as mud?

ORA-21700: object does not exist or is marked for delete

I have package with Period and TableOfPeriod types:
TYPE Period
IS RECORD
( StartPeriod Date,
EndPeriod Date
);
TYPE TableOfPeriod
IS TABLE OF Period;
and in this package I have three simple function:
FUNCTION Temp1
RETURN TableOfPeriod IS
returnedValue TableOfPeriod := TableOfPeriod();
BEGIN
returnedValue.extend(1);
returnedValue(1).StartPeriod := sysdate-100;
returnedValue(1).EndPeriod := sysdate;
RETURN returnedValue;
END Temp1;
FUNCTION CalculateFine
return VARCHAR2
IS
freewillLockTableRP TableOfPeriod:=TableOfPeriod();
compulsoryLockTableRP TableOfPeriod:=TableOfPeriod();
BEGIN
--for testing
compulsoryLockTableRP:=Temp1();
FOR i IN compulsoryLockTableRP.FIRST..compulsoryLockTableRP.LAST LOOP
IF(((compulsoryLockTableRP(i).EndPeriod - compulsoryLockTableRP(i).StartPeriod)>1)) THEN
BEGIN
-- RAISE_APPLICATION_ERROR(-20001, 'Hello world');
SELECT T111.StartPeriod StartPeriod,
T111.EndPeriod EndPeriod
bulk collect into freewillLockTableFull
FROM TABLE(DistributeDaysByPeriods(compulsoryLockTableRP, 5)) T111;
END;
END IF;
END LOOP;
/*SELECT T111.StartPeriod StartPeriod,
T111.EndPeriod EndPeriod
-- BULK COLLECT INTO compulsoryLockTableRP
bulk collect into freewillLockTableFull
FROM TABLE(DistributeDaysByPeriods(compulsoryLockTableRP, 5)) T111;*/
--===========
--SOME OTHER PROCESSING
RETURN 'Ok '
|| '#r';
EXCEPTION
WHEN No_Data_Found THEN return 'No data found#g';
-- WHEN OTHERS THEN RETURN SQLERRM;
END CalculateFine;
When I execute this function, I have next error:
"ORA-21700: object does not exist or is marked for delete ORA-06512:
at "MyPackageName", line 1181 ORA-06512: at line 1
21700. 00000 - "object does not exist or is marked for delete""
where 1181 line is a line with Select statement of CalculateFine function. Can anybody tell me, whats wrong and how I can solve this problem?
Check if you have in the same folder where your package is located a file with the same name but with an extention *.~sql (e.g.: your_file_name.~sql). I had the same error but after I have deleted an *.~sql file I could compile my package without ORA errors.