When I send mail with attachment through procedure using clob to create data.
For small data it's working fine. But for large data it's misbehaving (alignment changing). can you help whether anything needs to done with the code.
create or replace PROCEDURE RPT AS
l_clob clob;
l_bfile bfile;
l_fhandle utl_file.file_type;
l_buffer VARCHAR2(8192);
v_count number;
a_count number;
k_count number;
ka_count number;
currentdate DATE;
non_work_days_count number;
BEGIN
--preparing header
dbms_lob.createtemporary (l_clob, TRUE);
l_clob := l_clob
|| 'Column1'|| ','
|| 'Column2' || ','
|| 'Column3' || ','
|| 'Column4' || ','
|| UTL_TCP.crlf;
for crq in (select col1,col2,col3,col4 from table where id=1 ) loop
/* Prepare Details data using Clob */
l_clob := l_clob
|| to_clob(crq.COl1)|| ','
|| to_clob(crq.COL2) || ','
|| to_clob(crq.COL3) || ','
|| to_clob(crq.COL4) || ','
|| UTL_TCP.crlf;
end loop;
for crq in (select col1,col2,col3,col4 from table where id=2 ) loop
/* Prepare Details data using Clob */
l_clob := l_clob
|| to_clob(crq.COl1)|| ','
|| to_clob(crq.COL2) || ','
|| to_clob(crq.COL3) || ','
|| to_clob(crq.COL4) || ','
|| UTL_TCP.crlf;
end loop;
dbms_output.put_line('Sending mail with attachment ');
ATTACHMENT_SEND(p_to=> 'req#Email.com',
p_from=> 'req#Email.com',
p_subject=> ' Report ',
p_text_msg=>'Hi All',
p_attach_name =>'report_'||sysdate||'.csv',
p_attach_mime =>'text/plain',
p_attach_clob =>l_clob,
p_smtp_host=>'host.com');
dbms_lob.freetemporary(l_clob);
END RPT;
Also I observe when character length reach 32000 it's breaking(leaving remaining data).
The data in the created excel attachment is having alignment issue
After searching a lot, I found a different approach which worked as a gem for me(which can handle lakhs of records). I thought it would help someone someday.
Steps:
1)Created a directory (in which the expected excel is stored).
2)Write the output of the select statement into the above file.
3)Pick the file at above location and send it in the mail attachment.
Note: if any one needs SMTP code part or any assistance let me know
|| concatenation limits you up to 4000 in Oracle SQL while limits to 32000 in PL/SQL. You may try [DBMS_LOB.APPEND][1] procedure to concatenate long CLOBs. So you may try to convert your code to -
CREATE OR REPLACE PROCEDURE RPT AS
l_clob clob;
l_bfile bfile;
l_fhandle utl_file.file_type;
l_buffer VARCHAR2(8192);
v_count number;
a_count number;
k_count number;
ka_count number;
currentdate DATE;
non_work_days_count number;
BEGIN
--preparing header
dbms_lob.createtemporary (l_clob, TRUE);
l_clob := l_clob
|| 'Column1'|| ','
|| 'Column2' || ','
|| 'Column3' || ','
|| 'Column4' || ','
|| UTL_TCP.crlf;
for crq in (select col1,col2,col3,col4 from table where id=1 ) loop
/* Prepare Details data using Clob */
l_clob := DBMS_LOB.APPEND(
DBMS_LOB.APPEND(
DBMS_LOB.APPEND(
DBMS_LOB.APPEND(l_clob
,to_clob(crq.COl1) || ',')
,to_clob(crq.COL2) || ',')
,to_clob(crq.COL3) || ',')
,to_clob(crq.COL4) || ',' || UTL_TCP.crlf);
end loop;
for crq in (select col1,col2,col3,col4 from table where id=2 ) loop
/* Prepare Details data using Clob */
l_clob := DBMS_LOB.APPEND(
DBMS_LOB.APPEND(
DBMS_LOB.APPEND(
DBMS_LOB.APPEND(l_clob
,to_clob(crq.COl1) || ',')
,to_clob(crq.COL2) || ',')
,to_clob(crq.COL3) || ',')
,to_clob(crq.COL4) || ',' || UTL_TCP.crlf);
end loop;
dbms_output.put_line('Sending mail with attachment ');
ATTACHMENT_SEND(p_to => 'req#Email.com',
p_from => 'req#Email.com',
p_subject => ' Report ',
p_text_msg =>'Hi All',
p_attach_name =>'report_'||sysdate||'.csv',
p_attach_mime =>'text/plain',
p_attach_clob =>l_clob,
p_smtp_host =>'host.com');
dbms_lob.freetemporary(l_clob);
END RPT;
[1]: https://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_lob.htm#i997432
Related
The below code is used to create the stored procedure and this is how the stored procedure is called. Stored procedure is throwing ORA-20000: ORA-00913: too many values
BEGIN EDW_ODS_DELETE_RECORDS_PKG.MAIN('EDWFIN', 'PSP_LABOR_ADJUSTMENTS_F'); END;
create or replace
PACKAGE BODY "EDW_ODS_DELETE_RECORDS_PKG" AS
CON_EDW_IUD_FLAG CONSTANT CHAR := 'D';
CON_CURRENT_FLAG CONSTANT CHAR := 'N';
CON_DELETED_FLAG CONSTANT CHAR := 'Y';
PROCEDURE main (table_schema_in IN VARCHAR2, target_table_alias_in IN VARCHAR2) AS
v_source_schema VARCHAR2(30);
v_source_table_name VARCHAR2(30);
v_target_schema VARCHAR2(30);
v_target_table_name VARCHAR2(30);
v_source_table_key VARCHAR2(1000);
v_target_table_key VARCHAR2(1000);
v_table_type VARCHAR2(20);
v_last_deleted_date DATE;
v_delete_control_id NUMBER := 0;
v_target_table_alias VARCHAR2(30);
v_arc_target_table_name VARCHAR2(30);
BEGIN
SELECT SOURCE_TABLE_SCHEMA, SOURCE_TABLE_NAME, SOURCE_TABLE_KEY,
TARGET_TABLE_SCHEMA, TARGET_TABLE_NAME, TARGET_TABLE_KEY,
TABLE_TYPE, LAST_DELETED_DATE, DELETE_CONTROL_ID,
TARGET_TABLE_ALIAS,
ARC_TARGET_TABLE_NAME
INTO
v_source_schema, v_source_table_name, v_source_table_key,
v_target_schema, v_target_table_name, v_target_table_key,
v_table_type, v_last_deleted_date, v_delete_control_id,
v_target_table_alias,
v_arc_target_table_name
FROM EDW_ODS_DWH_DELETES_CONTROL
WHERE target_table_schema = table_schema_in AND target_table_alias = target_table_alias_in;
DBMS_OUTPUT.PUT_LINE ('Values : ' || v_last_deleted_date);
v_source_table_key := REPLACE(v_source_table_key, '~', ' || ''~'' || ');
v_target_table_key := REPLACE(v_target_table_key, '~', ' || ''~'' || ');
IF v_table_type = 'FACT' THEN
UPDATE_FACT_TABLES (v_source_schema, v_source_table_name, v_source_table_key,
v_target_schema, v_target_table_name, v_target_table_key,
v_last_deleted_date, v_delete_control_id,v_arc_target_table_name);
ELSE
UPDATE_DIMENSION_TABLES (v_source_schema, v_source_table_name, v_source_table_key,
v_target_schema, v_target_table_name, v_target_table_key,
v_last_deleted_date, v_delete_control_id, v_table_type);
END IF;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
ERROR_LOG(v_delete_control_id, table_schema_in, target_table_alias_in,
SQLERRM, DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
RAISE;
END main;
PROCEDURE UPDATE_FACT_TABLES (source_schema_in IN VARCHAR2, source_table_name_in IN VARCHAR2, source_table_key_in IN VARCHAR2,
target_schema_in IN VARCHAR2, target_table_name_in IN VARCHAR2, target_table_key_in IN VARCHAR2,
last_deleted_date_in IN DATE, delete_control_id_in IN NUMBER, arc_target_table_name IN VARCHAR2) AS
v_source_stage_table VARCHAR2(70);
v_target_fact_table VARCHAR2(70);
v_target_arc_table VARCHAR2(70);
query_fetch_deleted_recs CLOB;
query_insert_into_arc CLOB;
query_delete_from_fact CLOB;
v_delete_count NUMBER;
v_insert_count NUMBER;
v_last_deleted_date VARCHAR2(100) := TO_CHAR(last_deleted_date_in,'MM/DD/YYYY HH24:MI:SS');
BEGIN
v_source_stage_table := source_schema_in || '.' || source_table_name_in;
v_target_fact_table := target_schema_in || '.' || target_table_name_in;
v_target_arc_table := target_schema_in || '.' || arc_target_table_name;
query_fetch_deleted_recs := ' SELECT * FROM ' || v_source_stage_table ||
' STAGING_TABLE WHERE STAGING_TABLE.' || source_table_key_in || ' = FACT_TABLE.' || target_table_key_in ||
' AND NVL(STAGING_TABLE.EDW_IUD_FLAG, ''X'') = '''|| CON_EDW_IUD_FLAG ||
''' AND STAGING_TABLE.EDW_UPDATE_DATE_TIME >= TO_DATE('''|| v_last_deleted_date || ''', ''MM/DD/YYYY HH24:MI:SS'')';
DBMS_OUTPUT.PUT_LINE ('Query : ' || query_fetch_deleted_recs);
query_insert_into_arc := 'INSERT INTO ' || v_target_arc_table || ' SELECT * FROM ' || v_target_fact_table ||
' FACT_TABLE WHERE EXISTS (' || query_fetch_deleted_recs || ')';
query_delete_from_fact := 'DELETE FROM ' || v_target_fact_table ||
' FACT_TABLE WHERE EXISTS (' || query_fetch_deleted_recs || ')';
DBMS_OUTPUT.PUT_LINE ('Insert Query : ' || query_insert_into_arc);
EXECUTE IMMEDIATE query_insert_into_arc;
v_insert_count := SQL%ROWCOUNT;
EXECUTE IMMEDIATE query_delete_from_fact;
v_delete_count := SQL%ROWCOUNT;
COMMIT;
DBMS_OUTPUT.PUT_LINE ('Results : ' || v_insert_count ||v_delete_count);
--IF v_insert_count > 0 AND v_delete_count > 0 THEN
UPDATE_LAST_DELETED_DATE(v_source_stage_table, delete_control_id_in);
--END IF;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
RAISE;
END UPDATE_FACT_TABLES;
PROCEDURE UPDATE_DIMENSION_TABLES (source_schema_in IN VARCHAR2, source_table_name_in IN VARCHAR2, source_table_key_in IN VARCHAR2,
target_schema_in IN VARCHAR2, target_table_name_in IN VARCHAR2, target_table_key_in IN VARCHAR2,
last_deleted_date_in IN DATE, delete_control_id_in IN NUMBER, table_type_in IN VARCHAR2) AS
v_source_stage_table VARCHAR2(70);
v_target_dim_table VARCHAR2(70);
query_fetch_deleted_recs CLOB;
query_update_dim1 CLOB;
query_update_dim2 CLOB;
query_update_dim6 CLOB;
v_update_count NUMBER;
v_last_deleted_date VARCHAR2(100) := TO_CHAR(last_deleted_date_in,'MM/DD/YYYY HH24:MI:SS');
BEGIN
v_source_stage_table := source_schema_in || '.' || source_table_name_in;
v_target_dim_table := target_schema_in || '.' || target_table_name_in;
query_fetch_deleted_recs := ' SELECT * FROM ' || v_source_stage_table ||
' STAGING_TABLE WHERE STAGING_TABLE.' || source_table_key_in || ' = DIM_TABLE.' || target_table_key_in ||
' AND NVL(STAGING_TABLE.EDW_IUD_FLAG, ''X'') = '''|| CON_EDW_IUD_FLAG ||
''' AND STAGING_TABLE.EDW_UPDATE_DATE_TIME >= TO_DATE('''|| v_last_deleted_date || ''', ''MM/DD/YYYY HH24:MI:SS'')';
IF table_type_in = 'DIMTYP1' THEN
query_update_dim1 := 'UPDATE ' || v_target_dim_table || ' DIM_TABLE' ||
' SET DIM_TABLE.DELETE_FLAG = ''' || CON_DELETED_FLAG || ''', DIM_TABLE.EDW_UPDATE_DATE_TIME = SYSDATE, DIM_TABLE.EDW_UPDATED_BY = ''ETL'''||
' WHERE (DIM_TABLE.DELETE_FLAG = ''N'' OR DIM_TABLE.DELETE_FLAG IS NULL)' ||
' AND EXISTS (' || query_fetch_deleted_recs || ')';
DBMS_OUTPUT.PUT_LINE ('Query : ' || query_update_dim1);
EXECUTE IMMEDIATE query_update_dim1;
v_update_count := SQL%ROWCOUNT;
ELSIF table_type_in = 'DIMTYP2' THEN
query_update_dim2 := 'UPDATE ' || v_target_dim_table || ' DIM_TABLE' ||
' SET DIM_TABLE.CURRENT_FLAG = ''' || CON_CURRENT_FLAG || ''', DIM_TABLE.EDW_END_DATE = TRUNC(SYSDATE), ' ||
' EDW_UPDATE_DATE_TIME = SYSDATE, EDW_UPDATED_BY = ''ETL'''||
' WHERE DIM_TABLE.CURRENT_FLAG = ''Y'' AND EXISTS (' || query_fetch_deleted_recs || ')';
EXECUTE IMMEDIATE query_update_dim2;
v_update_count := SQL%ROWCOUNT;
ELSIF table_type_in = 'DIMTYP6' THEN
query_update_dim6 := 'UPDATE ' || v_target_dim_table || ' DIM_TABLE' ||
' SET DIM_TABLE.EDW_END_DATE = TRUNC(SYSDATE) , ' ||
' DIM_TABLE.DELETE_FLAG = ''' || CON_DELETED_FLAG || ''', DIM_TABLE.EDW_UPDATE_DATE_TIME = SYSDATE, DIM_TABLE.EDW_UPDATED_BY = ''ETL'''||
' WHERE DIM_TABLE.EDW_END_DATE = TO_DATE(''12/31/2099'',''MM/DD/YYYY'') AND EXISTS (' || query_fetch_deleted_recs || ')';
EXECUTE IMMEDIATE query_update_dim6;
v_update_count := SQL%ROWCOUNT;
END IF;
COMMIT;
DBMS_OUTPUT.PUT_LINE ('Results : ' || v_update_count);
--IF v_update_count > 0 THEN
UPDATE_LAST_DELETED_DATE(v_source_stage_table, delete_control_id_in);
--END IF;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
RAISE;
END UPDATE_DIMENSION_TABLES;
PROCEDURE UPDATE_LAST_DELETED_DATE (source_stage_table_in IN VARCHAR2, delete_control_id_in IN NUMBER) AS
query_max_updated_query CLOB;
v_max_updated_date DATE;
BEGIN
query_max_updated_query := 'SELECT MAX(STAGE_TABLE.EDW_UPDATE_DATE_TIME) FROM ' || source_stage_table_in || ' STAGE_TABLE ';
EXECUTE IMMEDIATE query_max_updated_query INTO v_max_updated_date;
UPDATE EDW_ODS_DWH_DELETES_CONTROL
SET EDW_UPDATE_DATE_TIME = SYSDATE, EDW_UPDATED_BY = 'ETL', LAST_DELETED_DATE = v_max_updated_date
WHERE DELETE_CONTROL_ID = delete_control_id_in;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
RAISE;
END UPDATE_LAST_DELETED_DATE;
PROCEDURE ERROR_LOG (delete_record_key_in IN NUMBER, table_schema_in IN VARCHAR2, target_table_in IN VARCHAR2,
error_message_in IN VARCHAR2, error_backtrace_in IN VARCHAR2 := NULL) AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO edw_ods_dwh_deletes_log VALUES (delete_record_key_in, target_table_in, table_schema_in, SYSDATE, 'ETL',
error_message_in, error_backtrace_in);
COMMIT;
RAISE_APPLICATION_ERROR(-20000, error_message_in);
EXCEPTION
WHEN OTHERS THEN
RAISE;
END ERROR_LOG;
END EDW_ODS_DELETE_RECORDS_PKG;
Your error is, as the ORA-00913 error message states, that in one of your statements you are passing too many values.
Cause:
As an example, if you have the table:
CREATE TABLE table_name (a NUMBER, b NUMBER);
And you do either of:
INSERT INTO table_name VALUES (1,2,3);
INSERT INTO table_name (a,b) VALUES (1,2,3);
Then you get the error:
ORA-00913: too many values
As you are trying to insert three values into two columns.
If you name all the columns:
INSERT INTO table_name (a,b,c) VALUES (1,2,3);
Then you will get a more expressive error message:
ORA-00904: "C": invalid identifier
Solution:
Go through every statement and explicitly name the columns you are inserting and make sure you are selecting the same number of columns.
For example, in the UPDATE_FACT_TABLES procedure you have:
query_insert_into_arc := 'INSERT INTO ' || v_target_arc_table || ' SELECT * FROM ' || v_target_fact_table ||
' FACT_TABLE WHERE EXISTS (' || query_fetch_deleted_recs || ')';
It would be better to be:
query_insert_into_arc := 'INSERT INTO ' || v_target_arc_table || ' (col1, col2, col3, col4)
|| ' SELECT other_col1, other_col2, other_col3, other_col3'
|| ' FROM ' || v_target_fact_table || ' FACT_TABLE'
|| ' WHERE EXISTS (' || query_fetch_deleted_recs || ')';
Then you know which columns are being inserted where and you will get a more detailed error message if you are trying to insert into a column that does not exist.
You also do not need to use:
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
RAISE;
As the default behaviour is to rollback the transaction when an exception is raised.
Additionally, you should not raise an exception in your autonomous transaction as you are already raising the exception in the non-autonomous procedure.
PROCEDURE ERROR_LOG (
delete_record_key_in IN NUMBER,
table_schema_in IN VARCHAR2,
target_table_in IN VARCHAR2,
error_message_in IN VARCHAR2,
error_backtrace_in IN VARCHAR2 := NULL
)
AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO edw_ods_dwh_deletes_log (
delete_record_key, -- Give the columns their proper names
target_table,
table_schema,
change_date,
col1,
error_message,
error_backtrace
) VALUES (
delete_record_key_in,
target_table_in,
table_schema_in,
SYSDATE,
'ETL',
error_message_in,
error_backtrace_in
);
COMMIT;
-- Remove raising the exception.
END ERROR_LOG;
I've been trying to identify what's wrong with the Insert Statement in the Execute Immediate for few hours without luck. Made sure that I am not missing any commas or entering any incorrect character.
I have gone through all the answers on SO and other websites trying to figure out what could I be doing wrong but no luck.
Running this function results in the following error (error line starts with "-->" Please ignore it as its just for highlighting purpose):
ORA-00936: missing expression
ORA-06512: at "BDW_AMPS.COUNT_RECORDS", line 62
and here's the PL/SQL Code for the function:
CREATE OR REPLACE FUNCTION count_records (
p_test_case_id IN NUMBER,
p_table_name IN VARCHAR2
) RETURN VARCHAR2 IS
v_amt_recs INT;
v_test_result VARCHAR2(10);
v_threshold_val VARCHAR2(10);
v_test_suite_table VARCHAR2(100);
v_test_result_id NUMBER;
v_batch_id NUMBER;
v_report_id NUMBER;
v_test_seq_no NUMBER;
v_session_name VARCHAR2(100);
v_error_description VARCHAR2(100);
v_process_by VARCHAR2(100);
BEGIN
v_test_suite_table := 'bdw_amps.spares_bdw_test_suite';
v_process_by := 'INFORMATICA';
EXECUTE IMMEDIATE 'SELECT THRESHHOLD_VALUE FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
INTO v_threshold_val;
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || p_table_name
INTO v_amt_recs;
EXECUTE IMMEDIATE 'SELECT BDW_AMPS.SPARES_TEST_SEQ_ID_SEQ.NEXTVAL FROM DUAL'
INTO v_test_result_id;
EXECUTE IMMEDIATE 'SELECT MAX(BATCH_ID) FROM BDW_AMPS.spares_bdw_session_audit
WHERE SESSION_NAME=(SELECT SESSION_NAME FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
|| ')'
INTO v_batch_id;
EXECUTE IMMEDIATE 'SELECT REPORT_ID FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
INTO v_report_id;
EXECUTE IMMEDIATE 'SELECT TEST_SEQ FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
INTO v_test_seq_no;
EXECUTE IMMEDIATE 'SELECT SESSION_NAME FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
INTO v_session_name;
IF
v_amt_recs > v_threshold_val
THEN
v_test_result := 'PASS';
--> EXECUTE IMMEDIATE 'INSERT INTO BDW_AMPS.spares_bdw_test_results(
TEST_RESULT_ID,
BATCH_ID,
REPORT_ID,
TEST_CASE_ID,
TEST_SEQ_NO,
TABLE_NAME,
SESSION_NAME,
TEST_RESULT,
PROCESS_DATE,
PROCESS_BY
)
VALUES
('|| v_test_result_id || ',
' || v_batch_id || ',
' || v_report_id || ',
' || p_test_case_id || ',
' || v_test_seq_no || ',
' || p_table_name || ',
' || v_session_name || ',
' || v_test_result || ',
SYSDATE,
' || v_process_by || '
)';
EXECUTE IMMEDIATE 'commit';
ELSE
v_test_result := 'FAIL';
v_error_description := 'Count: ' || v_amt_recs || ' is greater than threshold value: ' || v_threshold_val;
EXECUTE IMMEDIATE 'INSERT INTO BDW_AMPS.spares_bdw_test_results(
TEST_RESULT_ID,
BATCH_ID,
REPORT_ID,
TEST_CASE_ID,
TEST_SEQ_NO,
TABLE_NAME,
SESSION_NAME,
TEST_RESULT,
ERROR_DESCRIPTION,
PROCESS_DATE,
PROCESS_BY
)
VALUES (
'|| v_test_result_id || ',
' || v_batch_id || ',
' || v_report_id || ',
' || p_test_case_id || ',
' || v_test_seq_no || ',
' || p_table_name || ',
' || v_session_name || ',
' || v_test_result || ',
' || v_error_description || ',
SYSDATE,
' || v_process_by || '
)';
EXECUTE IMMEDIATE 'commit';
END IF;
RETURN v_test_result;
END;
Assuming that this is a simplified example of something that really does need to be dynamic, one issue is that the string values are not quoted. (If you'd had date values they would need special handling too.)
For example:
create table demo (numcol number, stringcol varchar2(20));
declare
l_num number := 123;
l_string varchar2(20) := 'Kittens';
l_sql long := 'insert into demo(numcol, stringcol) values ('||l_num||', '||l_string||')';
begin
dbms_output.put_line(l_sql);
execute immediate l_sql;
end;
/
Generated code:
insert into demo(numcol, stringcol) values (123, Kittens)
Fails with:
ORA-00984: column not allowed here
The error will vary depending on the contents of the string. For example, if it contains spaces:
declare
l_num number := 123;
l_string varchar2(20) := 'Kittens are cute';
l_sql long := 'insert into demo(numcol, stringcol) values ('||l_num||', '||l_string||')';
begin
dbms_output.put_line(l_sql);
execute immediate l_sql;
end;
/
Generated code:
insert into demo(numcol, stringcol) values (123, Kittens are cute)
ORA-00917: missing comma
or commas:
declare
l_num number := 123;
l_string varchar2(20) := 'Kittens, Puppies';
l_sql long := 'insert into demo(numcol, stringcol) values ('||l_num||', '||l_string||')';
begin
dbms_output.put_line(l_sql);
execute immediate l_sql;
end;
/
insert into demo(numcol, stringcol) values (123, Kittens, Puppies)
ORA-00913: too many values
You need to build the quoting:
declare
l_num number := 123;
l_string varchar2(20) := 'Kittens, Puppies';
l_sql long := 'insert into demo(numcol, stringcol) values ('||l_num||', '''||l_string||''')';
begin
dbms_output.put_line(l_sql);
execute immediate l_sql;
end;
/
so that you generate
insert into demo(numcol, stringcol) values (123, 'Kittens, Puppies')
(If the string could contain quote characters, that would need more work.)
It's worth always building the dynamic SQL as a variable and printing or logging it on failure, as it's usually pretty clear what the issue is when you can see the code.
Another point is that concatenating values like this is resource-intensive, as Oracle tries to cache SQL statements for reuse, so they will be individually parsed and optimised and take space in the cache, but they will never be reused. If this is going to be frequently run with different values, you should consider using bind variables via the using clause of execute immediate.
Your DML(INSERT) statements do not need EXECUTE IMMEDIATE statements. So, remove them after line 61 :
CREATE OR REPLACE FUNCTION count_records (
p_test_case_id IN NUMBER,
p_table_name IN VARCHAR2
) RETURN VARCHAR2 IS
v_amt_recs INT;
v_test_result VARCHAR2(10);
v_threshold_val VARCHAR2(10);
v_test_suite_table VARCHAR2(100);
v_test_result_id NUMBER;
v_batch_id NUMBER;
v_report_id NUMBER;
v_test_seq_no NUMBER;
v_session_name VARCHAR2(100);
v_error_description VARCHAR2(100);
v_process_by VARCHAR2(100);
BEGIN
v_test_suite_table := 'bdw_amps.spares_bdw_test_suite';
v_process_by := 'INFORMATICA';
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || p_table_name
INTO v_amt_recs;
v_test_result_id := BDW_AMPS.SPARES_TEST_SEQ_ID_SEQ.NEXTVAL;
EXECUTE IMMEDIATE 'SELECT MAX(BATCH_ID) FROM BDW_AMPS.spares_bdw_session_audit
WHERE SESSION_NAME=(SELECT SESSION_NAME FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
|| ')'
INTO v_batch_id;
EXECUTE IMMEDIATE 'SELECT THRESHHOLD_VALUE, REPORT_ID, TEST_SEQ,SESSION_NAME FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = :caseId'
INTO v_threshold_val,v_report_id,v_test_seq_no,v_session_name
USING p_test_case_id;
IF
v_amt_recs > v_threshold_val
THEN
v_test_result := 'PASS';
INSERT INTO BDW_AMPS.spares_bdw_test_results(
TEST_RESULT_ID,
BATCH_ID,
REPORT_ID,
TEST_CASE_ID,
TEST_SEQ_NO,
TABLE_NAME,
SESSION_NAME,
TEST_RESULT,
PROCESS_DATE,
PROCESS_BY
)
VALUES
( v_test_result_id ,
v_batch_id ,
v_report_id ,
p_test_case_id ,
v_test_seq_no ,
p_table_name ,
v_session_name ,
v_test_result ,
SYSDATE,
v_process_by
);
commit;
ELSE
v_test_result := 'FAIL';
v_error_description := 'Count: ' || v_amt_recs || ' is greater than threshold value: ' || v_threshold_val;
INSERT INTO BDW_AMPS.spares_bdw_test_results(
TEST_RESULT_ID,
BATCH_ID,
REPORT_ID,
TEST_CASE_ID,
TEST_SEQ_NO,
TABLE_NAME,
SESSION_NAME,
TEST_RESULT,
ERROR_DESCRIPTION,
PROCESS_DATE,
PROCESS_BY
)
VALUES (
v_test_result_id ,
v_batch_id ,
v_report_id ,
p_test_case_id ,
v_test_seq_no ,
p_table_name ,
v_session_name ,
v_test_result ,
v_error_description ,
SYSDATE,
v_process_by
);
commit;
END IF;
RETURN v_test_result;
END;
while usage of them are right for SELECT statements because of dynamic table names.
I am trying to use insert into statement, but getting the error:
ORA-01628: max # extents (32765) reached for rollback segment _SYSSMU134_1882489978$
Increasing the UNDO tablespace is not an option, so I would like a way to insert those data by chunks (for example with 1 million rows at a time). Can someone help to rewrite this procedure in that way?
CREATE OR REPLACE PROCEDURE create_chunks (
p_source_table IN VARCHAR2,
p_table_name_chunk IN VARCHAR2,
p_chunks IN VARCHAR2
) AS
v_insert_sql CLOB;
BEGIN
v_insert_sql := 'INSERT INTO ' || p_table_name_chunk ||
' (rid, chunk_number) ' ||
'SELECT /*+ parallel(64) */ rowid rid,' ||
'mod( ora_hash(rowid), :p_chunks ) as chunk_number '
'FROM ' || p_source_table;
EXECUTE IMMEDIATE v_insert_sql USING p_chunks;
COMMIT;
END;
This v_insert_sql is failing with above mentioned error. I have working solution using the cursor fetching like that:
DECLARE
CURSOR v_cur IS SELECT /*+ parallel(64) */
rowid rid, mod( ora_hash(rowid), 20000 ) AS chunk_number
-- I need this table to be parametric name
FROM some_table;
TYPE t_sample IS TABLE OF v_cur%ROWTYPE;
v_sample t_sample;
v_row_limit CONSTANT NUMBER := 1000000;
BEGIN
OPEN v_cur;
LOOP
FETCH v_cur BULK COLLECT INTO v_sample LIMIT v_row_limit;
FORALL i IN v_sample.first .. v_sample.last
INSERT INTO chunk_table VALUES v_sample(i);
COMMIT;
EXIT WHEN v_cur%NOTFOUND;
END LOOP;
CLOSE v_cur;
END;
I can't move this cursor straight into the procedure as the table name is varying and I need it to be parametric as with cursor approach I have to repeat the same code for different tables. So the question is how to deal with this?
Basically, I was able to just past the whole chunks approach inside procedure as dynamic query, like that:
CREATE OR REPLACE PROCEDURE create_chunks (
p_source_table IN VARCHAR2,
p_table_name_chunk IN VARCHAR2,
p_chunks IN VARCHAR2
) AS
v_insert_sql CLOB;
BEGIN
v_insert_sql := '' ||
' DECLARE ' || CHR(10) ||
' CURSOR cur1 IS SELECT ' || CHR(10) ||
' /*+ parallel(64) full(tbn)*/ rowid rid,' || CHR(10) ||
' mod( ora_hash(rowid), :p_chunks ) AS chunk_number' || CHR(10) ||
' FROM ' || p_source_table || ' tbn;' || CHR(10) ||
' TYPE t_sample IS TABLE OF cur1%ROWTYPE;' || CHR(10) ||
' v_sample t_sample;' || CHR(10) ||
' v_row_limit CONSTANT NUMBER := 1000000;' || CHR(10) ||
' BEGIN' || CHR(10) ||
' OPEN cur1;' || CHR(10) ||
' LOOP' || CHR(10) ||
' FETCH cur1 BULK COLLECT INTO v_sample LIMIT v_row_limit;' || CHR(10) ||
' FORALL i IN v_sample.first .. v_sample.last' || CHR(10) ||
' INSERT INTO ' || p_table_name_chunk || ' VALUES v_sample(i);' || CHR(10) ||
' COMMIT;' || CHR(10) ||
' EXIT WHEN cur1%NOTFOUND;' || CHR(10) ||
' END LOOP;' || CHR(10) ||
' CLOSE cur1;' || CHR(10) ||
' END;';
EXECUTE IMMEDIATE v_insert_sql USING p_chunks;
COMMIT;
END;
I have a stored procedure within Oracle that dynamically creates triggers for all of my tables (since they trigger the same stored procedure), by constructing SQL code and executing it with Oracle's PL/SQL EXECUTE command (although I am using SQL Commander for testing). How does one correctly create an if statement within a trigger? Below is my code, which gets syntax error on the line with there IF statement starts.
CREATE OR REPLACE TRIGGER "DATABASE"."TABLE_TRIGGER"
AFTER INSERT OR DELETE OR UPDATE ON TABLE
FOR EACH ROW
DECLARE
v_op VARCHAR2(20);
BEGIN
IF INSERTING THEN
v_op := 'INSERT';
ELSIF UPDATING THEN
v_op := 'UPDATE';
ELSE
v_op := 'DELETE';
END IF;
PKG.STORED_PROC(v_op, ' - MY_COLUMN: ' || :NEW.MY_COLUMN || '', 'MY_TABLE');
END;
This is a sample of the code I used to generate the SQL code.
PROCEDURE CREATE_TRIGGERS(
IN_TABLE_OMIT IN VARCHAR2, -- IN_TABLE_OMIT is a list of tables to not create a trigger on, as CSV
OUT_RESULT OUT VARCHAR2)
AS
v_table_results SYS_REFCURSOR;
v_column_results SYS_REFCURSOR;
v_template_head VARCHAR2(512);
v_template_body VARCHAR2(512);
v_template_operation VARCHAR(512);
v_template_column VARCHAR2(128);
v_template_data VARCHAR2(1024);
v_template_foot VARCHAR2(512);
v_result VARCHAR2(1024);
BEGIN
-- Create a template for each trigger
v_template_head := 'CREATE OR REPLACE TRIGGER "MY_DB"."MY_TABLE_TRIGGER"' || chr(10);
v_template_head := v_template_head || 'AFTER INSERT OR DELETE OR UPDATE ON MY_TABLE' || chr(10);
v_template_head := v_template_head || 'FOR EACH ROW' || chr(10) || 'DECLARE' || chr(10) || 'v_op VARCHAR2(20);' || chr(10) || 'BEGIN' || chr(10) || chr(10);
v_template_operation := 'IF INSERTING THEN v_op := ''INSERT''; ELSIF UPDATING THEN v_op := ''UPDATE''; ELSE v_op := ''DELETE''; END IF;' || chr(10);
v_template_body := 'MY_DB.STORED_PROC(' || chr(10) || 'v_op,' || chr(10);
v_template_column := ''' - MY_COLUMN: '' || :NEW.MY_COLUMN || ';
v_template_foot := '''MY_TABLE'');' || chr(10) || chr(10) || 'END;';
-- Insert double quotes into template
-- Loop through each table
FOR LOOP_TABLE IN (SELECT TABLE_NAME FROM USER_TABLES ORDER BY TABLE_NAME) LOOP
IF INSTR(IN_TABLE_OMIT, LOOP_TABLE.TABLE_NAME) != 0 OR INSTR('AUDIT_TABLE', LOOP_TABLE.TABLE_NAME) != 0 THEN
FOR LOOP_COLUMN IN (SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = LOOP_TABLE.TABLE_NAME) LOOP
v_template_data := v_template_data || REPLACE(v_template_column, 'MY_COLUMN', LOOP_COLUMN.COLUMN_NAME);
END LOOP;
v_template_head := REPLACE(v_template_head, 'MY_TABLE', LOOP_TABLE.TABLE_NAME);
v_template_data := v_template_data || ''''',' || chr(10);
v_template_foot := REPLACE(v_template_foot, 'MY_TABLE', LOOP_TABLE.TABLE_NAME);
v_result := v_template_head || v_template_operation || v_template_body || v_template_data || v_template_foot;
v_template_data := '';
OUT_RESULT := chr(10) || v_result;
ELSE
dbms_output.put_line('Searched for ' || LOOP_TABLE.TABLE_NAME || ' in ' || IN_TABLE_OMIT);
END IF;
END LOOP;
END;
The trigger was successfully created when removing all semi-colons from the generated trigger statement.
I have created the PL/SQL stored procedure below to search an entire Oracle11g database for a string (srchstr) and return the table and column where that string was found to a table called VALUESEARCHRESULTS.
The procedure has ran successfully in Oracle XE via SQL Developer as a user. However, when try to run it as user SYS in Oracle11g for schema ABC, I receive the following error:
ORA-00911: invalid character
Cause: identifiers may not start with any ASCII character other than letters and numbers. $#_ are also allowed after the first character. Identifiers enclosed by double quotes may contain any character other than a double quote. Alternative quotes (q"#...#") cannot use spaces, tabs, or carriage returns as delimiters. For all other contexts, consult the SQL Language Reference Manual.
Does anyone know why this may be? Please see my code below.
CREATE OR REPLACE PROCEDURE ABC.FIND_STRING(p_str IN VARCHAR2) authid current_user is
l_query clob;
srchstr varchar2(30) := '';
r_cname varchar2(30) := '';
l_case clob;
l_runquery boolean;
l_tname varchar2(30);
l_cname varchar2(30);
begin
dbms_application_info.set_client_info( '%' || upper(p_str) || '%' );
for x in (select * from user_tables)
loop
l_query := 'select ''' || x.table_name || ''', $$
from ' || x.table_name || '
where rownum = 1 and ( 1=0 ';
l_case := 'case ';
l_runquery := FALSE;
for y in ( select *
from user_tab_columns
where table_name = x.table_name
and (data_type in('CHAR', 'DATE', 'FLOAT', 'NCHAR', 'NUMBER', 'NVARCHAR2', 'VARCHAR2' )
or data_type like 'INTERVAL%' or data_type like 'TIMESTAMP%' )
)
loop
l_runquery := TRUE;
l_query := l_query || ' or upper(' || y.column_name ||
') like userenv(''client_info'') ';
l_case := l_case || ' when upper(' || y.column_name ||
') like userenv(''client_info'') then ''' ||
y.column_name || '''';
end loop;
if ( l_runquery )
then
l_case := l_case || ' else NULL end';
l_query := replace( l_query, '$$', l_case ) || ')';
begin
execute immediate l_query into l_tname, l_cname;
r_cname := l_cname;
dbms_application_info.read_client_info(srchstr);
insert into ABC.ValueSearchResults (resulttable, resultcolumn, searchstring) values (x.table_name, r_cname, srchstr);
dbms_output.put_line
( srchstr || ' found in ' || l_tname || '.' || l_cname );
exception
when no_data_found then
dbms_output.put_line
( srchstr || ' has no hits in ' || x.table_name );
end;
end if;
end loop;
end;
EDIT: The stored procedure above compiles without error. The code below executes the stored procedure by passing values from a table into the stored procedure. The error shows when the code below is ran:
BEGIN
FOR c IN (SELECT ControlValue FROM ABC.ControlValues) LOOP
ABC.FIND_STRING(c.ControlValue);
END LOOP;
END;
I have found a resolution for the issue I initially raised.
Cause of error: Not specifying a schema; only grabbing user-specific tables.
While the stored procedure would execute when deployed as user ABC, the error generated when running the stored procedure as a user other ABC. It appeared the same table name existed in multiple schemas. Thus, adding an OWNER variable specified the schema associated with the table name and eliminated the error.
Additionally, the procedure was originally searching for USER_TABLES. This limited the results to only the tables of the current schema. By replacing USER_TABLES with DBA_TABLES, the stored procedure's search spanned through all tables of the database.
See below for the corrected code:
CREATE OR REPLACE
PROCEDURE FIND_STRING(
p_str IN VARCHAR2) authid current_user
IS
l_query CLOB;
srchstr VARCHAR2(100) := '';
r_cname VARCHAR2(100) := '';
l_case CLOB;
l_runquery BOOLEAN;
l_tname VARCHAR2(100);
l_cname VARCHAR2(100);
BEGIN
dbms_application_info.set_client_info( '%' || upper(p_str) || '%' );
FOR x IN
(SELECT *
FROM dba_tables
WHERE table_name <> 'CONTROLVALUES'
AND table_name <> 'VALUESEARCHRESULTS'
AND tablespace_name <> 'SYSTEM'
AND tablespace_name <> 'SYSAUX'
AND tablespace_name <> 'TEMP'
AND tablespace_name <> 'UNDOTBS1'
)
LOOP
l_query := 'select ''' || x.owner || '.' || x.table_name || ''', $$
from ' || x.owner || '.' || x.table_name || '
where rownum = 1 and ( 1=0 ';
l_case := 'case ';
l_runquery := FALSE;
FOR y IN
(SELECT *
FROM dba_tab_columns
WHERE table_name = x.table_name
AND owner = x.owner
AND (data_type IN ( 'CHAR', 'DATE', 'FLOAT', 'NCHAR', 'NUMBER', 'NVARCHAR2', 'VARCHAR2' )
OR data_type LIKE 'INTERVAL%'
OR data_type LIKE 'TIMESTAMP%' )
)
LOOP
l_runquery := TRUE;
l_query := l_query || ' or upper(' || y.column_name || ') like userenv (''client_info'') ';
l_case := l_case || ' when upper(' || y.column_name || ') like userenv (''client_info'') then ''' || y.column_name || '''';
END LOOP;
IF ( l_runquery ) THEN
l_case := l_case || ' else NULL end';
l_query := REPLACE( l_query, '$$', l_case ) || ')';
BEGIN
EXECUTE immediate l_query INTO l_tname, l_cname;
r_cname := l_cname;
dbms_application_info.read_client_info(srchstr);
INSERT
INTO VALUESEARCHRESULTS
(
resulttable,
resultcolumn,
searchstring
)
VALUES
(
x.table_name,
r_cname,
srchstr
);
dbms_output.put_line ( srchstr || ' found in ' || l_tname || '.' || l_cname );
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line ( srchstr || ' has no hits in ' || x.owner || '.' || x.table_name );
END;
END IF;
END LOOP;
END;