I am using the following Procedure in pl sql
CREATE OR REPLACE "MY_PROCEDURE" (v_id number, v_name varchar2) AS
BEGIN
EXECUTE IMMEDIATE ' CREATE TABLE T_TEMPO ( t_id number , t_name varchar2(250) , t_value number )';
EXECUTE IMMEDIATE 'INSERT INTO T_TEMPO (t_id , t_name, t_value)
SELECT id , name , value
from TABLE_2
where TABLE_2.id = || v_id ||
AND TABLE_2.name = || v_name || ';
But this doesn't work I have a missing expression error, I wonder it can't evaluate the value of the variables v_id and v_name inside the execute immediate.
Can anyone help please?
You'll either need to quote the values (using quotation marks where necessary):
create or replace procedure my_procedure
( v_id number
, v_name varchar2 )
as
begin
execute immediate 'CREATE TABLE T_TEMPO (t_id number, t_name varchar2(250), t_value number )';
execute immediate 'INSERT INTO T_TEMPO (t_id, t_name, t_value)
SELECT id, name, value
FROM table_2
WHERE table_2.id = ' || v_id ||
' AND table_2.name = ''' || v_name || '''';
end my_procedure;
or (generally better) pass them as bind variables:
create or replace procedure my_procedure
( v_id number
, v_name varchar2 )
as
begin
execute immediate 'CREATE TABLE T_TEMPO (t_id number, t_name varchar2(250), t_value number )';
execute immediate 'INSERT INTO T_TEMPO (t_id, t_name, t_value)
SELECT id, name, value
FROM table_2
WHERE table_2.id = :id
AND table_2.name = :name' using v_id, v_name;
end my_procedure;
btw I would use the v prefix for variables and p for parameters.
Please use variables outside quotation:
EXECUTE IMMEDIATE ' CREATE TABLE T_TEMPO ( t_id number , t_name varchar2(250) , t_value number )';
EXECUTE IMMEDIATE 'INSERT INTO T_TEMPO (t_id , t_name, t_value)
SELECT id , name , value
from TABLE_2
where TABLE_2.id = ' || v_id ||
' AND TABLE_2.name = '''|| v_name || '''';
Related
I'm try use DML operations on table, when insert or update. I need to show column name and column comment when the operation failed. For example code:
CREATE TABLE test_test(col1 VARCHAR2(10), col2 VARCHAR2(100) not null);
DECLARE
ex_insert_null EXCEPTION;
PRAGMA EXCEPTION_INIT(ex_insert_null, -1400);
ex_value_too_large EXCEPTION;
PRAGMA EXCEPTION_INIT(ex_value_too_large, -12899);
BEGIN
INSERT INTO test_test
(col1
,col2)
SELECT CASE
WHEN LEVEL = 8 THEN
(LEVEL + 1) || 'qqqqqqqqqqqq'
ELSE
(LEVEL + 2) || 'qqq'
END AS col1
,CASE
WHEN LEVEL = 7 THEN
NULL
ELSE
(LEVEL + 3) || 'wwwwwww'
END AS col2
FROM dual
CONNECT BY LEVEL <= 10;
COMMIT;
EXCEPTION
WHEN ex_insert_null THEN
ROLLBACK;
dbms_output.put_line('ex_insert_null at ' || ' ' /* || column_name || ' ' || column_comment */);
WHEN ex_value_too_large THEN
ROLLBACK;
dbms_output.put_line('ex_value_too_large at ' || ' ' /* || column_name || ' ' || column_comment */);
END;
/
As APC has pointed out, you could use "existing Oracle exceptions" eg if you had something like ...
procedure insert_( col1 varchar2, col2 varchar2 )
is
v_errorcode varchar2(64) ;
v_errormsg varchar2(128) ;
begin
insert into t ( c1, c2 ) values ( col1, col2 ) ;
exception
when others then
if sqlcode = -1400 or sqlcode = -12899 then
v_errorcode := sqlcode;
v_errormsg := substr( sqlerrm, 1, 128 );
dbms_output.put_line( v_errorcode || ' ' || v_errormsg ) ;
raise;
end if;
end insert_ ;
... you could get error messages such as these:
-1400 ORA-01400: cannot insert NULL into ("MYSCHEMA"."T"."C2")
-12899 ORA-12899: value too large for column "MYSCHEMA"."T"."C1" (actual: 13, maximum: 10)
If this is enough information for you, fine. However, you also want to see the COMMENTS for the columns. Although we could get the column names from the SQLERRM strings, it may be more reliable to use user-defined exceptions (as you have hinted).
As a starting point, the following DDL and PACKAGE code may be of use for you. ( see also: dbfiddle here )
Tables:
drop table t cascade constraints ;
drop table errorlog cascade constraints ;
create table t (
c1 varchar2(10)
, c2 varchar2(64) not null
) ;
comment on column t.c1 is 'this is the column comment for c1';
comment on column t.c2 is 'this is the column comment for c2';
create table errorlog (
when_ timestamp
, msg varchar2(4000)
) ;
Package spec
create or replace package P is
-- insert into T, throwing exceptions
procedure insert_( col1 varchar2, col2 varchar2 );
-- use your example SELECT, call the insert_ procedure
procedure insert_test ;
-- retrieve the column comments from user_col_comments
function fetch_comment( table_ varchar2, col_ varchar2 ) return varchar2 ;
end P ;
/
Package body
create or replace package body P is
procedure insert_( col1 varchar2, col2 varchar2 )
is
ex_value_too_large exception ; -- T.c1: varchar2(10)
ex_insert_null exception ; -- T.c2: cannot be null
v_errorcol varchar2(32) := '' ;
v_comment varchar2(128) := '' ;
v_tablename constant varchar2(32) := upper('T') ;
begin
if length( col1 ) > 10 then
v_errorcol := upper('C1') ;
raise ex_value_too_large ;
end if;
if col2 is null then
v_errorcol := upper('C2') ;
raise ex_insert_null ;
end if ;
insert into t ( c1, c2 ) values ( col1, col2 ) ;
exception
when ex_value_too_large then
dbms_output.put_line( ' ex_value_too_large # '
|| v_errorcol || ' (' || fetch_comment( v_tablename, v_errorcol ) || ')' );
when ex_insert_null then
dbms_output.put_line( ' ex_insert_null # '
|| v_errorcol || ' (' || fetch_comment( v_tablename, v_errorcol ) || ')' );
when others then
raise ;
end insert_ ;
procedure insert_test
is
begin
for rec_ in (
select
case
when level = 8 then ( level + 1 ) || 'qqqqqqqqqqqq'
else ( level + 2 ) || 'qqq'
end as col1
, case
when level = 7 then null
else ( level + 3 ) || 'wwwwwww'
end as col2
from dual
connect by level <= 10
) loop
insert_( rec_.col1, rec_.col2 ) ;
end loop;
commit;
end insert_test;
function fetch_comment( table_ varchar2, col_ varchar2 ) return varchar2
is
v_comment varchar2(4000) ; -- same datatype as in user_tab_comments
begin
select comments into v_comment
from user_col_comments
where table_name = table_
and column_name = col_ ;
return v_comment ;
end fetch_comment ;
end P ;
/
For testing the package code, execute the following anonymous block:
begin
P.insert_test ;
end;
/
-- output
ex_insert_null # C2 (this is the column comment for c2)
ex_value_too_large # C1 (this is the column comment for c1)
-- Table T contains:
SQL> select * from T;
C1 C2
3qqq 4wwwwwww
4qqq 5wwwwwww
5qqq 6wwwwwww
6qqq 7wwwwwww
7qqq 8wwwwwww
8qqq 9wwwwwww
11qqq 12wwwwwww
12qqq 13wwwwwww
In the dbfiddle, all output will be written to T and ERRORLOG, respectively. You can also use dbms_output.put_line (which is commented out in the dbfiddle) if needed. Notice that the cursor for loop in the insert_test procedure is inefficient (we could use BULK operations). Also, you need to decide where and how the exceptions are handled. As mentioned, this example is just a starting point - which will probably need lots of refinements.
I have a table XX_LOCATION with 20 columns. Out of this I want data in only 4 columns in rest 16 I want to update the column values to null.
How can 1 update statement be used for this i.e. I don't want to write each column name of 16 columns in the update statement. Is there any other way out?
Ok, I admit. I am having a little bit of fun with this one.
BEGIN
FOR eachrec IN (SELECT column_name
FROM user_tab_cols a
WHERE table_name = 'MYTABLE'
AND column_name NOT IN ('COL1', 'COL2', 'COL3'
, 'COL4'))
LOOP
execute immediate 'update XX_LOCATION set ' || eachrec.column_name || ' = null';
END LOOP;
END;
Here is another possibility, this one with only a single execute immediate:
DECLARE
l_cmd VARCHAR2 (2000);
l_comma VARCHAR2 (1);
BEGIN
l_cmd := 'update xx_location set ';
FOR eachrec IN (SELECT column_name
FROM user_tab_cols a
WHERE table_name = 'MYTABLE'
AND column_name NOT IN ('COL1', 'COL2', 'COL3'
, 'COL4'))
LOOP
l_cmd := l_cmd || l_comma || eachrec.column_name || ' = null';
l_comma := ',';
END LOOP;
execute immediate l_cmd;
END;
And finally, a completely automated solution to exclude N columns, without having to type the non-specified column names:
CREATE TYPE column_tt IS TABLE OF VARCHAR2 (30);
CREATE OR REPLACE PROCEDURE nullify_columns (
p_owner IN all_tab_cols.owner%TYPE
, p_table IN all_tab_cols.table_name%TYPE
, p_exclude_columns IN OUT NOCOPY column_tt
)
AS
l_cmd VARCHAR2 (2000);
l_comma VARCHAR2 (1);
BEGIN
l_cmd := 'update ' || p_owner || '.' || p_table || ' set ';
FOR eachrec IN (SELECT column_name
FROM all_tab_cols a
WHERE owner = p_owner
AND table_name = p_table)
LOOP
IF NOT eachrec.column_name MEMBER OF p_exclude_columns
THEN
l_cmd := l_cmd || l_comma || eachrec.column_name || ' = null';
l_comma := ',';
END IF;
END LOOP;
EXECUTE IMMEDIATE l_cmd;
END;
CREATE TABLE totally_bogus_dude
(
col1 VARCHAR2 (10)
, col2 VARCHAR2 (10)
, col3 VARCHAR2 (10)
, col4 VARCHAR2 (10)
, col5 VARCHAR2 (10)
);
DECLARE
l_exclude column_tt := column_tt ();
BEGIN
l_exclude.EXTEND;
l_exclude (l_exclude.COUNT) := 'COL1';
l_exclude.EXTEND;
l_exclude (l_exclude.COUNT) := 'COL2';
l_exclude.EXTEND;
l_exclude (l_exclude.COUNT) := 'COL3';
l_exclude.EXTEND;
l_exclude (l_exclude.COUNT) := 'COL4';
FOR eachrec IN (SELECT COLUMN_VALUE
FROM TABLE (l_exclude))
LOOP
DBMS_OUTPUT.put_line (eachrec.COLUMN_VALUE);
END LOOP;
nullify_columns (p_owner => USER, p_table => 'TOTALLY_BOGUS_DUDE', p_exclude_columns => l_exclude);
END;
I am trying to declare a cursor inside procedure body.
I know it is supposed to be done in the declare block but the table the cursor refers is created inside the procedure body.
--TABLE MAY OR MAY NOT BE PRESENT PRIOR TO PROCEDURE EXECUTION
SELECT COUNT(*)
INTO ln_cnt
FROM User_Tables
WHERE table_name = 'TMP$UOM_COMBO_GEN';
IF ln_cnt > 0 THEN
EXECUTE IMMEDIATE ' CREATE TABLE TMP$UOM_COMBO_GEN (UOM_ID VARCHAR2(20 BYTE), HIER_CODE VARCHAR2(20 BYTE),NODE_CODE VARCHAR2(200 BYTE))';
END IF;
CURSOR C_HIER
IS
SELECT DISTINCT HIER_CODE FROM TMP$UOM_COMBO_GEN WHERE UOM_ID=P_UOM_ID;
FOR HIER IN C_HIER
LOOP
IF C_HIER%ROWCOUNT = 1 THEN
LV_SQL2 := '(SELECT UOM_ID, NODE_CODE '||HIER.HIER_CODE||' FROM TMP$UOM_COMBO_GEN WHERE UOM_ID='''||P_UOM_ID||''' AND HIER_CODE='''||HIER.HIER_CODE||''')'||HIER.HIER_CODE;
LV_SORT := ' ORDER BY '||HIER.HIER_CODE||'';
LV_SQL := 'SELECT * FROM ' || LV_SQL2;
ELSE
LV_SQL3 := ' LEFT OUTER JOIN(SELECT NODE_CODE '||HIER.HIER_CODE||' FROM TMP$UOM_COMBO_GEN WHERE UOM_ID='''||P_UOM_ID||''' AND HIER_CODE='''||HIER.HIER_CODE||''')'||HIER.HIER_CODE ||' ON 1=1';
LV_SORT := LV_SORT||','||HIER.HIER_CODE||'';
LV_SQL := LV_SQL || LV_SQL3;
END IF;
END LOOP;
I am getting the following error.
Error(17,10): PLS-00103: Encountered the symbol "C_HIER" when expecting one of the following: := . ( # % ;
Well a table once created is stored in database and u can refer it from wherever u want to refer in the schema .
Also there a change may be required in your code in the following part
SELECT COUNT(*)
INTO ln_cnt
FROM User_Tables
WHERE table_name = 'TMP$UOM_COMBO_GEN';
IF ln_cnt > 0 THEN -- means only if table exists u want to create the table which will
--throw an exception if table is already there ,
--so better equate it to 0
EXECUTE IMMEDIATE ' CREATE TABLE TMP$UOM_COMBO_GEN (UOM_ID VARCHAR2(20 BYTE), HIER_CODE VARCHAR2(20 BYTE),NODE_CODE VARCHAR2(200 BYTE))';
END IF;
Now , if u really have a requirement to create a new table every time some condition is true/false and u then want to select the table in a cursor do something like following by using reference cursors
create or replace procedure abc(Table_name varchar2 , param_list varchar2 , where_clause varchar2) is
c_hier sys_refcursor ;
LV_SQL2 varchar2(2000) ;
LV_SORT varchar2(2000) ;
LV_SQL varchar2(2000) ;
LV_SQL3 varchar2(2000) ;
begin
SELECT COUNT(*)
INTO ln_cnt
FROM User_Tables
WHERE table_name = Table_name; -- Use any table here
IF ln_cnt = 0 THEN
EXECUTE IMMEDIATE ' CREATE TABLE '||Table_name||' '||param_list;
END IF;
open c_hier for 'SELECT DISTINCT '||param_list||' FROM '||table_name||' '||where_clause;
FOR HIER IN C_HIER
LOOP
IF C_HIER%ROWCOUNT = 1 THEN
LV_SQL2 := '(SELECT UOM_ID, NODE_CODE '||HIER.HIER_CODE||' FROM TMP$UOM_COMBO_GEN WHERE UOM_ID='''||P_UOM_ID||''' AND HIER_CODE='''||HIER.HIER_CODE||''')'||HIER.HIER_CODE;
LV_SORT := ' ORDER BY '||HIER.HIER_CODE||'';
LV_SQL := 'SELECT * FROM ' || LV_SQL2;
ELSE
LV_SQL3 := ' LEFT OUTER JOIN(SELECT NODE_CODE '||HIER.HIER_CODE||' FROM TMP$UOM_COMBO_GEN WHERE UOM_ID='''||P_UOM_ID||''' AND HIER_CODE='''||HIER.HIER_CODE||''')'||HIER.HIER_CODE ||' ON 1=1';
LV_SORT := LV_SORT||','||HIER.HIER_CODE||'';
LV_SQL := LV_SQL || LV_SQL3;
END IF;
END LOOP;
I'm trying to implement an undo and logging feature for my project.
When a user deletes a row from a table with the DELETE_ROW procedure i select all values from that row and insert it into my row_history table by serializing row values as xml with LOG_DELETED_ROW procedure, then i delete row from its original table.
Serializing with built-in functions of Oracle was easy but i couldn't find a way to deserialize the rowdata and insert it back to own table.
Is there any way to store that deleted row into another table and restore it when needed?
Delete Procedure:
create or replace procedure DELETE_ROW(tableName varchar2, userId varchar2, columnName varchar2, columnValue number) is
begin
log_deleted_row(tableName, userId, columnName, columnValue);
execute immediate 'delete from ' || tableName || ' where ' || columnName || ' = ' || columnValue;
end DELETE_ROW;
Logging Procedure:
create or replace procedure LOG_DELETED_ROW(tableName varchar2, userId varchar2, columnName varchar2, columnValue number) is
tableId number;
begin
SELECT ID into tableId FROM TABLES WHERE NAME = tableName;
execute immediate
'INSERT INTO ROW_HISTORY(TABLE_ID,ROW_ID,ROW_DATA)
SELECT
'|| tableId ||',
'|| columnValue ||',
to_clob(
DBMS_XMLGEN.getxmltype(
''SELECT * FROM ' || tableName || ' where ' || columnName || ' = ' || columnValue || '''
)
)FROM DUAL';
end LOG_DELETED_ROW;
Row History Table:
create table ROW_HISTORY
(
ID NUMBER not null,
TABLE_ID NUMBER not null,
ROW_ID NUMBER not null,
ROW_DATA CLOB not null
)
DBMS_XMLSAVE seems to be the thing you need.Here is a procedure which should do what you need to do.
CREATE OR REPLACE PROCEDURE insert_xml_data(p_table IN VARCHAR2, xml_data IN CLOB) IS
t_context DBMS_XMLSAVE.CTXTYPE;
t_rows NUMBER;
BEGIN
t_context := DBMS_XMLSAVE.NEWCONTEXT(p_table);
t_rows := DBMS_XMLSAVE.INSERTXML(t_context,xml_data);
DBMS_XMLSAVE.CLOSECONTEXT(t_context);
END;
/
I believe you could use DBMS_SQL package here - it will allow you to reconstruct insert statement knowing table name and columns.
Another, more complicated, way would be to insantiate LCR$_ROW_RECORD object and then run its EXECUTE member - it will perform actual insert.
I have this SQL:
DROP TABLE MISSINGTABLE;
CREATE TABLE MISSINGTABLE (
TABLE_NAME VARCHAR2 (70),
DESCRIPTION VARCHAR2 (1000)
)
CREATE OR REPLACE PROCEDURE MISSINGTABLES AS
BEGIN
INSERT INTO MISSINGTABLE
((((SELECT TABLE_NAME, 'Missing Table on PEKA_ERP_001' Description FROM ALL_TABLES WHERE OWNER = 'ASE_ERP_001')
MINUS
(SELECT TABLE_NAME, 'Missing Table on PEKA_ERP_001' Description FROM ALL_TABLES WHERE OWNER = 'PEKA_ERP_001'))
UNION
((SELECT TABLE_NAME, 'Missing Table on ASE_ERP_001' Description FROM ALL_TABLES WHERE OWNER = 'PEKA_ERP_001')
MINUS
(SELECT TABLE_NAME, 'Missing Table on ASE_ERP_001' Description FROM ALL_TABLES WHERE OWNER = 'ASE_ERP_001'))));
END;
So, how u can see, I'm creating a Table and then a Procedure, which fills the Table.
Now I want 2 Variables for these Arguments: 'PEKA_ERP_001' and 'ASE_ERP_001' (so I don't always need to write it manually, because this values changes a lot)
I tried this (included only the first part of above Statement):
DECLARE
S1 VARCHAR2(100) := 'ASE_ERP_001';
S2 VARCHAR2(100) := 'PEKA_ERP_001';
TableMissing VARCHAR(100) := 'Missing Table on ';
Apostrophe VARCHAR(10) := '''';
BEGIN
EXECUTE IMMEDIATE ('CREATE OR REPLACE PROCEDURE MISSINGTABLES AS BEGIN INSERT INTO MISSINGTABLE (SELECT TABLE_NAME, ' || Apostrophe || TableMissing || S2 || Apostrophe || ' Description FROM ALL_TAB_COLUMNS WHERE OWNER = ' || Apostrophe || S1 || Apostrophe || ')' || ' END;');
END;
It creates The Procedure, but the Procedure contains the "CREATE OR REPLACE PROCEDURE" itself and its showing me an error... (I cannot execute the Procedure)
Can anyone help me? How can I write the first SQL Statement at the Head which works, only with 2 Variables more, ASE_ERP_001 and PEKA_ERP_001 ?
EDIT:
Statement:
DECLARE
S1 VARCHAR2(100) := 'ASE_ERP_001';
S2 VARCHAR2(100) := 'PEKA_ERP_001';
TabelleFehlt VARCHAR(100) := 'Diese Tabelle fehlt ';
Hochkomma VARCHAR(10) := '''';
BEGIN
EXECUTE IMMEDIATE ('CREATE OR REPLACE PROCEDURE MISSINGTABLES AS BEGIN INSERT INTO MISSINGTABLE (SELECT TABLE_NAME, ' || Hochkomma || TabelleFehlt || S2 || Hochkomma || ' Beschreibung FROM ALL_TAB_COLUMNS WHERE OWNER = ' || Hochkomma || S1 || Hochkomma || ') END;');
END;
The Statement Above Creates a Procedure.
But it also shows me this:
ORA-06512: in Row 7
24344. 00000 - "success with compilation error"
*Cause: A sql/plsql compilation error occurred.
*Action: Return OCI_SUCCESS_WITH_INFO along with the error code
And The PROCEDURE Itselfs Contains this:
create or replace
PROCEDURE MISSINGTABLES AS BEGIN INSERT INTO MISSINGTABLE (SELECT TABLE_NAME, 'Diese Tabelle fehlt PEKA_ERP_001' Beschreibung FROM ALL_TAB_COLUMNS WHERE OWNER = 'ASE_ERP_001') END;
But it should not Contain "Create or Replace Procedure MISSINGTABLES" etc. only the INSERT STatement, I cannot execute the Procedure anyway..
even better would be to use the script from bpgergo, if it would go.
I hope I did not mix the arguments up, you should check them again
CREATE OR REPLACE PROCEDURE MISSINGTABLES (p_1 in varchar2, p_2 in varchar2)
AS
BEGIN
INSERT INTO MISSINGTABLE
((((SELECT TABLE_NAME, 'Missing Table on '||p_1 Description FROM ALL_TABLES WHERE OWNER = p_2)
MINUS
(SELECT TABLE_NAME, 'Missing Table on '||p_1 Description FROM ALL_TABLES WHERE OWNER = p_1))
UNION
((SELECT TABLE_NAME, 'Missing Table on '||p_2 Description FROM ALL_TABLES WHERE OWNER = p_1)
MINUS
(SELECT TABLE_NAME, 'Missing Table on '||p_2 Description FROM ALL_TABLES WHERE OWNER = p_2))));
END;
EDIT
you would call this like:
begin
MISSINGTABLES ('PEKA_ERP_001', 'ASE_ERP_001');
end;
The SQL that you are trying to execute immediate will be evaluated as:
CREATE OR REPLACE PROCEDURE MISSINGTABLES AS
BEGIN
INSERT INTO MISSINGTABLE
(SELECT TABLE_NAME, COLUMN_NAME, 'Missing Table on PEKA_ERP_001' Beschreibung
FROM ALL_TAB_COLUMNS WHERE OWNER = 'ASE_ERP_001')
END;
This probably isn't the logic that you actually want, but the immediate problem is that you are trying to populate a non-existant third column called Beschreibung instead of populating the second column, DESCRIPTION .
Might I suggest an improvement to your SELECT?
Here's a possible alternative:
SELECT
TABLE_NAME,
'Missing Table on'
|| CASE MAX(OWNER) WHEN 'PEKA_ERP_001' THEN 'ASE_ERP_001' ELSE 'PEKA_ERP_001' END
AS Description
FROM ALL_TABLES
WHERE OWNER IN ('PEKA_ERP_001', 'ASE_ERP_001')
GROUP BY TABLE_NAME
HAVING COUNT(*) = 1
This query returns only rows where a TABLE_NAME has just one OWNER. The owner that is missing the table is then shown to be as the other one of the two being tested.
Using parameters, the entire CREATE PROCEDURE statement might look like this:
CREATE OR REPLACE PROCEDURE MISSINGTABLES
(
owner1 IN varchar2,
owner2 IN varchar2
)
AS
BEGIN
INSERT INTO MISSINGTABLE
(
SELECT
TABLE_NAME,
'Missing Table on'
|| CASE MAX(OWNER) WHEN owner1 THEN owner2 ELSE owner1 END
AS Description
FROM ALL_TABLES
WHERE OWNER IN (owner1, owner2)
GROUP BY TABLE_NAME
HAVING COUNT(*) = 1
);
END;