generic stored procedure in oracle - sql

I want to write a PLSQL stored procedure that accepts a table name as argument. This table is source table. Now inside my procedure i want to manipulate the fields of that table.
EX: I want to insert the records of this source table into another target table whose name is XYZ_<source table name>. The column names for source and target tables are the same. But there may be some extra fields in target table. How do i do it? The order of column names is not same.

You will have to build the INSERT statement dynamically.
create or replace procedure gen_insert
(p_src_table in user_tables.table_name%type
, p_no_of_rows out pls_integer)
is
col_str varchar2(16000);
begin
for rec in ( select column_name
, column_id
from user_tab_columns
where table_name = p_src_table
order by column_id )
loop
if rec.column_id != 1 then
col_str := col_str || ',' || rec.column_name;
else
col_str := rec.column_name;
end if:
end loop;
execute immediate 'insert into xyz_' || p_src_table || '('
|| col_str || ')'
|| ' select ' || col_str
|| ' from ' || p_src_table;
p_no_of_rows := sql%rowcount;
end;
/
Obviously you may want to include some error handling and other improvements.
edit
Having edited your question I see you have a special requirement for naming the target table which was obscured by the SO formatting.

You can do this using Dynamic SQL. Here's a link with basic info on Oracle Dynamic SQL

Related

snowflake procedure syntax error while querying information schema

Idea is I am trying to query information schema metadata and build columns based on datatypes if date then I create min date max date ,if number then check count of distinct or count rows
I have simplified now I will pass dbname , schema name and table name as parameters,
My output should return with below columns
SCHEMA_NM,TBL_NAME,_COUNT,_DISTINCT_COUNT,_MIN_DATE,_MAX_DATE.
For testing purpose at least if two measure is syntactically correct remaining I will take care
CREATE OR REPLACE PROCEDURE PROFILING( DB_NAME VARCHAR(16777216),TBL_SCHEMA VARCHAR(16777216), TBL_NAME VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE SQL
EXECUTE AS CALLER
AS
$$
DECLARE
BEGIN
create or replace temporary table tbl_name as (select case when data_type=NUMBER then (execute immediate 'select count(col_val) from ' || :1 || '.' || :2 || '.' || :3) else null end as col_value_num,case when data_type=DATE then (execute immediate 'select count(col_val) from ' || :1 || '.' || :2 || '.' || :3) else null end as col_min_date from ':1.information_schema.columns where table_catalog=:1 and table_schema=:2 and table_name=:3 ' )) ;
insert into some_base_table as select * from tbl_name;
truncate tbl_name
RETURN 'SUCCESS';
END;
$$;
With above query I am getting below error
error : SQL compilation error: Invalid expression value (?SqlExecuteImmediateDynamic?) for assignment.
Any help here please
There are multiple errors in your code, but the error you mentioned is about this line:
num := (execute immediate "select count(col_val) from tab_cat.tab_schema.tab_name") ;
NUM is declared as integer, you can't directly assign a value from execute immediate. Execute immediate statement returns a resultset. To access the value you need to define a cursor and fetch the data.
The SQL should be surrounded by single quotes (not double quotes), and you should also build the string correctly. Something like this:
result := (execute immediate 'select count(col_val) from ' || tab_cat || '.' || tab_schema || '.' || tab_name ) ;

How to create a view in a FOR loop in Oracle SQL

