I have a Trigger and Function which sends mail with "updated" column(s),
when i am updating in my back-end (sql developer), i receive a mail with that particular column.
But when i do UPDATE directly through Apex Page i get mail listing all columns names indicating all are updated.
Function Code:
create or replace function SNAP_FUN(inTableName in varchar2) return varchar2 is
result varchar2(4000);
sep varchar2(2) := null;
begin
for c in (select column_name from user_tab_columns where table_name = inTableName) loop
if updating(c.column_name) then
result := result || sep || c.column_name;
sep := ', ';
end if;
end loop;
return result;
end;
/
Trigger
create or replace trigger SNAP_TRIG
after update on dw.W_SUPPL_SNAPSHOT_CONTROL_G
for each row
DECLARE X VARCHAR2(4000);
begin
begin
X:=X||('Updated:' || snap_fun('W_SUPPL_SNAPSHOT_CONTROL_G'));
end;
dlr_send_mail('***.com', 'SUPPLEMENTAL_SNAPSHOT', 'These are the column changes observed' || X
, '****', 'host')
end;
Related
I have error master table which contain description like 'Error in table abc in xyz column.' I need to format string for column name which is xyz here. Where ever I need to call this table I will pass column name and then I will get expected description.
Ex - Insert into errorTabl values(01,There is error in {0})
Whenever inside package I need to retrieve value of 01 then I will pass column name col1 so then expected value will be as below :
01 There is error in col1
Request you to please help me for insert and select both statements.
Though this doesn't make sense, maybe the code below could help you to start with something or to clarify your problem.
NOTE: the code below is here just to show you the basics - there is no sense in it for any kind of production. You are the one to adjust it to your context.
So, the package to put and get things into or from errors table:
CREATE OR REPLACE PACKAGE ERRS AS
Procedure putError(p_table IN VarChar2, p_column IN VarChar2);
Function getError(p_table VarChar2, p_column VarChar2) RETURN VarChar2;
END ERRS;
-- ---------------------------------------------------------------------------------
CREATE OR REPLACE PACKAGE BODY ERRS AS
Procedure putError(p_table IN VarChar2, p_column IN VarChar2) AS
BEGIN
Declare
mSql VarChar2(512) := '';
sq VarChar2(1) := '''';
Begin
mSql := 'Insert Into ERRORTABLE values( ' || sq || '01' || sq || ', ' || sq ||
'There is error in table ' || p_table || ' in ' || p_column || ' column' || sq || ')';
Execute Immediate mSql;
Commit;
End;
END putError;
-- -------------------------------------------------------------------------------
Function getError(p_table VarChar2, p_column VarChar2) RETURN VarChar2 IS
BEGIN
Declare
Cursor c IS
Select ERR_DESC From ERRORTABLE Where ERR_DESC Like('%table ' || p_table || ' in ' || p_column || '%');
mRet VarChar2(512) := '';
mDesc VarChar2(512) := '';
Begin
Open c;
LOOP
FETCH c into mDesc;
EXIT WHEN c%NOTFOUND;
mRet := '01 ' || mDesc || Chr(10);
END LOOP;
Close c;
RETURN RTRIM(mRet, Chr(10));
End;
END getError;
END ERRS;
Now the calling code to insert 5 records (once more - this is senseless) and to get you one of them...
set serveroutput on
DECLARE
errMsg VarChar2(512);
BEGIN
ERRS.putError('T_ABC', 'C_XYZ');
ERRS.putError('T_ABC', 'C_MNO');
ERRS.putError('T_ABC', 'C_PQR');
ERRS.putError('T_DEF', 'C_MNO');
ERRS.putError('T_DEF', 'C_XYZ');
--
errMsg := ERRS.getError('T_ABC', 'C_XYZ');
dbms_output.put_line(errMsg);
END;
/* R e s u l t :
anonymous block completed
01There is error in table T_ABC in C_XYZ column
*/
Just needed to pass double colon in insert query so then it will take single colon in table.
Ex - Insert into errorTabl values(01,There is error in ''{0}'')
In table it will be look like
**Id** **Description**
01 There is error in'{0}'.
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;
How to handle the case when select statement don't return any record in SYS_REFCURSOR ?
I am using dynamic sql generation process using bind variables.
create or replace
procedure test_dynamic_sql
(
last_name varchar2,
rc out sys_refcursor,
jobid varchar2,
sdate date,
edate date,
status out varchar2,
message out varchar2 )
is
q long;
lname varchar2(240);
begin
q := 'select employee_id
from employees e
where 1=1';
if last_name is not null then
q := q || 'and (e.LAST_NAME = :LAST_NAME)';
else
q := q || 'and (1=1 or :LAST_NAME is null)';
end if;
if jobid is not null then
q := q || 'and (e.JOB_ID = :JOBID)';
else
q := q || 'and (1=1 or :JOBID is null)';
end if;
if sdate is not null then
q := q || 'and (e.hire_date >= :sdate)';
else
q := q || 'and (1=1 or :sdate is null)';
end if;
if edate is not null then
q := q || 'and (e.hire_date <= :edate)';
else
q := q || 'and (1=1 or :edate is null)';
end if;
open rc for q using last_name, jobid, sdate, edate;
/*
IF rc%NOTFOUND THEN
STATUS := 'NR';
MESSAGE := 'Not Found';
ELSE
STATUS := 'S';
MESSAGE := 'Found';
END IF;
*/
exception
when others then
STATUS :='E';
message := sqlcode||'-->'||sqlerrm;
end;
I have tried %NOTFOUND and %FOUND attributes but its not working.
I have also tried NO_DATA_FOUND exception but its also not working.
I need to return status as 'S', 'E', 'NR'
S --> SUCCESS (when records found)
E --> ERROR (when any error occured)
NR--> NO RECORDS (when 0 records)
Thanks!
This answer is to address the issues you are having while working with Ref Cursors as Out Parameters. The below code calls your test_dynamic_sql() Procedure. Within this Proc we OPEN the cursor, FETCH the data it is pointing to and we DO NOT CLOSE the cursor as we are immediately using that Cursor again outside of the test_dynamic_sql() Procedure. One thing to NOTE - When FETCH is used that Cursor will no longer provide you with the data and must be opened again. Since your Cursor is utilizing Dynamic SQL we must Declare our Dynamic 'Query' in the same place we are declaring the rest of our Global Variables.
"Cursors are NOT designed to be re-used: you read them once, keep moving forward and as you're doing so you're discarding any previously scanned rows." This fact was stolen from this SO Post: Oracle. Reuse cursor as parameter in two procedures.
Outside of this procedure we first must check if the Cursor was successfully initialized by using an IF statement to check if the Cursor exists: IF (g_rc IS NOT NULL) THEN.
Full Code Sample below:
DECLARE
/* g for Global */
g_status VARCHAR2(5);
g_message VARCHAR2(100);
g_rc SYS_REFCURSOR;
/* Store Dynamic SQL Query */
g_SQL VARCHAR2(200);
/* Bind Variables */
g_jobid NUMBER;
g_last_name VARCHAR2(240);
/* Declare Global Record used to FETCH data into */
g_rec_employee employees%ROWTYPE;
PROCEDURE test_dynamic_sql(pv_last_name VARCHAR2,
p_rc OUT SYS_REFCURSOR,
pv_jobid VARCHAR2,
pv_status OUT VARCHAR2,
pv_message OUT VARCHAR2,
pv_q OUT VARCHAR2)
AS
/* Declare Record used to FETCH data into */
rec_employee employees%ROWTYPE;
/* Bind Variables */
jobid NUMBER := to_number(pv_jobid);
last_name VARCHAR2(240) := pv_last_name;
BEGIN
/* Reset/Initialize Cursor Output Variable */
p_rc := NULL;
/* Dynamic SQL statement with placeholder: */
pv_q := 'SELECT * FROM employees WHERE 1=1';
IF last_name IS NOT NULL
THEN pv_q := pv_q || ' AND (lastname = :LAST_NAME)';
ELSE pv_q := pv_q || ' AND (1=1 or :LAST_NAME is null)';
END IF;
IF jobid IS NOT NULL
THEN pv_q := pv_q || ' AND (ID = :JOBID)';
ELSE pv_q := pv_q || ' AND (1=1 or :JOBID is null)';
END IF;
/* Open cursor & specify bind argument in USING clause: */
OPEN p_rc FOR pv_q USING last_name, jobid;
LOOP
/* In order to work with any Data that a Cursor 'points' to we must FETCH the data. This allows us to use %ROWCOUNT and %NOTFOUND */
FETCH p_rc INTO rec_employee;
EXIT WHEN p_rc%NOTFOUND;
END LOOP;
IF p_rc%ROWCOUNT = 0 THEN
pv_status := 'NR';
pv_message := 'Not Found';
--EXIT;
ELSIF p_rc%ROWCOUNT = 1 THEN
pv_status := 'S';
pv_message := 'Found';
--EXIT;
ELSE
pv_status := 'MU';
pv_message := 'Multiple Records';
END IF;
--dbms_output.put_line('Final Count: ' || p_rc%ROWCOUNT);
/* Close Cursor - We don't close the Cursor here as we want to use this cursor as an OUT Parameter outside of this Proc */
CLOSE p_rc;
EXCEPTION
WHEN OTHERS THEN
pv_status :='E';
pv_message := sqlcode||'-->'||sqlerrm;
dbms_output.put_line('STATUS: ' || pv_status);
dbms_output.put_line('MESSAGE: ' || pv_message);
CLOSE p_rc;
END test_dynamic_sql;
BEGIN
g_jobid := null;
g_last_name := 'Loch';
test_dynamic_sql(pv_last_name => g_last_name,
p_rc => g_rc, /* Out Parameter */
pv_jobid => g_jobid,
pv_status => g_status, /* Out Parameter */
pv_message => g_message, /* Out Parameter */
pv_q => g_SQL /* Out Parameter */
);
/* Output OUT Variables aka Provide Output to User */
dbms_output.put_line('STATUS: ' || g_status);
dbms_output.put_line('MESSAGE: ' || g_message);
IF (g_rc IS NOT NULL) THEN
dbms_output.put_line('We have something here. Fetching Data Now:');
OPEN g_rc FOR g_sql USING g_last_name, g_jobid;
LOOP
FETCH g_rc INTO g_rec_employee;
EXIT WHEN g_rc%NOTFOUND;
/* Print the Job ID just to show it is working */
dbms_output.put_line('Job_ID: ' || g_rec_employee.id || ' is the id');
END LOOP;
dbms_output.put_line('Total of: '|| g_rc%ROWCOUNT || ' records Fetched.');
CLOSE g_rc;
ELSE
dbms_output.put_line('null');
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line('Error '||TO_CHAR(SQLCODE)||': '||SQLERRM);
CLOSE g_rc;
END;
The above works with the same Employees table data as in my first Answer to this SO Question.
There are a few things you are missing if you wish to work with a cursor in the manner you are attempting regardless of the implicit Ref Cursor due to the Dynamic SQL or an explicit Cursor.
In order to make use of %ROWCOUNT or %NOTFOUND you must first FETCH the Cursor. This Link "PL/SQL 101 : Understanding Ref Cursors" that provides a ton of information on this topic but all that is needed to help with answering your question is to know that you must FETCH the data first.
Below is an image showing the data in my Employees table. NOTE that there are two employees with the last name 'Loch'.
The below Code is all within it's own anonymous block but can easily be converted into a Procedure/Function. It has all of your required Status's and Messages. In order to handle searches that have more than one result I added an additional Status/Message to tell the user that Multiple Records were returned. Last, just to make it easier to work with your code I took out all but two of your Parameters. NOTE: If the Procedure's Parameters are all passed in as NULL the Dynamic SQL That is generated will query the entire table as it basically removes all of the Filters in the WHERE clause.
DECLARE
/* Parameters */
rc SYS_REFCURSOR;
q VARCHAR2(200);
status VARCHAR2(5);
message VARCHAR2(100);
/* Declare Record used to FETCH data into */
rec_employee employees%ROWTYPE;
/* Bind Variables */
jobid NUMBER := null;
last_name VARCHAR2(240) := 'Loch';
BEGIN
/* Dynamic SQL statement with placeholder: */
q := 'SELECT * FROM employees WHERE 1=1';
IF last_name IS NOT NULL
THEN q := q || ' AND (lastname = :LAST_NAME)';
ELSE q := q || ' AND (1=1 or :LAST_NAME is null)';
END IF;
IF jobid IS NOT NULL
THEN q := q || ' AND (ID = :JOBID)';
ELSE q := q || ' AND (1=1 or :JOBID is null)';
END IF;
/* Open cursor & specify bind argument in USING clause: */
OPEN rc FOR q USING last_name, jobid;
LOOP
/* In order to work with any Data that a Cursor 'points' to we must FETCH the data. This allows us to use %ROWCOUNT and %NOTFOUND */
FETCH rc INTO rec_employee;
EXIT WHEN rc%NOTFOUND;
END LOOP;
IF rc%ROWCOUNT = 0 THEN
STATUS := 'NR';
MESSAGE := 'Not Found';
--EXIT;
ELSIF rc%ROWCOUNT = 1 THEN
STATUS := 'S';
MESSAGE := 'Found';
--EXIT;
ELSE
STATUS := 'MU';
MESSAGE := 'Multiple Records';
END IF;
dbms_output.put_line('Final Count: ' || rc%ROWCOUNT);
/* Close Cursor */
CLOSE rc;
/* Return Variables or Provide Output to User */
dbms_output.put_line('STATUS: ' || STATUS);
dbms_output.put_line('MESSAGE: ' || MESSAGE);
EXCEPTION
WHEN OTHERS THEN
STATUS :='E';
message := sqlcode||'-->'||sqlerrm;
dbms_output.put_line('STATUS: ' || STATUS);
dbms_output.put_line('MESSAGE: ' || MESSAGE);
END;
The requirement is to check data consistency of a view. It's a bit complicated, so let's move step by step.
A table check_data_column has basically 5 imp. columns: ViewName, ColumnName, Mandatory, MaxLength, DataType.
It will contain Information about each field of a particular view. For example:
ViewName: Employee_V
ColumnName: EmployeeNo
Mandatory: 1 (True)
MaxLength: 10
DataType: Number
ViewName: Employee_V
ColumnName: EmployeeName
Mandatory: 1 (True)
MaxLength: 20
DataType: String
Now I have to write a function which takes all the entries from this check_data_column and check the data in the appropriate view for each mentioned column.
From the above example, it will check the data in the Employee_V.
Each entry in EmployeNo column should not be null, max length should be 10 and it should be a numeric value.
Similarly, each entry in EmployeeName column should not be null, max length should be 20 and it should be a string.
Number of views is unknown and no. of columns in each view is unknown.
To solve the above problem, I wrote the following code:
FUNCTION CheckData(viewname VARCHAR2)
RETURN VARCHAR2
Is
return_v VARCHAR2(1000);
query_v VARCHAR2(200);
column_c SYS_REFCURSOR;
column_v column_c%ROWTYPE;
CURSOR ddc_c IS
SELECT *
FROM check_data_column;
BEGIN
return_v := null;
FOR ddc_v IN ddc_c LOOP
query_v := 'SELECT' || ddc_v.column_name || 'FROM anc_sap.' || ddc_v.viewname;
OPEN column_c FOR query_v;
LOOP
FETCH column_c INTO column_v;
EXIT WHEN column_c%NOTFOUND;
IF LENGTH(column_v) > ddc_v.max_length THEN
return_v := 'Max. length exceeded';
END IF;
----Other validations (on mandatory and data type)
END LOOP;
CLOSE column_c;
END LOOP;
RETURN return_v;
END CheckData;
Problem:
The problem I am facing here is in declaring column_v variable for sys_refcursor column_c. Since at this point of time I am not able to think replacement for sys_refcursor, is there anything else I can do?
This function worked in simple tests. It checks nulls and length, you have to add rest of validations.
create or replace function CheckData(i_viewname VARCHAR2)
RETURN VARCHAR2
Is
query_v VARCHAR2(2000);
v_cnt number := 0;
CURSOR ddc_c IS
SELECT * FROM check_data_column where viewname = i_viewname;
BEGIN
FOR ddc_v IN ddc_c LOOP
-- check nulls
if ddc_v.mandatory = 1 then
query_v := 'select count(1) from '|| ddc_v.viewname
||' where '||ddc_v.columnname||' is null';
execute immediate query_v into v_cnt;
if v_cnt > 0 then
return 'null values for mandatory column '
||ddc_v.viewname ||'.'||ddc_v.columnname||' exists';
end if;
end if;
-- check column length
query_v := 'select count(1) from '|| ddc_v.viewname
||' where length('||ddc_v.columnname||') > '||ddc_v.maxlength;
execute immediate query_v into v_cnt;
if v_cnt > 0 then
return 'max length in column '||ddc_v.viewname
||'.'||ddc_v.columnname||' exceeded';
end if;
-- other validations
END LOOP;
RETURN 'OK';
END CheckData;
Here is a scenario.
I have around 300 tables in my database and I want to merge another database in my database. Both the databases have same tables but the datatype and no of columns vary.
Now how to convert data from other database to my database ?
eg.
db1: Table T1(col1 int,col2 char,......,col31 int)
db2: Table T1(col1 int,col2 char,......,col31 int,col32 char,col33 char )
Since datatype and no of column vary,I cant use
"insert into db1.tbl
select * from db2.tbl ".
I dont want to create script for each and every table . Help me out !!!
every morning I copy a large amount of tables from the production database into my datawarehouse. This is my "check & fix" procedure I run before each truncate + insert.
procedure check_and_fix_table(p_naam in varchar2)
/**
* check if columns have changed on PROD and create and execute the matching ALTER TABLE statement
*/
is
v_coltype varchar2(100);
v_sql varchar2(200);
function check_column(p_column in varchar2)
return boolean
is
v_dummy number;
begin
select 1 into v_dummy
from user_tab_cols tc
where tc.table_name = upper(p_naam)
and tc.column_name = p_column;
return true;
exception
when no_data_found then return false;
end;
begin
-- loop through all columns that are altered (if nothing altered, then nothing will happen
for i in (select tc.column_name
, tc.data_type
, tc.data_length
, tc.data_precision
from user_tab_cols#DB_LINK_TO_PRODUCTION tc
where tc.table_name = upper(p_naam)
and tc.column_name not like 'SYS_NC%' -- These columns are created by oracle for function based indexes
minus
select tc.column_name
, tc.data_type
, tc.data_length
, tc.data_precision
from user_tab_cols tc
where tc.table_name = upper(p_naam))
loop
-- create column type
if i.data_type in ('CHAR','VARCHAR2') then
v_coltype := i.data_type||'('||i.data_length||')';
elsif i.data_type = 'NUMBER' then
if i.data_precision is not null then
v_coltype := i.data_type||'('||i.data_precision||')';
else
v_coltype := i.data_type;
end if;
else -- DATE, CLOB, BLOB, etc
v_coltype := i.data_type;
end if;
-- check if the column is altered or added
if check_column(i.column_name) then
-- execute the ALTER TABLE to fix the column
v_sql := 'alter table '||p_naam||' modify '||i.column_name||' '||v_coltype;
else
-- add new column
v_sql := 'alter table '||p_naam||' add '||i.column_name||' '||v_coltype;
end if;
execute immediate v_sql;
-- logging change
prc_log(c_procedureid, 1, p_naam||' changed. Fixed by executing: '||v_sql);
end loop;
exception
when others then
prc_log(c_procedureid, 3, 'Error at copy_package.check_and_fix_table - '||substr(sqlerrm, 0, 1900));
end;
Then in my main procedure I use it like this (where p_naam is the tablename passed as parameter to the procedure):
check_and_fix_table(p_naam);
-- full copy of table from PROD
execute immediate 'truncate table ' || p_naam;
execute immediate 'insert /*+append*/ into ' || p_naam || ' select * from ' || p_naam || '#DB_LINK_TO_PRODUCTION';
Hope this helps :)