SQL Variable, How to do it? - sql

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;

Related

dynamic SQL ERROR: column "age" does not exist

postgres 12
I am trying to loop through a table which has schema , table_names and columns
I want to do various things like finding nulls ,row count etc. I failed at the first hurdle trying to update the col records.
table i am using
CREATE TABLE test.table_study (
table_schema text,
table_name text,
column_name text,
records int,
No_Nulls int,
No_Blanks int,
per_pop int
);
I populate the table with some schema names ,tables and columns from information_schema.columns
insert into test.table_study select table_schema, table_name, column_name
from information_schema.columns
where table_schema like '%white'
order by table_schema, table_name, ordinal_position;
I want to populate the rest with a function
function :-
CREATE OR REPLACE PROCEDURE test.insert_data_population()
as $$
declare s record;
declare t record;
declare c record;
BEGIN
FOR s IN SELECT distinct table_schema FROM test.table_study
LOOP
FOR t IN SELECT distinct table_name FROM test.table_study where table_schema = s.table_schema
loop
FOR c IN SELECT column_name FROM test.table_study where table_name = t.table_name
LOOP
execute 'update test.table_study set records = (select count(*) from ' || s.table_schema || '.' || t.table_name || ') where table_study.table_name = '|| t.table_name ||';';
END LOOP;
END LOOP;
END LOOP;
END;
$$
LANGUAGE plpgsql;
I get this error SQL Error [42703]: ERROR: column "age" does not exist. the table age does exist.
when I take out the where clause
execute 'update referralunion.testinsert ti set records = (select count(*) from ' || s.table_schema || '.' || t.table_name || ') ;';
it works, I just cant figure out whats wrong?
Your procedure is structured entirely wrong. What it results in is an attempt to get every column name for every table name in every schema. I would guess results in your column does not exist error. Further is shows procedural thinking. SQL requires think in terms of sets. Below I use basically your query to demonstrate then a revised version which uses a single loop.
-- setup (dropping schema references)
create table table_study (
table_schema text,
table_name text,
column_name text,
records int,
no_nulls int,
no_blanks int,
per_pop int
);
insert into table_study(table_schema, table_name, column_name)
values ('s1','t1','age')
, ('s2','t1','xyz');
-- procedure replacing EXECUTE with Raise Notice.
create or replace procedure insert_data_population()
as $$
declare
s record;
t record;
c record;
line int = 0;
begin
for s in select distinct table_schema from table_study
loop
for t in select distinct table_name from table_study where table_schema = s.table_schema
loop
for c in select column_name from table_study where table_name = t.table_name
loop
line = line+1;
raise notice '%: update table_study set records = (select count(*) from %.% where table_study.table_name = %;'
, line, s.table_schema, t.table_name, c.column_name;
end loop;
end loop;
end loop;
end;
$$
language plpgsql;
Run procedure
do $$
begin
call insert_data_population();
end;
$$;
RESULTS
1: update table_study set records = (select count(*) from s2.t1 where table_study.table_name = age; 2: update table_study set records = (select count(*) from s2.t1 where table_study.table_name = xyz; 3: update table_study set records = (select count(*) from s1.t1 where table_study.table_name = age; 4: update table_study set records = (select count(*) from s1.t1 where table_study.table_name = xyz;
Notice lines 2 and 3. Each references a column name that does not exist in the table. This results from the FOR structure with the same table name in different schema.
Revision for Single Select statement with Single For loop.
create or replace
procedure insert_data_population()
language plpgsql
as $$
declare
s record;
line int = 0;
begin
for s in select distinct table_schema, table_name, column_name from table_study
loop
line = line+1;
raise notice '%: update table_study set records = (select count(*) from %.% where table_study.table_name = %;'
, line, s.table_schema, s.table_name, s.column_name;
end loop;
end;
$$;
do $$
begin
call insert_data_population();
end;
$$;
RESULTS
1: update table_study set records = (select count(*) from s2.t1 where table_study.table_name = xyz;
2: update table_study set records = (select count(*) from s1.t1 where table_study.table_name = age;
Note: In Postgres DECLARE begins a block. It is not necessary to declared each variable. I would actually consider it bad practice. In theory it could require an end for each declare as each could be considered a nested block. Fortunately Postgres does not require this.

How to refresh all virtual tables in HANA?

I create a stored procedure with a cursor for looping over each virtual table in the system.
CREATE OR REPLACE PROCEDURE "Basis.db::sp_basis_alter_vt_2"( )
AS
OBJECT_NAME nvarchar(500);
BEGIN
DECLARE OBJECT_ELEMENT_NAME nvarchar(500);
DECLARE CURSOR v_Cursor
FOR SELECT CONCAT(OBJECT_NAME, '"') AS OBJECT_NAME FROM(
SELECT CONCAT(OBJECT_NAME, TABLE_NAME) AS OBJECT_NAME FROM(
SELECT CONCAT(OBJECT_NAME, '"."') AS OBJECT_NAME, TABLE_NAME FROM (
SELECT CONCAT('"', SCHEMA_NAME) AS OBJECT_NAME, TABLE_NAME FROM "PUBLIC"."TABLES" WHERE TABLE_NAME LIKE 'VT_%')));
OPEN v_Cursor;
FETCH v_Cursor into OBJECT_ELEMENT_NAME;
FOR cur_row AS v_CURSOR DO
ALTER VIRTUAL TABLE cur_row.OBJECT_NAME REFRESH DEFINITION;
END FOR;
CLOSE v_Cursor;
END;
The problem currently is, that cur_row.OBJECT_NAME isn't recognized as a table entry but as schema name.
How can I refresh all Virtual Tables in HANA Cloud?
Error output is:
Could not execute 'CREATE OR REPLACE PROCEDURE "Basis.db::sp_basis_alter_vt_2"( ) AS OBJECT_NAME ...'
Error: (dberror) [257]: sql syntax error: incorrect syntax near "REFRESH": line 15 col 42 (at pos 640)
It seems like this solution worked out for me.
Thank you Lars, for your revision!
CREATE OR REPLACE PROCEDURE "Basis.db::sp_basis_alter_vt_2"( )
AS
OBJECT_NAME nvarchar(517);
BEGIN
DECLARE CURSOR virt_tables FOR
SELECT
'"' || SCHEMA_NAME || '"."' || TABLE_NAME || '"' AS OBJECT_NAME
FROM
"PUBLIC"."TABLES"
WHERE
TABLE_NAME LIKE 'VT_%';
FOR vtab AS virt_tables DO
EXECUTE IMMEDIATE 'ALTER VIRTUAL TABLE ' || vtab.OBJECT_NAME || ' REFRESH DEFINITION';
END FOR;
END;

Oracle- creating dynamic function for deleting tables based on cursor

I'm trying to build a dynamic function in Oracle using a cursor for all the tables that need to be dropped and re-created again. For example, I have the following example table structure:
CREATE TABLE All_tmp_DATA AS
(SELECT 'T_tmp_test1' As Table_NM, 'TEST1' As Process_name FROM DUAL UNION ALL
SELECT 'T_tmp_test2' As Table_NM, 'TEST1' As Process_name FROM DUAL UNION ALL
SELECT 'T_tmp_test3' As Table_NM, 'TEST1' As Process_name FROM DUAL)
The above tables starting with "T_tmp" represent all the tables in the database which needs to be dropped if their counts are >1 when starting the TEST1 process. I really need a function to pass in the parameter Process_name where I can input "TEST1", and build a loop using a cursor by binding it to the Table_NM from All_tmp_DATA and inserting it into table_name in the following code:
BEGIN
SELECT count(*)
INTO l_cnt
FROM user_tables
WHERE table_name = 'MY_TABLE';
IF l_cnt = 1 THEN
EXECUTE IMMEDIATE 'DROP TABLE my_table';
END IF;
END;
In the beginning, I'd suggest you not to use mixed case when naming Oracle objects.
Test case:
SQL> select * From all_tmp_data;
TABLE_NM PROCE
----------- -----
T_tmp_test1 TEST1
T_tmp_test2 TEST1
T_tmp_test3 TEST1
SQL> create table "T_tmp_test1" as select * From dept;
Table created.
SQL> -- I don't have "T_tmp_test2"
SQL> create table "T_tmp_test3" as select * From emp;
Table created.
SQL>
SQL> select table_name From user_Tables where upper(table_name) like 'T_TMP%';
TABLE_NAME
------------------------------
T_tmp_test3
T_tmp_test1
Procedure which drops tables contained in ALL_TMP_DATA:
as opposed to your code, I concatenated table name with DROP
as you use table names with mixed case, you have to enclose their names into double quotes, always (did I say not do use that?)
As the final select shows, those tables don't exist any more.
SQL> declare
2 l_cnt number;
3 begin
4 for cur_r in (select table_nm from all_tmp_data) loop
5 select count(*) into l_cnt
6 from user_tables
7 where table_name = cur_r.table_nm;
8
9 if l_cnt > 0 then
10 execute immediate ('drop table "' || cur_r.table_nm || '"');
11 end if;
12 end loop;
13 end;
14 /
PL/SQL procedure successfully completed.
SQL> select table_name From user_Tables where upper(table_name) like 'T_TMP%';
no rows selected
SQL>
As of the process column: I have no idea what is it used for so I did exactly that - didn't use it.
You can use the exception handling to handle such scenario directly as follows:
DECLARE
TABLE_DOES_NOT_EXIST EXCEPTION;
PRAGMA EXCEPTION_INIT ( TABLE_DOES_NOT_EXIST, -00942 );
BEGIN
FOR CUR_R IN (
SELECT TABLE_NM
FROM ALL_TMP_DATA
) LOOP
BEGIN
EXECUTE IMMEDIATE 'drop table "' || cur_r.table_nm || '"';
DBMS_OUTPUT.PUT_LINE('"' || cur_r.table_nm || '" table dropped.');
EXCEPTION
WHEN TABLE_DOES_NOT_EXIST THEN
DBMS_OUTPUT.PUT_LINE('"' || cur_r.table_nm || '" table does not exists');
END;
END LOOP;
END;
/

Inserting row values into another table's column

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.

Catching an exception while altering a table in Oracle

I'm trying to write a command in Oracle that will wither ADD or MODIFY a column depending on whether or not it already exists. Basically something like:
BEGIN
ALTER TABLE MY_TABLE ADD ( COL_NAME VARCHAR2(100 );
EXCEPTION WHEN OTHERS THEN
ALTER TABLE MY_TABLE MODIFY ( COL_NAME VARCHAR2(100) );
END;
However, Oracle complains about having the ALTER command inside of BEGIN. Is there a way to achieve this using a single SQL command in Oracle?
Thanks!
In order to put DDL in a PL/SQL block, you would need to use dynamic SQL.
Personally, I'd check whether the column exists first and then issue the DDL. Something like
DECLARE
l_cnt INTEGER;
BEGIN
SELECT COUNT(*)
INTO l_cnt
FROM dba_tab_cols
WHERE table_name = 'MY_TABLE'
AND owner = <<owner of table>>
AND column_name = 'COL_NAME';
IF( l_cnt = 0 )
THEN
EXECUTE IMMEDIATE 'ALTER TABLE my_table ADD( col_name VARCHAR2(100) )';
ELSE
EXECUTE IMMEDIATE 'ALTER TABLE my_table MODIFY( col_name VARCHAR2(100) )';
END IF;
END;
If you don't have access to DBA_TAB_COLS, you could also use ALL_TAB_COLS or USER_TAB_COLS depending on what schema the table resides in and what privileges you have on the table.
I found a solution based on this post.
DECLARE v_column_exists number := 0;
BEGIN
SELECT COUNT(*) INTO v_column_exists
FROM ALL_TAB_COLUMNS
WHERE TABLE_NAME = 'MY_TABLE'
AND COLUMN_NAME = 'COL_NAME';
IF (v_column_exists = 0) THEN
EXECUTE IMMEDIATE 'ALTER TABLE MY_TABLE ADD ( COL_NAME VARCHAR2(200) )';
ELSE
EXECUTE IMMEDIATE 'ALTER TABLE MY_TABLE MODIFY ( COL_NAME VARCHAR2(200) )';
END IF;
END;