PL/SQL how can ı create string function= - oracle

In the desired structure, the function will take 2 string parameters.
If 2nd String is found in 1st String; The 1.string in the 2.string will be removed and added to the end of the 2.string.
If it is not found, the error 'NOT FOUND' will be given.
The desired structure should be as follows.

Here's one option:
SQL> create or replace function f_test (par_1 in varchar2, par_2 in varchar2)
2 return varchar2
3 is
4 retval varchar2(20);
5 begin
6 if instr(par_1, par_2) > 0 then
7 retval := replace(par_1, par_2) || par_2;
8 else
9 retval := 'Not found';
10 end if;
11
12 return retval;
13 end;
14 /
Function created.
SQL>
SQL> select f_test('topualiat', 'ali' ) result_1,
2 f_test('little' , 'foot') result_2
3 from dual;
RESULT_1 RESULT_2
--------------- ---------------
topuatali Not found
SQL>

Related

PL/SQL Function error Encountered the symbol "(" when expecting one of the following

error in using pl/sql function in the blocks of pl/sql
i'm trying to replace a char with a varchar2 using a function
i want to replace 'M' char to 'Male' VARCHAR2 after extract the data from the table using cursor
this is my code
`
CREATE OR REPLACE FUNCTION change_gender(GENDER IN CHAR)
RETURN VARCHAR2(6);
IS
new_gender VARCHAR2(6);
BEGIN
IF (GENDER == 'M') THEN
new_gender := 'Male'
return new_gender;
END;
DECLARE
current_student_address STUDENTS.address%type;
CURSOR students_cursor IS
SELECT ID,NAME,GENDER
FROM STUDENTS
WHERE ADDRESS = current_student_address;
students_row students_cursor%ROWTYPE;
BEGIN
current_student_address := 'Road102';
FOR students_row IN students_cursor LOOP
DBMS_OUTPUT.PUT_LINE(students_row.id || ' ' || students_row.name || ' ' || change_gender(students_row.gender));
END LOOP;
END;
`
and this is the error I'm receiving
Error at line 2: PLS-00103: Encountered the symbol "(" when expecting one of the following:
. # % ; is default authid as cluster order using external
character deterministic parallel_enable pipelined aggregate
result_cache accessible rewrite
It's just =, not ==. Also, you're missing statement terminator (semi-colon), as well as end if. Return datatype can't have size.
As of the function's logic: what about other genders? What will function return then? It must return something (even if it were null).
Therefore, I'd suggest something like this:
Sample data:
SQL> select * from students;
ID NAME ADDRESS GENDER
---------- ------ ------- ----------
1 Little Road102 M
2 Foot Road102 F
Function:
SQL> CREATE OR REPLACE FUNCTION change_gender(GENDER IN CHAR)
2 RETURN VARCHAR2
3 IS
4 new_gender VARCHAR2(6);
5 BEGIN
6 RETURN case when gender = 'M' then 'Male'
7 when gender = 'F' then 'Female'
8 else 'Other'
9 end;
10 end;
11 /
Function created.
Testing:
SQL> set serveroutput on
SQL> DECLARE
2 current_student_address STUDENTS.address%type;
3 CURSOR students_cursor IS
4 SELECT ID,NAME,GENDER
5 FROM STUDENTS
6 WHERE ADDRESS = current_student_address;
7 students_row students_cursor%ROWTYPE;
8 BEGIN
9 current_student_address := 'Road102';
10 FOR students_row IN students_cursor LOOP
11 DBMS_OUTPUT.PUT_LINE(students_row.id || ' ' || students_row.name || ' ' ||
12 change_gender(students_row.gender));
13 END LOOP;
14 END;
15 /
1 Little Male
2 Foot Female
PL/SQL procedure successfully completed.
SQL>

How to insert encrypted value in table Oracle apex

