Oracle Stored Procedure compilation error - oracle

I'm new to PL/SQL. Can anyone please help fix my compilation error? Your help is much appreciated. Also, after I would like to call this procedure to check and add a new user.
create or replace procedure CheckAddUser ( userid in varchar2(20))
as
declare vartmp number;
begin
SELECT nvl((SELECT distinct 1 FROM crm_admin.LTY_USER_STORE WHERE usr_nm = userid ), 0) INTO :varTmp FROM dual;
IF (:varTmp = 0) THEN
dbms_output.put_line('the user ' || ':userid' || ' does not exist');
elsif (:varTmp = 1) THEN
dbms_output.put_line('the user ' || ':userid' || ' already exist');
End if;
end;

Try this:
create or replace procedure checkadduser(userid in varchar2)
as
vartmp number;
begin
select coalesce(max(1), 0) into vartmp
from dual
where exists (
select 1
from crm_admin.lty_user_store
where usr_nm = userid
);
if vartmp = 0 then
dbms_output.put_line('the user ' || userid || ' does not exist');
elsif vartmp = 1 then
dbms_output.put_line('the user ' || userid || ' already exist');
end if;
end;
/
Changes made:
Removed the size from parameter
Removed the declare keyword - not part of the procedure syntax
Modified the query to stop searching as soon as a row is found and return 1 otherwise 0.
select coalesce(max(1), 0) into varTmp
from dual
where exists (
select 1
from crm_admin.lty_user_store
where usr_nm = userid
);
If the usr_nm is unique in your table, this will work well too (this can be used even if it's not unique but can be bit less performant if number of rows per usr_nm can be arbitrarily large):
select coalesce(max(1), 0)
into varTmp
from crm_admin.lty_user_store
where usr_nm = userid
Do not use : with the variables and parameters.

Don't use ":" with var.
I did some changes, which I would migth use:
--I recommended to change procedure to function, then you can use it in SQL
create or replace
procedure CheckAddUser ( userid in varchar2)
as
--Best practics, use self-describing variables
isuserexist number(1,0); -- vartmp
message_suff varchar2(30):=' does not exist';
begin
--Best practics, first check the parameters
if trim(userid) is null then
raise_application_error(-20000, 'Param userid is empty');
end if;
select count(*) into isuserexist
from crm_admin.lty_user_store
where usr_nm = userid;
--only one if, reads easier
if isUserExist > 0 then
message_suff:= ' already exist';
end if;
dbms_output.put_line('the user ' || ':userid' || message_suff);
end;

Related

Procedure Error: ORA-24344: success with compilation error

The procedure takes two dates and find the reports that issued during this duration, and update total salary, and print them.
CREATE OR REPLACE PROCEDURE Salary_Update(p_Date1 DATE, p_Date2 DATE) AS
CURSOR MYCR IS
SELECT ReportID, TotalSale, Rate, TotalSalary, ReportDate
FROM WEEKLY_REPORT
WHERE ReportDate BETWEEN TO_DATE(p_Date1, 'DD-MM-YYYY') AND TO_DATE(p_Date2, 'DD-MM-YYYY');
BEGIN
FOR MYPOINTER IN MYCR LOOP
UPDATE WEEKLY_REPORT SET TotalSalary = ((TotalSale/100)*Rate);
DBMS_OUTPUT.PUT_LINE('The total salary for report ' || MYPOINTER.REPORTID || ' updated to ' || MYPOINTER.TotalSalary || 'dollars, which is ' || MYPOINTER.Rate || '% of the total sale of ' || MYPOINTER.TotalSale || 'dollars.');
WHERE ReportID = MYPOINTER.ReportID;
END LOOP;
END Salary_Update;
/
the execution
BEGIN Salary_Update('02-04-2020','05-04-2020');
END;
BEGIN
Salary_Update(to_date('02-04-2020','dd-mm-yyyy'), to_date('05-04-2020','dd-mm-yyyy'));
END;
both don't work.
There are a number of syntax and logic errors. You haven't specified exactly what you want the code to do or provided a reproducible test case but my guess is that you want something like
CREATE OR REPLACE PROCEDURE Salary_Update(
p_Date1 DATE,
p_Date2 DATE)
AS
CURSOR MYCR IS
SELECT ReportID, TotalSale, Rate, TotalSalary, ReportDate
FROM WEEKLY_REPORT
WHERE ReportDate BETWEEN p_date1 AND p_date2;
BEGIN
FOR MYPOINTER IN MYCR
LOOP
UPDATE WEEKLY_REPORT
SET TotalSalary = ((TotalSale/100)*Rate)
WHERE ReportID = MYPOINTER.ReportID;
DBMS_OUTPUT.PUT_LINE('The total salary for report ' || MYPOINTER.REPORTID || ' updated to ' || MYPOINTER.TotalSalary || 'dollars, which is ' || MYPOINTER.Rate || '% of the total sale of ' || MYPOINTER.TotalSale || 'dollars.');
END LOOP;
END Salary_Update;
/
The string you're outputting doesn't seem to make sense-- MYPOINTER.TotalSalary is the value from the cursor which will be the value from before the update. If it is important that you print out the value you updated TotalSalary to, you'd probably want something like
CREATE OR REPLACE PROCEDURE Salary_Update(
p_Date1 DATE,
p_Date2 DATE)
AS
CURSOR MYCR IS
SELECT ReportID, TotalSale, Rate, TotalSalary, ReportDate
FROM WEEKLY_REPORT
WHERE ReportDate BETWEEN p_date1 AND p_date2;
l_newSalary weekly_report.totalSalary%type;
BEGIN
FOR MYPOINTER IN MYCR
LOOP
l_newSalary := (mypointer.TotalSale/100) * mypointer.rate;
UPDATE WEEKLY_REPORT
SET TotalSalary = l_newSalary
WHERE ReportID = MYPOINTER.ReportID;
DBMS_OUTPUT.PUT_LINE('The total salary for report ' || MYPOINTER.REPORTID || ' updated to ' || l_newSalary || 'dollars, which is ' || MYPOINTER.Rate || '% of the total sale of ' || MYPOINTER.TotalSale || 'dollars.');
END LOOP;
END Salary_Update;
/
If the error that you're getting is an ORA-00942 error that weekly_report doesn't exist, then there is no such table in the current schema. Assuming that the query works when run interactively, potentially the table exists in a different schema, there is a local synonym in the current schema for that table, and the owner of the procedure only has access to the table granted via a role. In that case, you'd need your DBA to grant access to the table directly to the owner of the procedure.

Pass a table name and time stamp variable to a PL/SQL

I am writing a below PL/SQL code in SQL developer to delete data from a table with a timestamp column in the where condition. How can I modify this code to pass the table name and the timestamp value to values that I want based on what table and time records I want to delete the data from and create a stored procedure that can be reused.
DBMS_OUTPUT.ENABLE;
DECLARE
counter INTEGER := 0;
stop INTEGER;
BEGIN
dbms_output.put_line('START');
LOOP
counter := counter + 1;
DELETE my_schema.test
WHERE t = '10-JUN-20 04.33.46.000000000 AM'
AND ROWNUM <= 100000;
SELECT COUNT(*)
INTO stop
FROM my_schema.test
WHERE t = '10-JUN-20 04.33.46.000000000 AM';
EXIT WHEN stop <= 0;
COMMIT;
END LOOP;
dbms_output.put_line('Counter: ' || counter);
dbms_output.put_line('Left: ' || stop);
COMMIT;
END;
Adapting your anonymous to a stored procedure will, as indicated, require converting it to dynamic SQL. Always more difficult. And subject to SQL injection. For this you should validate string replacement parameters. I have a couple other changes:
Pass the desired as a timestamp, not a string, this allows/forces the
calling routine to determine the format and necessary conversion, if
any.
Added a parameter for column name as well. This frees naming columns
from the requirement of the procedure.
There is no need to count remaining items. Your loop processes until
that value reaches 0, but this can be determined by the number of
rows deleted on the last pass. Delete sets sql%rowcount to the number
of rows deleted. When the pass deletes 0 rows the process is
complete.
Removed the results display and the commit from the procedure, again
offloading this to the caller.
create or replace
procedure delete_values_by_timestamp
( p_table_name in varchar2
, p_column_name in varchar2
, p_timestamp in timestamp
, p_result_msg out varchar2
)
IS
table_name_parameter_invalid exception;
pragma exception_init(table_name_parameter_invalid, -44002);
column_name_parameter_invalid exception;
pragma exception_init(column_name_parameter_invalid, -44003);
k_nl constant varchar2(1) := chr(10);
k_max_delete_per_interation constant integer := 100000;
k_base_delete varchar2(256) :=
'delete from <table_name>' ||
' where <column_name> <= :1' ||
' and rownum <= :2';
v_delete_sql varchar2 (256) ;
v_rows_deleted integer := 0;
begin
v_delete_sql := replace(replace(k_base_delete,'<table_name>', dbms_assert.sql_object_name(p_table_name))
,'<column_name>',dbms_assert.simple_sql_name(p_column_name));
dbms_output.put_line('Running SQL:' || k_nl || v_delete_sql);
loop
execute immediate v_delete_sql using p_timestamp, k_max_delete_per_interation;
exit when sql%rowcount = 0;
v_rows_deleted :=v_rows_deleted + sql%rowcount;
end loop;
if v_rows_deleted = 0
then
p_result_msg := 'No Data Found';
else
p_result_msg := 'Number of Rows Deleted ' || to_char(v_rows_deleted);
end if;
exception
when table_name_parameter_invalid then
raise_application_error(-20199,'Invalid Table Name (' || p_table_name || ') specified.');
when column_name_parameter_invalid then
raise_application_error(-20198,'Invalid Column Name (' || p_column_name || ') specified.');
end delete_values_by_timestamp;
See example: In the example I reduce the number of rows deleted on each iteration from 100000 to 20. An additionally enhancement would be to pass the number of rows for each iteration as a parameter.
I couldn't test it but you could create a function whcih takes the table name and the timestamp as parameter.
As long you want to delete every record with the given timestamp you don't need to loop for each record.
This function should be just an example.
FUNCTION delete_values_by_timestamp (p_table_name IN VARCHAR2 DEFAULT NULL,
p_timestamp IN VARCHAR2 DEFAULT NULL)
RETURN VARCHAR2
IS
v_count NUMBER := 0;
v_query VARCHAR2 (500) := '';
BEGIN
IF p_table_name IS NOT NULL
THEN
IF p_timestamp IS NOT NULL
THEN
v_query := 'SELECT COUNT(*)
FROM my_schema.' || p_table_name | '
WHERE t = TO_DATE(''' || p_timestamp ||''', ''DD.MM.YYYY HH24:MI:SS.SSSS'')';
EXECUTE IMMEDIATE v_query INTO v_count;
IF v_count > 0
THEN
v_query := 'DELETE FROM my_schema.' || p_table_name || '
WHERE t = TO_DATE(''' || p_timestamp ||''', ''DD.MM.YYYY HH24:MI:SS.SSSS'')';
EXECUTE IMMEDIATE v_query;
ELSE
RETURN 'NO RECORDS FOUND!';
END IF;
ELSE
RETURN 'TIMESTAMP EMPTY!';
END IF;
ELSE
RETURN 'TABLE NAME EMPTY!';
END IF;
END;

"No Data found" error when compiling PLSQL Function

When trying to compile in order to execute both functions(#directory) I keep getting a no data error on line 48. (or line 13 for the function). This is the error i receive. NOTE: SYSTEM is the server I'm connected to.
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at "SYSTEM.DEPTPROJECT", line 13
ORA-06512: at line 4
ORA-06512: at line 4
these are my function
SET ECHO ON;
SET FEEDBACK ON;
SET LINESIZE 100;
SET PAGESIZE 100;
SET SERVEROUTPUT ON;
CREATE OR REPLACE FUNCTION DEPTPROJECT(departmentNumber IN NUMBER)
RETURN VARCHAR IS
dep# DEPARTMENT.D#%TYPE;
depName DEPARTMENT.DName%TYPE;
counter NUMBER(10,0);
empNumber CHAR(5);
empName VARCHAR2(30);
result VARCHAR2(600);
BEGIN
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = dep#;
result := result || 'Department'|| dep# || '' || depName || chr (10);
FOR i IN(SELECT P# , PTitle , Budget FROM PROJECT WHERE PROJECT.D# = dep# ORDER BY BUDGET DESC)
LOOP
result:= result || chr(9)|| 'Project: ' || i.P# || '' || i.PTitle || i.Budget || chr(10);
FOR j IN(SELECT EMPLOYEE.Name, EMPLOYEE.E# FROM WORKSON INNER JOIN EMPLOYEE ON EMPLOYEE.E# = WORKSON.E# WHERE WORKSON.P# = i.P# ORDER BY EMPLOYEE.NAME ASC )
LOOP
result:= result || chr(10) || j.E# || '' || j.Name || chr(10);
END LOOP;
END LOOP;
RETURN result;
END;
/
BEGIN
FOR x IN(SELECT D# FROM DEPARTMENT)
LOOP
DBMS_OUTPUT.PUT_LINE(DEPTPROJECT(x.D#));
END LOOP;
END;
/
When you are selecting INTO a variable and there are no records returned you should get a NO DATA FOUND error. I believe the correct way to write the above code would be to wrap the SELECT statement with it's own BEGIN/EXCEPTION/END block.
Example:
SET ECHO ON;
SET FEEDBACK ON;
SET LINESIZE 100;
SET PAGESIZE 100;
SET SERVEROUTPUT ON;
CREATE OR REPLACE FUNCTION DEPTPROJECT(departmentNumber IN NUMBER)
RETURN VARCHAR IS
dep# DEPARTMENT.D#%TYPE;
depName DEPARTMENT.DName%TYPE;
counter NUMBER(10,0);
empNumber CHAR(5);
empName VARCHAR2(30);
result VARCHAR2(600);
BEGIN
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = departmentNumber;
result := result || 'Department'|| dep# || '' || depName || chr (10);
FOR i IN(SELECT P# , PTitle , Budget FROM PROJECT WHERE PROJECT.D# = dep# ORDER BY BUDGET DESC)
LOOP
result:= result || chr(9)|| 'Project: ' || i.P# || '' || i.PTitle || i.Budget || chr(10);
FOR j IN(SELECT EMPLOYEE.Name, EMPLOYEE.E# FROM WORKSON INNER JOIN EMPLOYEE ON EMPLOYEE.E# = WORKSON.E# WHERE WORKSON.P# = i.P# ORDER BY EMPLOYEE.NAME ASC )
LOOP
result:= result || chr(10) || j.E# || '' || j.Name || chr(10);
END LOOP;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
result := 'Record Not Found';
RETURN result;
END;
/
BEGIN
FOR x IN(SELECT D# FROM DEPARTMENT)
LOOP
DBMS_OUTPUT.PUT_LINE(DEPTPROJECT(x.D#));
END LOOP;
END;
/
I'd guess that line 13 should use the variable being passed to the function:
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = dep#;
Should be:
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = departmentNumber;
You are using following query to fetch dep# and depName but your where clause is WHERE DEPARTMENT.D# = dep# .
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = dep#;
Here dep# is a variable which you have declared but not initialized.
So dep# is null and comparision to NULL will always lead to false which means your query is returning no record.
As you have used INTO in your query, Oracle is seeking for exactly one record from this query but it is returning no records. Hence, you are facing the issue.
According to your logic either change the WHERE clause to include departmentNumber in comparision or assign proper value to dep# before using it in your query.
Also, make sure to wrap your SELECT .. INTO query in BEGIN..EXCEPTION..END to avoid such a dynamic exception.
Cheers!!

Write a database function that should display {1} if object exists {0} if object does not exist in the database

Help me finish this function, please. If you could proof read and correct my mistake I could really appreciate it.
a. The function takes two INPUT parameters {object_name, object_type} and return an INT.
Object Names and Object Types are related as follows.
b. {object_name} can be any database object like TABLES, SEQUENCES, SYNONYMS, VIEWS.
c. {object_type} can be {T, SEQ, SYN, V}. Each object type corresponds to its object names.
T=>TABLES, SYN=>SYNONYMS, SEQ=>SEQUENCES, V=>VIEWS.
For example if I pass the object_name as ‘EMPLOYEES’, object_type as ‘T’ then it should check if this object in the database and then return either {1} or {0}.
create or replace function OBJECT_CHECK (object_name varchar,
object_type varchar,
)
return int
AS
BEGIN
DECLARE
v_Number NUMBER;
V_NUMBER1 NUMBER;
v_str VARCHAR2(100);
OBJECTS_NAME VARCHAR2(100):='&object';
v_tab VARCHAR2(100);
BEGIN
SELECT COUNT(* ) --for tables checking
INTO v_Number
FROM User_Tables
WHERE Table_Name = UPPER(OBJECTS_NAME);
v_str :='TABLE_NAME';
IF V_NUMBER =0 THEN -- for synonyms checking
SELECT COUNT(* )
INTO v_Number
FROM user_synonyms
WHERE synonym_Name = UPPER(OBJECTS_NAME);
v_str :='SYNONYM';
END IF;
--dbms_output.put_line(v_number);
v_str:='INDEX';
END IF;
IF V_NUMBER = 0 THEN -- for COLUMN checking
BEGIN
FOR i IN
(SELECT table_name FROM all_tab_cols WHERE column_name =UPPER(OBJECTS_NAME)
)
LOOP
dbms_output.put_line(UPPER(OBJECTS_NAME)|| ' Coulmn available in ' ||
i.table_name || ' table ');
END LOOP;
v_str:='colum';
END;
END IF;
IF V_NUMBER = 0 THEN
SELECT count(*)
into v_number FROM all_tab_cols WHERE column_name =UPPER(OBJECTS_NAME);
end if;
IF v_Number >= 1 AND v_str='TABLE_NAME' THEN
dbms_Output.Put_Line(UPPER(OBJECTS_NAME) ||'-----> TABLE IS AVAILABLE IN THE
SCHEMA ' );
ELSE
dbms_Output.Put_Line(UPPER(OBJECTS_NAME) ||'-----> NO SUCH TABLE AVAILABLE IN
THE SCHEMA ' );
END IF;
IF v_Number >= 1 AND v_str='SYNONYM' THEN
dbms_Output.Put_Line(UPPER(OBJECTS_NAME) ||'-----> SYNONYM IS AVAILABLE IN THE
SCHEMA ' );
ELSE
dbms_Output.Put_Line(UPPER(OBJECTS_NAME) ||'-----> NO SUCH SYNONYM AVAILABLE
IN THE SCHEMA ' );
END IF;
IF v_Number >= 1 AND v_str='INDEX' THEN
dbms_Output.Put_Line(UPPER(OBJECTS_NAME) ||'-----> INDEX IS AVAILABLE IN THE
SCHEMA ' );
ELSE
dbms_Output.Put_Line(UPPER(OBJECTS_NAME) ||'-----> NO SUCH INDEX AVAILABLE IN
THE SCHEMA ' );
END IF;
IF v_Number = 0 or V_STR <>'colum' THEN
dbms_Output.Put_Line(UPPER(OBJECTS_NAME) ||'-----> NO SUCH COLUMN AVAILABLE IN
THE SCHEMA ' );
END IF;
END;
END;
Not sure if this is the problem you're referring to, but you've got some syntax errors. You should have received error messages pointing you to these. However...
You have a comma here...remove it
create or replace function OBJECT_CHECK (object_name varchar,
object_type varchar, <--HERE
)
return int
And you have an extra end here as well
END;
END;

Dynamically assigning variables oracle sql

I have a table attribute_config with below columns:
table_name column_name key
Let us say is has below 2 rows
account accountphone accountnum
customer customernumber customerid
Key can be only accountnum or customerid.
I have to write code which will accept (i_accountnum,i_customerid) and;
fetch the respective values from columns mentioned in column_name in tables mentioned in table_name using the key in where condition.
For ex: select accountphone from account where accountnum = i_accountnum
select customernumber from customer where customerid = i_customerid
the complete query should be formed dynamically, whether to pass i_accountnum or i_customerid in the query also needs to be decided dynamically. if key - accountnum, i_accountnum will be passed to where condition.
I have been trying on these lines so far, this is not working, i know it is wrong.
declare
v_accountnum varchar2(20);
v_customerid varchar2(20);
v_attribute_value varchar2(20);
v_stmt varchar2(255);
begin
Account_Num := 'TestCustomer'; -- input to the function
v_customer_ref := 'TestAccount'; -- input to the function
for i in (Select * from attribute_config) loop
v_stmt := 'select ' || i.column_name || ' from ' || i.table_name ||' where ' || i.key|| ' = v_' || i.key;
execute immediate v_Stmt into v_attribute_value;
end loop;
end;
This will fix your code, but I do not see any advantage of using dynamic query when your code should accept 2 parameters(i_accountnum,i_customerid) - which is already static situation and fetch the relevant values, perhaps only in learning purposes.
declare
procedure fecth_values(i_accountnum account.accountnum%type,
i_customerid customer.customerid%type) return varchar2 is
v_attribute_value varchar2(20);
begin
for i in (select * from attribute_config) loop
execute immediate 'select ' || i.column_name || ' from ' ||
i.table_name || ' where ' || i.key || ' = ' || case when i.key = 'accountnum' then i_accountnum when i.key = 'customerid' then i_customerid end;
into v_attribute_value;
dbms_output.put_line(v_attribute_value);
end loop;
return null;
end;
begin
fecth_values(1, 1);
end;
Your where clause was wrong the i.key should be compared against the inputed values, not the 'v_' || i.key, which is undeclared when you execute your stmt.

Resources