What I'm trying to do is create views based off a condition between two tables, and I want it to go through all tables that meet this condition.
I've been doing some research and I found that cursors would be helpful for this sort of thing, but I've been running into a "cursor out of scope" at line 15.
DECLARE
query_str VARCHAR2(32000);
CURSOR all_syn IS
SELECT SYNONYM_NAME, TABLE_NAME
FROM ALL_SYNONYMS
WHERE SYNONYM_NAME LIKE 'S!_AG!_%' ESCAPE '!';
CURSOR our_tables IS
SELECT TABLE_NAME
FROM ALL_TABLES
WHERE TABLE_NAME LIKE 'AG!_%1' ESCAPE '!';
BEGIN
query_str := 'CREATE OR REPLACE VIEW ' || LTRIM(all_syn.SYNONYM_NAME, 'S_') || 'AS
SELECT TO_CHAR(itemnum) itemnum,
TO_CHAR(keywordnum) keywordnum,
TO_CHAR(keysetnum) keysetnum,
MOD_BY_EMPLOYEE,
MOD_BY_PROCESS,
MOD_DATE_EMPLOYEE,
MOD_DATE_PROCESS
FROM all_syn.SYNONYM_NAME,
our_tables.TABLE_NAME
WHERE our_tables.TABLE_NAME = ' || LTRIM(all_syn.SYNONYM_NAME, 'S_');
FOR v_rec IN all_syn LOOP
IF (v_rec.TABLE_NAME LIKE 'KEYXITEM%') THEN
EXECUTE IMMEDIATE query_str;
END IF;
END LOOP;
END;
The reason I am doing this is because my company has tables that aren't directly connected to a certain 3rd party DB link, so they had me change the table names by putting a 1 at the end of the affected tables, creating synonyms for these tables with the DB link, and then make views of these synonyms with the original table name so that they now have the DB link and act as the original table so that we don't have to change any code. I have to join the synonym tables with the changed tables, because we added some attributes that the 3rd party tables don't have.
If anyone has any suggestions or advice, it would be greatly appreciated! I'm new to using dynamic sql and PL/SQL, so bear with me please.
EDIT:
So I've improved my code, and I feel like I'm getting closer to my desired results, however I'm getting this weird error:
line 28, column 52:
PLS-00357: Table,View Or Sequence reference 'ALL_TABLES.TABLE_NAME' not allowed in this context
Which doesn't make sense to me as I'm declaring it in the query.
BEGIN
FOR v_rec IN all_syn LOOP
IF (v_rec.TABLE_NAME LIKE 'KEYXITEM%') THEN
query_str := 'CREATE OR REPLACE VIEW ' || LTRIM(v_rec.SYNONYM_NAME, 'S_') || ' AS
SELECT itemnum AS item_num,
keywordnum AS key_word_num,
keysetnum AS key_set_num,
MOD_BY_EMPLOYEE,
MOD_BY_PROCESS,
MOD_DATE_EMPLOYEE,
MOD_DATE_PROCESS,
FROM ( SELECT TABLE_NAME
FROM ALL_TABLES
WHERE TABLE_NAME LIKE ' || '''AG!_%1''' || ' ESCAPE ' || '''!''' || '
AND ' || RTRIM(ALL_TABLES.TABLE_NAME, '1') ||' = ' || LTRIM(v_rec.SYNONYM_NAME, 'S_') || ') our_tables,
' || v_rec.SYNONYM_NAME;
-- EXECUTE IMMEDIATE query_str;
END IF;
dbms_output.put_line(query_str);
END LOOP;
END;
You cannot reference cursor like that. Move the query_str creation inside the FOR LOOP and reference the record variable.
EDIT: I've tried to fix the FROM/WHERE clause, but you might be missing a join condition there.
DECLARE
query_str VARCHAR2(32000);
CURSOR all_syn IS
SELECT SYNONYM_NAME, TABLE_NAME
FROM ALL_SYNONYMS
WHERE SYNONYM_NAME LIKE 'S!_AG!_%' ESCAPE '!';
CURSOR our_tables IS
SELECT TABLE_NAME
FROM ALL_TABLES
WHERE TABLE_NAME LIKE 'AG!_%1' ESCAPE '!';
BEGIN
FOR v_rec IN all_syn LOOP
IF (v_rec.TABLE_NAME LIKE 'KEYXITEM%') THEN
query_str := 'CREATE OR REPLACE VIEW ' || LTRIM(v_rec.SYNONYM_NAME, 'S_') || 'AS
SELECT TO_CHAR(itemnum) itemnum,
TO_CHAR(keywordnum) keywordnum,
TO_CHAR(keysetnum) keysetnum,
MOD_BY_EMPLOYEE,
MOD_BY_PROCESS,
MOD_DATE_EMPLOYEE,
MOD_DATE_PROCESS
FROM ' || v_rec.SYNONYM_NAME || ',
' || v_rec.TABLE_NAME || '
WHERE ' || v_rec.TABLE_NAME = ' || LTRIM(v_rec.SYNONYM_NAME, 'S_');
EXECUTE IMMEDIATE query_str;
END IF;
END LOOP;
END;

SAP HANA execute query generated within a procedure

I am new with SAP HANA, I am trying to generate a query and execute it within a stored procedure.
I got an error and I am not sure that HANA can do something like that.
Here my code
CREATE PROCEDURE "PROCEDURE_IBA_TESTCSV"(
IN SCHEMA_NAME VARCHAR(100))
LANGUAGE SQLSCRIPT SQL SECURITY INVOKER AS
BEGIN
DECLARE T VARCHAR(1000);
DECLARE TA VARCHAR(1000);
SELECT
' SELECT ' || MAX(C_1) || IFNULL(MAX(C_2),'')|| IFNULL(MAX(C_3),'') ||' AS STATEMENT FROM ' || SCHEMA_NAME || '.' || TABLE_NAME || ' ' INTO T
FROM (
SELECT POSITION, DATA_TYPE_ID, COLUMN_NAME ,SCHEMA_NAME, TABLE_NAME ,
CASE WHEN POSITION = 1 THEN
' CASE WHEN ( '|| COLUMN_NAME ||' IS NULL ) THEN '''' ELSE REPLACE(TO_CHAR(' || COLUMN_NAME || '),''.'','','') END' END AS C_1,
CASE WHEN POSITION = 2 THEN '||''#''|| CASE WHEN ( '|| COLUMN_NAME ||' IS NULL ) THEN '''' ELSE TO_NVARCHAR('||COLUMN_NAME||') END' END AS C_2,
CASE WHEN POSITION = 3 THEN '||''#''|| CASE WHEN ( '|| COLUMN_NAME ||' IS NULL ) THEN '''' ELSE TO_NVARCHAR('||COLUMN_NAME||') END' END AS C_3
FROM (
select SCALE,SCHEMA_NAME,position,TABLE_NAME,column_name, data_type_id from TABLE_COLUMNS where
schema_name ='IMPORT_KT_STAMM_IK_348BA_20160706' AND TABLE_NAME='CLS_220_KTHISTORIE')) group by SCHEMA_NAME,TABLE_NAME;
execute immediate :T ;
INSERT INTO Test SELECT :T from DUMMY;
END;
With execute :T I get this output
I would like to store SUM(length) of this output into a variable within the same procedure.
Is that possible ? Any help ?
thanks in advance
Ok, now I understand, where this is going.
As you want to work with tables of different shape, you won't be able to avoid dynamic SQL altogether.
But since you always melt it into a single column, you could simply store that transformed data into, say a temporary table, and run the SUM(LENGTH(()) on that.
Not sure though why you want to go through this rather painful exercise, instead of simply exporting the data into some folder and checking the resulting size there.
I don't quite get why you use dynamic SQL here. With dynamic SQL (exec/execute immediate) you don't get access to the result set.
Alternatively you can use cursors.
You can provide parameters for SCHEMA_NAME and TABLE_NAME and be 'dynamic' that way.
I guess this question is related to SAP HANA getting csv data size right?
I modified my code:
I write "insert into Table SELECT " instead "SELECT" in line 8
and now I get data in table

How to Refer to a Column by ID or Index Number

In Oracle PL/SQL, I have run a query and am trying to read through each column for each row one by one so I can concatenate them together with a delimiter (hard format requirement). The script is used on multiple tables of varying sizes, so the number of columns is not known in advance. I used
SELECT COUNT(column_name) INTO NumColumns FROM all_tabs_cols
WHERE table_name = Table_Array(i);
where Table_Array has already been defined. This is in the middle of a for loop and has successfully gotten me a total number of columns. Table_Cursor is a SELECT * statement. After this I am trying to do something like
FOR j IN 0..NumColumns-1 LOOP
FETCH TABLE_CURSOR.column(j) INTO DataValue;
DBMS_OUTPUT.PUT(DataValue || '/');
END LOOP
The above is pseudo code. It illustrates the concept I am after. I do not know PL/SQL well enough to know how to get a value like this out of a row. I am also worried about accidentally advancing the cursor while doing this. How can I accomplish this task?
You must use some form of dynamic SQL. Here is a quick example:
It builds the SQL statement that will select the '/' separated columns from the table you want. Then it uses dynamic SQL to run that SQL statement.
DECLARE
p_table_name VARCHAR2(30) := 'DBA_OBJECTS';
l_sql VARCHAR2(32000);
TYPE varchar2tab IS TABLE OF VARCHAR2(32000);
l_array varchar2tab;
BEGIN
SELECT 'SELECT ' || listagg(column_name,' ||''/''||') within group ( order by column_id ) || ' FROM ' || owner || '.' || table_name || ' WHERE ROWNUM <= 100'
INTO l_sql
FROM dba_tab_columns
where table_Name = 'DBA_OBJECTS'
group by owner, table_Name;
EXECUTE IMMEDIATE l_sql BULK COLLECT INTO l_array;
FOR i in l_array.first .. l_array.last LOOP
dbms_output.put_line(l_array(i));
END LOOP;
END;
This is how your code should look:
SELECT F1 || ', ' || F2 || ', ' || ... || ', ' || FN
FROM TABLE
NO LOOPS
Here is how you can generate code that does not use loops.
Note, if you want you can take out the where statement and generate the code for the whole database.
Test with just one table first.
SELECT 'SELECT '|| LISTAGG(COLUMN_NAME, ' || '', '' || ') || ' FROM '||TABLE_NAME as sql_stm
FROM ALL_TAB_COLUMNS
WHERE TABLE_NAME='tablename'
GROUP BY TABLE_NAME;

Oracle Apex unique column alias on query generated by Pl/SQL

I am trying to get report which query is being dynamically pulled by PL/SQL block.
I got inspiration from
this article
number of columns is dynamic and depend on the loop:
declare
l_qry VARCHAR2(4300);
s_qry VARCHAR2(80) := 0;
v_resort_id NUMBER := 1;
begin
l_qry := 'select a.column1,';
FOR pci in ( select id,name from table_pci where resort_id = v_resort_id) LOOP
s_qry := s_qry||'package.some_function (a.id,''' || pci.id || ''' , ''PC'') Property_type,' ;
END LOOP;
l_qry := l_qry ||s_qry;
l_qry := l_qry||'a.column2 from features a where a.feature_type = ''condition1'' ';
return(l_qry);
end;
Property_type is hardcoded alias on the dynamic column, so everytime loop goes round it will try to generate column with the same name and Apex with flag it as error.If I select
Use Generic Column Names (parse query at runtime only) it return correct number of columns but named Col1,Col2,Col3...
If I try to grab something dynamic from table_pci like name, I tried:
s_qry := s_qry||'package.some_function (a.id,''' || pci.id || ''' , ''PC'') '''|| pci.name || ''',' ;
I get error
failed to parse SQL query:
ORA-00923: FROM keyword not found where expected
Any help with finding a way to dynamicaly name the column greatly appreicated.
Any pointers, any advices and links.
I think you might have a syntax error in your attempt to use a dynamic column alias.
Try:
s_qry := s_qry||'package.some_function (a.id,''' || pci.id || ''' , ''PC'') AS '|| pci.name || ',' ;
If the value in pci.name potentially has spaces in it them enclose it with double quotes:
s_qry := s_qry||'package.some_function (a.id,''' || pci.id || ''' , ''PC'') AS "'|| pci.name || '",' ;
Hope it helps...