Hi everyone so I'm making an authentification scheme that has 2 functions.
A function that authenticates the user. All the data for the user is stored in a table called DJELATNIK which has attributes KORISNICKO_IME (username) and LOZINKA (password) and some more.
So this function just returns true if the username and password match in that table.
create or replace FUNCTION
prijava_custom(p_username IN VARCHAR2, p_password IN VARCHAR2)
RETURN BOOLEAN
AS
v_korisnicko varchar2(100);
v_lozinka varchar2(100);
BEGIN
SELECT KORISNICKO_IME, LOZINKA
INTO v_korisnicko, v_lozinka
FROM DJELATNIK
WHERE UPPER(KORISNICKO_IME) = UPPER(p_username)
AND LOZINKA = enkripcija_MD5(p_password);
RETURN TRUE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN FALSE;
END;
The other function is the encryption mentioned in the last function.
create or replace Function enkripcija_MD5 (pstring IN VARCHAR2) Return VARCHAR2 IS
hash_lozinka VARCHAR2(32) := '' ;
BEGIN
hash_lozinka := DBMS_OBFUSCATION_TOOLKIT.md5(input => UTL_I18N.STRING_TO_RAW (pstring, 'AL32UTF8' ));
RETURN hash_lozinka;
END enkripcija_MD5;
The thing that escapes my mind at the moment is how I save the encrypted password in the table instead of the plain text password?
I tried making an "After submit" process on the FORM edit page but that didn't work. Tried making a dynamic action that sets the password value right away to the hashed value, but that didnt work either. I know it's like a really banal thing and I should know it but I really cant think of it so I'm looking for ideas.
One option would be a database trigger.
Here's an example.
Simplified table:
SQL> CREATE TABLE djelatnik
2 (
3 korisnicko_ime VARCHAR2 (20),
4 lozinka VARCHAR2 (32)
5 );
Table created.
Function:
SQL> CREATE OR REPLACE FUNCTION enkripcija_MD5 (pstring IN VARCHAR2)
2 RETURN VARCHAR2
3 IS
4 hash_lozinka VARCHAR2 (32) := '';
5 BEGIN
6 hash_lozinka :=
7 DBMS_OBFUSCATION_TOOLKIT.md5 (
8 input => UTL_I18N.STRING_TO_RAW (pstring, 'AL32UTF8'));
9 RETURN hash_lozinka;
10 END enkripcija_MD5;
11 /
Function created.
Trigger:
SQL> CREATE OR REPLACE TRIGGER trg_biu_djel
2 BEFORE INSERT OR UPDATE
3 ON djelatnik
4 FOR EACH ROW
5 BEGIN
6 :new.lozinka := enkripcija_md5 (:new.lozinka);
7 END;
8 /
Trigger created.
Let's test it:
SQL> INSERT INTO djelatnik (korisnicko_ime, lozinka)
2 VALUES ('little', 'foot');
1 row created.
Table contents:
SQL> SELECT * FROM djelatnik;
KORISNICKO_IME LOZINKA
-------------------- --------------------------------
little D8735F7489C94F42F508D7EB1C249584
Query from your prijava_custom function:
SQL> SELECT *
2 FROM djelatnik
3 WHERE UPPER (korisnicko_ime) = 'LITTLE'
4 AND lozinka = enkripcija_md5 ('foot');
KORISNICKO_IME LOZINKA
-------------------- --------------------------------
little D8735F7489C94F42F508D7EB1C249584
SQL>
Testing your function:
SQL> set serveroutput on
SQL> CREATE OR REPLACE FUNCTION prijava_custom (p_username IN VARCHAR2,
2 p_password IN VARCHAR2)
3 RETURN BOOLEAN
4 AS
5 v_korisnicko VARCHAR2 (100);
6 v_lozinka VARCHAR2 (100);
7 BEGIN
8 SELECT KORISNICKO_IME, LOZINKA
9 INTO v_korisnicko, v_lozinka
10 FROM DJELATNIK
11 WHERE UPPER (KORISNICKO_IME) = UPPER (p_username)
12 AND LOZINKA = enkripcija_MD5 (p_password);
13
14 RETURN TRUE;
15 EXCEPTION
16 WHEN NO_DATA_FOUND
17 THEN
18 RETURN FALSE;
19 END;
20 /
Function created.
SQL> begin
2 if prijava_custom('little', 'foot') then
3 dbms_output.put_line('True');
4 else
5 dbms_output.put_line('False');
6 end if;
7 end;
8 /
True
PL/SQL procedure successfully completed.
SQL>
Everything looks OK to me.

I want to Create a function named VALIDATE_EMP which accepts employeeNumber as a parameter, Returns TRUE or FALSE depending on existence

Sample Data
create table Employees (emp_id number, emp_name varchar2(50), salary number, department_id number) ;
insert into Employees values(1,'ALex',10000,10);
insert into Employees values(2,'Duplex',20000,20);
insert into Employees values(3,'Charles',30000,30);
insert into Employees values(4,'Demon',40000,40);
Code :
create or replace function validate_emp(empno in number)
return boolean
is lv_count number
begin
select count(employee_id) into lv_count from hr.employees where employee_id = empno;
if lv_count >1 then
return true;
else
return false;
end;
I want to Create a function named VALIDATE_EMP which accepts empno as a parameter, Returns TRUE if the specified employee exists in the table name “Employeee” else FALSE.
missing semi-colon as terminator of the local variable declaration
if user you're connected to isn't hr, remove it (otherwise, leave it as is)
column name is emp_id, not employee_id
missing end if
When fixed, code compiles:
SQL> CREATE OR REPLACE FUNCTION validate_emp (empno IN NUMBER)
2 RETURN BOOLEAN
3 IS
4 lv_count NUMBER;
5 BEGIN
6 SELECT COUNT (emp_id)
7 INTO lv_count
8 FROM employees
9 WHERE emp_id = empno;
10
11 IF lv_count > 1
12 THEN
13 RETURN TRUE;
14 ELSE
15 RETURN FALSE;
16 END IF;
17 END;
18 /
Function created.
SQL>
How to call it? Via PL/SQL as Oracle's SQL doesn't have the Boolean datatype.
SQL> set serveroutput on
SQL> declare
2 result boolean;
3 begin
4 result := validate_emp(1);
5
6 dbms_output.put_line(case when result then 'employee exists'
7 else 'employee does not exist'
8 end);
9 end;
10 /
employee does not exist
PL/SQL procedure successfully completed.
SQL>
Maybe you'd rather return VARCHAR2; then you'd mimic Boolean, but you'd be able to use it in plain SQL:
SQL> CREATE OR REPLACE FUNCTION validate_emp (empno IN NUMBER)
2 RETURN VARCHAR2
3 IS
4 lv_count NUMBER;
5 BEGIN
6 SELECT COUNT (emp_id)
7 INTO lv_count
8 FROM employees
9 WHERE emp_id = empno;
10
11 IF lv_count > 1
12 THEN
13 RETURN 'TRUE';
14 ELSE
15 RETURN 'FALSE';
16 END IF;
17 END;
18 /
Function created.
SQL> select validate_emp(1) from dual;
VALIDATE_EMP(1)
-------------------------------------------------------------------
FALSE
SQL>

