I have a table with 100 columns called like col_1, col_2, .. col_100
is there a way to select values of that columns of single into an array of 100 elements?
(Oracle 10.2)
you could just select them like:
SQL> create type foo as table of number; -- or varray, as you wish.
2 /
Type created.
SQL> select foo(l.a, l.b, l.c) foo from your_tab l;
FOO
-----------------
FOO(1, 2, 3)
etc..
Here's a brute force method. There's probably a more elegant way, or at least one that will cut down on typing. The example uses five columns rather than 100.
DECLARE
-- Change VARCHAR2(10) in the next line to your col_1 .. col_100 type
TYPE My100Array IS TABLE OF VARCHAR2(10) INDEX BY PLS_INTEGER;
myVals My100Array;
indx NUMBER;
BEGIN
SELECT 'These', 'are', 'the', 'column', 'values'
INTO myVals(1), myVals(2), myVals(3), myVals(4), myVals(5)
FROM DUAL;
FOR INDX IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE(indx || ': ' || myVals(indx));
END LOOP;
END;
Here's the output when I run this:
1: These
2: are
3: the
4: column
5: values
Of course, this will be a bit tough with 100 columns, but once you get the query out of the way you'll have the array as you want it.
Another example:
DECLARE
CURSOR c_data IS
SELECT * FROM scott.emp; -- replace emp table with your_table
TYPE t_source_tab IS TABLE OF scott.emp%ROWTYPE;
l_tab t_source_tab;
BEGIN
SELECT * BULK COLLECT INTO l_tab FROM scott.emp;
-- display values in array --
FOR i IN l_tab.FIRST ..l_tab.LAST
LOOP
DBMS_OUTPUT.PUT_LINE (l_tab(i).hiredate ||chr(9)||l_tab(i).empno ||chr(9)||l_tab(i).ename);
END LOOP;
END;
/
sounds like you want to unpivot your data..
unfortunately UNPIVOT was only added in 11g (not 10.2)
you could manually unpivot but one of the other solutions would work better i think.
However, if you were on 11g or later you could try this
create table my_table (col1 number,col2 number, col3 number);
Table MY_TABLE created.
insert into my_table values (4,5,6);
1 row inserted.
select * from my_table;
COL1 COL2 COL3
---------- ---------- ----------
4 5 6
select val from my_table unpivot ( val for col in ( col1,col2,col3));
VAL
----------
4
5
6
from there is trivial to select into an single column array
DECLARE
CURSOR c_data IS
select val from my_table unpivot ( val for col in ( col1,col2,col3));
TYPE t_source_tab IS TABLE OF c_data%ROWTYPE;
l_tab t_source_tab;
BEGIN
open c_data;
fetch c_data bulk collect into l_tab;
close c_data;
-- display values in array --
FOR i IN l_tab.FIRST ..l_tab.LAST
LOOP
DBMS_OUTPUT.PUT_LINE (l_tab(i).val);
END LOOP;
END;
/
Related
I would like to construct a query where a table name is based off of another table's column mod 12. For example:
SELECT *
FROM table_b_XX
where XX here is determined by table_a.column_a % 12.
Presuming you have such a tables:
SQL> create table table_a as
2 select 1212 as column_a from dual;
Table created.
As the following result returns 0, we need table_b_00 so I'll create it:
SQL> select mod(1212, 12) from dual;
MOD(1212,12)
------------
0
SQL> create table table_b_00 as select 'table 00' name from dual;
Table created.
SQL> create table table_b_01 as select 'table 01' name from dual;
Table created.
Now, create a function which returns ref cursor; it selects rows from a table whose name is designed by the help of the table_a contents:
SQL> create or replace function f_test return sys_refcursor
2 is
3 l_str varchar2(200);
4 rc sys_refcursor;
5 begin
6 select 'select * from table_b_' || lpad(mod(a.column_a, 12), 2, '0')
7 into l_str
8 from table_a a;
9
10 open rc for l_str;
11 return rc;
12 end f_test;
13 /
Function created.
Let's try it:
SQL> select f_test from dual;
F_TEST
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
NAME
--------
table 00
Right; that's contents of table_b_00.
Consider the following meta code:
DECLARE
n VARCHAR2(32767);
r VARCHAR2(32767);
BEGIN
SELECT column_a INTO name FROM table_a;
EXECUTE IMMEDIATE 'SELECT r FROM table_b_'||n INTO r;
END;
/
For example I had a table named car with two column(col1,col2)
For now I would like insert some values inside the column like:
('Super car','Yellow car')
('BMW5','XL')
('Benz','AGM')
so I would like write a cursor to return ('BMW5','XL') in one single column, how do I do that?(I'm using sql developer)
I would appreciate any suggestion! Thank you!
declare
cursor mycursor is select concat(col1,col2) from car where REGEXP_LIKE(left, '^[[:digit:]]+$')
begin
for counter in mycursor
loop
dbms_output.put_line(counter.concat);
endloop;
end
You can use Concat() function in your query inside the cursor i.e.
CONCAT returns Col1 concatenated with Col2
select concat(col1,col2)
from car where <<conditions if any>>
You can write above query in Cursor like
DECLARE
CURSOR car_cursor IS select concat(col1,col2)
from car WHERE REGEXP_LIKE(col1, '[[:digit:]]');
cv_col1_col2 VARCHAR2 ;
BEGIN
OPEN car_cursor;
LOOP
FETCH car_cursor INTO cv_col1_col2;
Dbms_output.put_line('Concated Name' || cv_col1_col2)
END LOOP
CLOSE car_cursor;
END;
This is how I understood the question (though, more through by description than the title as they aren't related much).
Sample data:
SQL> create table car (col1 varchar2(10), col2 varchar2(10));
Table created.
SQL> insert into car
2 select 'Super car', 'Yellow car' from dual union all
3 select 'BMW5', 'XL' from dual union all
4 select 'Benz', 'AGM' from dual;
3 rows created.
PL/SQL code that uses a cursor FOR loop, returning concatenated col1 and col2 values for rows in which either of those columns contains a digit:
SQL> set serveroutput on;
SQL> begin
2 for cur_r in (select col1 ||' '|| col2 result
3 from car
4 where regexp_like(col1 || col2, '\d') -- any column contains
5 ) -- a digit
6 loop
7 dbms_output.put_line(cur_r.result);
8 end loop;
9 end;
10 /
BMW5 XL
PL/SQL procedure successfully completed.
SQL>
I have a table (let's name it source_tab) where I store list of all database tables that meet some criteria.
tab_name: description:
table1 some_desc1
table2 some_desc2
Now I need to execute a select statement on each of these tables and return a result as a table (I created custom TYPE). However I have a problem - when using bulk collect, only the last select statement is returned. The same issue was with open cursor. Is there any possibility to achieve this goal, another then concatenating all select statements using union all and executing it as one statement? And because I'm the begginer in sql, my second question is, is it ok to use this dynamic sql in terms of sql injection issues? Below is simplified version of my code:
CREATE OR REPLACE FUNCTION my_function RETURN newly_created_table_type IS
ret_tab_type newly_created_table_type;
BEGIN
for r in (select * from source_tab)
loop
execute immediate 'select value1, value2,''' || r.tab_name || ''' from ' || r.tab_name bulk collect into ret_tab_type;
end loop;
return ret_tab_type;
END;
I'm using Oracle 11.
In your case you are trying to populate a collection dynamically and wanted result in a single collection. In your case its not possible to do that in a single loop. Also as mentioned by #OldProgrammer, piperow would be a better solution from performance point. See below demo:
--Tables and Values:
CREATE TABLE SOURCE_TAB(TAB_NAME VARCHAR2(100), DESCRIPTION VARCHAR2(100));
/
SELECT * FROM SOURCE_TAB;
/
INSERT INTO SOURCE_TAB VALUES('table1','some_desc1');
INSERT INTO SOURCE_TAB VALUES('table2','some_desc2');
/
CREATE TABLE TABLE1(COL1 NUMBER, COL2 NUMBER);
/
INSERT INTO TABLE1 VALUES(1,2);
INSERT INTO TABLE1 VALUES(3,4);
INSERT INTO TABLE1 VALUES(5,6);
/
Select * from TABLE1;
/
CREATE TABLE TABLE2(COL1 NUMBER, COL2 NUMBER);
/
INSERT INTO TABLE2 VALUES(7,8);
INSERT INTO TABLE2 VALUES(9,10);
INSERT INTO TABLE2 VALUES(11,12);
/
Select * from TABLE2;
/
--Object Created
--UDT
CREATE OR REPLACE TYPE NEWLY_CREATED_TABLE_TYPE IS OBJECT (
VALUE1 NUMBER,
VALUE2 NUMBER
);
/
--Type of UDT
CREATE OR TYPE NEWLY_CRTD_TYP AS TABLE OF NEWLY_CREATED_TABLE_TYPE;
/
--Function:
--Function
CREATE OR REPLACE FUNCTION MY_FUNCTION
RETURN NEWLY_CRTD_TYP PIPELINED
AS
CURSOR CUR_TAB
IS
SELECT *
FROM SOURCE_TAB;
RET_TAB_TYPE NEWLY_CRTD_TYP;
BEGIN
FOR I IN CUR_TAB
LOOP
--Here i made sure that all the tables have col1 & col2 columns since you are using dynamic sql.
EXECUTE IMMEDIATE 'select NEWLY_CREATED_TABLE_TYPE(COL1, COL2) from '|| I.TAB_NAME
BULK COLLECT INTO RET_TAB_TYPE;
EXIT WHEN CUR_TAB%NOTFOUND;
FOR REC IN 1 .. RET_TAB_TYPE.COUNT
LOOP
PIPE ROW (RET_TAB_TYPE (REC) );
END LOOP;
END LOOP;
RETURN;
END;
/
Output:
SQL> Select * from table(MY_FUNCTION);
VALUE1 VALUE2
---------- ----------
1 2
3 4
5 6
7 8
9 10
11 12
6 rows selected.
May be you can combine all the queries into one using UNION ALL before execution, if the number and type of columns to be retrieved from all the tables are identical.
CREATE OR REPLACE FUNCTION my_function
RETURN newly_created_table_type
IS
ret_tab_type newly_created_table_type;
v_query VARCHAR2 (4000);
BEGIN
SELECT LISTAGG (' select VALUE1,VALUE2 FROM ' || tab_name, ' UNION ALL ')
WITHIN GROUP (ORDER BY tab_name)
INTO v_query
FROM source_tab;
EXECUTE IMMEDIATE v_query BULK COLLECT INTO ret_tab_type;
RETURN ret_tab_type;
END;
You could then use a single select statement to get all the values.
select * FROM TABLE ( my_function );
I have a bash script in which I would like to do such a query in SqlPlus
CREATE TABLE tab1(digits VARCHAR2(100));
INSERT INTO tab1(digits) VALUES (5,6);
COMMIT;
#!/bin/bash
.
.
DECLARE
lv_digits VARCHAR2(100):='';
BEGIN
SELECT digits INTO digits FROM tab1;
FOR i IN (SELECT column1 FROM tab2 WHERE column_id IN (lv_digits) AS text);
LOOP
DBMS_OUTPUT.PUT_LINE(i.text);
END LOOP;
END;
/
I don't know how to properly enter a condition into WHERE to return a value
How to manually introduc WHERE column_id IN (5,6) AS text it works correctly and the value must be loaded from another table with a column that is VARCHAR2.
DECLARE
lv_digits VARCHAR2(100):='';
BEGIN
SELECT digits INTO digits FROM tab1;
FOR i IN (SELECT column1 FROM tab2 WHERE column_id IN (5,6) AS text);
LOOP
DBMS_OUTPUT.PUT_LINE(i.text);
END LOOP;
END;
/
Does anyone have any idea how to convert this?
This can be useful to someone
DECLARE
lv_digits VARCHAR2(100):='';
BEGIN
SELECT digits INTO digits FROM tab1;
FOR i IN (SELECT column1 FROM tab2 WHERE column_id IN (select regexp_substr(digits,'[^,]+', 1, level) from karuzela_loop
connect by regexp_substr(digits, '[^,]+', 1, level) is not NULL) AS text);
LOOP
DBMS_OUTPUT.PUT_LINE(i.text);
END LOOP;
END;
/
#mathguy thanks for the tips
I have a column in a table which is varray of varchar2. After fetching this column value I want to process each element of this varray column. How to split the retrieved column into individual values.
This might help you:
CREATE TABLE t (id NUMBER, val VARCHAR2(20));
insert into t values (1,'val1');
INSERT INTO t VALUES (2,'val2');
INSERT INTO t VALUES (3, 'val3');
SET serveroutput ON
DECLARE
type my_type IS varray(200) OF VARCHAR2(200);
obj1 my_type := my_type();
BEGIN
FOR i IN 1..3 LOOP
obj1.extend;
SELECT val INTO obj1(i) FROM t WHERE id = i;
end loop;
FOR j IN obj1.first..obj1.last LOOP
dbms_output.put_line(obj1(j));
END LOOP;
END;
results:
val1
val2
val3
or you can use the following folowing for nested table columns:
FOR REC IN
(SELECT * FROM TABLE(c) --or select * from table(cast(c as object_type_tab))
)
LOOP
dbms_output.put_line(rec.id || ', ' || rec.val);
END LOOP;