Need to find the number of times PLSQL function gets executed

There is a requirement from client side that after function get executed more than 2 times then its output should be concatinated with some string and this function is inside a package .
for example...
function get called 7 times from package (its a backend job which executed automatically) and returns 'abc' but when the job runs for the 3rd time i want output 'abcde'.
One option is to create a separate log table and insert a row for each of function calls; then - within a function - check how many times it was invoked and return appropriate output. Something like this:
Log table:
SQL> CREATE TABLE flog
2 (
3 cuser VARCHAR2 (30),
4 sid NUMBER
5 );
Table created.
Package:
SQL> CREATE OR REPLACE PACKAGE pkg_test
2 IS
3 FUNCTION f_test
4 RETURN VARCHAR2;
5
6 PROCEDURE p_test;
7 END;
8 /
Package created.
Package body:
SQL> CREATE OR REPLACE PACKAGE BODY pkg_test
2 IS
3 FUNCTION f_test
4 RETURN VARCHAR2
5 IS
6 l_cnt NUMBER;
7 retval VARCHAR2 (10);
8 BEGIN
9 SELECT COUNT (*)
10 INTO l_cnt
11 FROM flog
12 WHERE cuser = USER
13 AND sid = SYS_CONTEXT ('USERENV', 'SID');
14
15 retval := CASE WHEN l_cnt <= 2 THEN 'abc' ELSE 'abc' || 'de' END;
16 RETURN retval;
17 END;
18
19 PROCEDURE p_test
20 IS
21 BEGIN
22 FOR i IN 1 .. 3
23 LOOP
24 INSERT INTO flog (cuser, sid)
25 VALUES (USER, SYS_CONTEXT ('USERENV', 'SID'));
26
27 DBMS_OUTPUT.put_line ('Execution #' || i || ', result = ' || f_test);
28 END LOOP;
29 END;
30 END pkg_test;
31 /
Package body created.
Testing:
SQL> SET SERVEROUTPUT ON
SQL> EXEC pkg_test.p_test;
Execution #1, result = abc
Execution #2, result = abc
Execution #3, result = abcde
PL/SQL procedure successfully completed.
SQL>

PL/SQL Store return variable of a function in a Boolean variable

So I have a function that accepts a student id and checks to see if the user exists. I created the function without error and I'm trying to store the return variable in a Boolean like this and print the result
SQL> DECLARE
2 tf BOOLEAN;
3 BEGIN
4 EXECUTE tf := valid_stud(5)
5 DBMS_OUTPUT.PUT_LINE(tf);
6 END;
7 /
But this is getting me an error.
ERROR at line 4:
ORA-06550: line 4, column 9:
PLS-00103: Encountered the symbol "TF" when expecting one of the following:
:= . ( # % ; immediate
The symbol "." was substituted for "TF" to continue.
My function is this
CREATE OR REPLACE FUNCTION valid_stud(v_student_id NUMBER) RETURN BOOLEAN
IS
v_id NUMBER;
BEGIN
SELECT student_id
INTO v_id
FROM STUDENT
WHERE student_id = v_student_id;
IF SQL%FOUND THEN
RETURN TRUE;
END IF;
EXCEPTION
WHEN no_data_found THEN RETURN FALSE;
END valid_stud;
/
Here's a demonstration which shows how to do that.
Sample table:
SQL> create table student (
2 student_id number
3 );
Table created.
Function: I removed unnecessary check whether SELECT returned a value; if it did, fine. If not, it'll raise an exception.
SQL> create or replace function valid_stud (
2 v_student_id number
3 ) return boolean is
4 v_id number;
5 begin
6 select student_id into
7 v_id
8 from student
9 where student_id = v_student_id;
10
11 return true;
12 exception
13 when no_data_found then
14 return false;
15 end valid_stud;
16 /
Function created.
Testing:
SQL> set serveroutput on
SQL> declare
2 tf boolean;
3 begin
4 tf := valid_stud(5);
5 if tf then
6 dbms_output.put_line('Student exists');
7 else
8 dbms_output.put_line('Student does not exist');
9 end if;
10 end;
11 /
Student does not exist
PL/SQL procedure successfully completed.
SQL>

Resources