How to select a table using a string in Oracle? - sql

First of all, I know the question is vague, so feel free to edit it if you can describe it better.
There are some sets of table like TEST_201812, TEST_201901, etc. . I have another table that stores these values:
TEST_DATE:
ID DATE
1 201810
2 201811
3 201812
4 201901
Now what I want is to select the tables mentioned above (e.g.TEST_201812) by using TEST_DATE. I know it's wrong, but something like this:
select * from TEST_(select DATE from TEST_DATE where ID = 1)
Does anyone know how to achieve this?

Seriously, such a data model is a disaster. If you want to keep separate months separately, use one - partitioned - table.
Anyway, here's one option of how to do that:
Sample tables and a function that returns refcursor:
SQL> create table test_201812 as select * From dept;
Table created.
SQL> create table test_date (id number, datum number);
Table created.
SQL> insert into test_date values (1, 201812);
1 row created.
SQL> create or replace function f_test (par_id in test_date.id%type)
2 return sys_refcursor
3 is
4 l_datum test_date.datum%type;
5 l_str varchar2(200);
6 l_rc sys_refcursor;
7 begin
8 select datum
9 into l_datum
10 from test_date
11 where id = par_id;
12
13 l_str := 'select * from test_' || l_datum;
14 open l_rc for l_str;
15 return l_rc;
16 end;
17 /
Function created.
Testing:
SQL> select f_test(1) from dual;
F_TEST(1)
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL>

Related

How to use CASE statement in FROM Clause to decide which table to be used for fetching data in Oracle?

I have two tables , HISTORY_DATA and CURRENT_DATA , I have an input parameter REPORT_DATE ,as per following Condition , I have to fetch data :
IF(REPORT_DATE<=TRUNC(SYSDATE-40))THEN
SCHD_TABLE:='HISTORY_DATA' ;
ELSE
SCHD_TABLE:='CURRENT_DATA';
END IF ;
I tried using dynamic SQL , but it is giving error as invalid table name .
SELECT * FROM ''||SCHD_TABLE||'' ;
Used CASE STATEMENT but it also gave Syntax error :
SELECT * FROM (CASE WHEN REPORT_DATE<=TRUNC(SYSDATE-40) THEN HISTORY_DATA
ELSE CURRENT_DATA
END)
Please guide how to resolve this .
Assuming that history_data and current_data have equivalent columns, you can use UNION ALL and two queries. Each query SELECTs everything from a table if and only if the condition depending on you variable in the WHERE clause is true. Since the conditions in the WHERE clauses are negations of each other, one query will return an empty set when the other returns something. So you'll only get the result from the table you want according to your condition.
SELECT *
FROM history_data
WHERE report_date <= trunc(sysdate - 40)
UNION ALL
SELECT *
FROM current_data
WHERE report_date > trunc(sysdate - 40);
And by the way, it's a CASE expression not a statement you have there.
One option is to use a function that returns refcursor. Here's an example.
First, sample tables:
SQL> create table history_data as
2 select deptno, ename, job from emp where deptno = 10;
Table created.
SQL> create table current_data as
2 select deptno, ename, job from emp where deptno = 20;
Table created.
Function returns data depending on par_report_date:
SQL> create or replace function f_test (par_report_date in date)
2 return sys_refcursor
3 is
4 rc sys_refcursor;
5 begin
6 if par_report_date <= trunc(sysdate) - 40 then
7 open rc for select * from history_data;
8 else
9 open rc for select * from current_data;
10 end if;
11 return rc;
12 end;
13 /
Function created.
Testing (history data):
SQL> select f_test(date '2021-02-15') history_data from dual;
HISTORY_DATA
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
DEPTNO ENAME JOB
---------- ---------- ---------
10 CLARK MANAGER
10 KING PRESIDENT
10 MILLER CLERK
Testing (current data):
SQL> select f_test(sysdate) current_data from dual;
CURRENT_DATA
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
DEPTNO ENAME JOB
---------- ---------- ---------
20 SMITH CLERK
20 JONES MANAGER
20 SCOTT ANALYST
20 ADAMS CLERK
20 FORD ANALYST
SQL>
Based on your comment (about dynamic SQL): I'm not sure what benefit you expect from it. Yes, you can "concatenate" appropriate table name to the select statement, but the outcome is just the same. For example:
SQL> create or replace function f_test (par_report_date in date)
2 return sys_refcursor
3 is
4 l_str varchar2(200);
5 rc sys_refcursor;
6 begin
7 l_str := 'select * from ' ||
8 case when par_report_date <= trunc(sysdate) - 40 then 'history_data'
9 else 'current_data'
10 end;
11 open rc for l_str;
12 return rc;
13 end;
14 /
Function created.
SQL> select f_test(date '2021-02-15') history_data from dual;
HISTORY_DATA
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
DEPTNO ENAME JOB
---------- ---------- ---------
10 CLARK MANAGER
10 KING PRESIDENT
10 MILLER CLERK
SQL>

Writing a PLSQL select in array

I'm using a DB 'A' to output a list of numbers :
123455
123456
123457
And I'm looking to build a dynamic statement to look into a DB 'B' with those results as a filter
a. Build an array with the values from DB 'A'
SELECT * FROM my_table
WHERE number in &array;
How can I achieve this ?
The DB 'B' is an Oracle DB.
Thanks
Hm. Looks like your "background" is not Oracle, because there are no "DB"s there. I mean, there are, but not in a context you're using them. If "DB" stands for a "Database", to me it looks as if you're actually talking about tables here.
Also, I don't understand what
The DB 'B' is in PLSQL means.
If "database" is a table, how is it in PL/SQL?
Anyway, to get you started: I'm fetching some data from Scott's EMP and DEPT tables. For collections, I'm using Oracle's built-in types.
These are employees in departments 10 and 20:
SQL> select deptno, ename
2 from emp
3 where deptno in (10, 20)
4 order by deptno, ename;
DEPTNO ENAME
---------- ----------
10 CLARK
10 KING
10 MILLER
20 ADAMS
20 FORD
20 JONES
20 SCOTT
20 SMITH
8 rows selected.
PL/SQL procedure which does something with them (the way I understood the question):
SQL> declare
2 l_a sys.odcinumberlist;
3 l_b sys.odcivarchar2list;
4 begin
5 select deptno
6 bulk collect into l_a
7 from dept
8 where deptno in (10, 20);
9
10 select ename
11 bulk collect into l_b
12 from emp
13 where deptno in (select * from table(l_a))
14 order by ename;
15
16 for i in l_b.first .. l_b.last loop
17 dbms_output.put_line(l_b(i));
18 end loop;
19 end;
20 /
ADAMS
CLARK
FORD
JONES
KING
MILLER
SCOTT
SMITH
PL/SQL procedure successfully completed.
SQL>
Lines #1 - 3 - declaration section
lines #5 - 8 - inserting values (departments) into l_a collection
Lines #10 - 14 - inserting values (employees) into l_b collection, based on values stored in l_a
Lines #16 - 18 - displaying contents of l_b
See if it helps.
[EDIT] After seeing your comment: as far as I can tell, you can't do what you wanted, not as simple as you'd want it to. This is how it works - you enter a comma-separated values as a parameter (that's your "array"), split it into rows and use the result as a subquery:
SQL> SELECT *
2 FROM dept
3 WHERE deptno IN ( SELECT REGEXP_SUBSTR ( '&&par_depts',
4 '[^,]+',
5 1,
6 LEVEL)
7 FROM DUAL
8 CONNECT BY LEVEL <= REGEXP_COUNT ( '&&par_depts', ',') + 1);
Enter value for par_depts: 10,20
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
SQL>
This is a SQL*Plus example; you'll probably have to substitute '&&par_depts' with :par_depts (depending on a tool you use).
Use the MEMBER operator.
First create a collection type in SQL:
CREATE TYPE int_list IS TABLE OF INT;
Then just use it in an SQL statement:
SELECT *
FROM my_table
WHERE value MEMBER OF int_list(123455, 123456, 123457);
Which, for the sample data:
CREATE TABLE my_table ( id, value ) AS
SELECT LEVEL, 123453 + LEVEL FROM DUAL CONNECT BY LEVEL <= 5;
Outputs:
ID
VALUE
2
123455
3
123456
4
123457
If you want it in PL/SQL then:
DECLARE
items int_list := int_list(123455, 123456, 123457);
BEGIN
FOR row IN (
SELECT *
FROM my_table
WHERE value MEMBER OF items
)
LOOP
DBMS_OUTPUT.PUT_LINE( row.id || ', ' || row.value );
END LOOP;
END;
/
Which, for the same data, outputs:
2, 123455
3, 123456
4, 123457
db<>fiddle here
However, if you just want to connect two databases then setup a database link.

SQL: Autogenerate generic id on record insert

I have developed a procedure that adds a consultant to a table.
I would like to add a procedure to the consultant ID so that everytime a consultant gets added to the table a generic id is added to the record.
How can I create this procedure?
create or replace PROCEDURE ADD_CONSULTANT
( p_con_id LDS_CONSULTANT.CONSULTANT_ID%type,
p_con_name LDS_CONSULTANT.CST_NAME%type,
p_con_start LDS_CONSULTANT.START_DATE%type,
p_con_end LDS_CONSULTANT.LEAVE_DATE%type,
p_con_loc LDS_CONSULTANT.LOCATION%type,
p_con_spec LDS_CONSULTANT.SPECIALIST_AREA%type)
IS
BEGIN
INSERT INTO LDS_CONSULTANT (CONSULTANT_ID, CST_NAME, START_DATE, LEAVE_DATE, LOCATION, SPECIALIST_AREA)
VALUES (p_con_id, p_con_name, p_con_start, p_con_end, p_con_loc, p_con_spec);
END;
You didn't mention which database version you use, so the answer & the solution you choose might differ.
A simple solution is to use a sequence. Here's an example. First, a table:
SQL> CREATE TABLE lds_consultant (
2 consultant_id NUMBER,
3 cst_name VARCHAR2(20),
4 start_date DATE,
5 leave_date DATE,
6 location VARCHAR2(20),
7 specialist_area VARCHAR2(20)
8 );
Table created.
A sequence:
SQL> CREATE SEQUENCE seq_cons;
Sequence created.
A procedure; I removed parameter which you originally used, as you don't need it any more.
SQL> CREATE OR REPLACE PROCEDURE add_consultant (
2 p_con_name lds_consultant.cst_name%TYPE,
3 p_con_start lds_consultant.start_date%TYPE,
4 p_con_end lds_consultant.leave_date%TYPE,
5 p_con_loc lds_consultant.location%TYPE,
6 p_con_spec lds_consultant.specialist_area%TYPE
7 )
8 IS
9 BEGIN
10 INSERT INTO lds_consultant (
11 consultant_id,
12 cst_name,
13 start_date,
14 leave_date,
15 location,
16 specialist_area
17 ) VALUES (
18 seq_cons.NEXTVAL, --> this
19 p_con_name,
20 p_con_start,
21 p_con_end,
22 p_con_loc,
23 p_con_spec
24 );
25 END;
26 /
Procedure created.
Let's test it:
SQL> BEGIN
2 add_consultant('Littlefoot',trunc(SYSDATE),NULL,'Croatia','IT');
3 END;
4 /
PL/SQL procedure successfully completed.
SQL> SELECT * FROM lds_consultant;
CONSULTANT_ID CST_NAME START_DATE LEAVE_DATE LOCATION SPECIALIST_AREA
------------- -------------------- ---------- ---------- -------------------- --------------------
1 Littlefoot 13.05.2018 Croatia IT
SQL>
Another option is a database trigger:
SQL> CREATE OR REPLACE TRIGGER trg_bi_cons BEFORE
2 INSERT ON lds_consultant
3 FOR EACH ROW
4 BEGIN
5 :new.consultant_id := seq_cons.nextval;
6 END;
7 /
Trigger created.
Unlike the previous example, you don't even need to reference the consultant_id any more as trigger does that job.
SQL> CREATE OR REPLACE PROCEDURE add_consultant (
2 p_con_name lds_consultant.cst_name%TYPE,
3 p_con_start lds_consultant.start_date%TYPE,
4 p_con_end lds_consultant.leave_date%TYPE,
5 p_con_loc lds_consultant.location%TYPE,
6 p_con_spec lds_consultant.specialist_area%TYPE
7 )
8 IS
9 BEGIN
10 INSERT INTO lds_consultant (
11 cst_name,
12 start_date,
13 leave_date,
14 location,
15 specialist_area
16 ) VALUES (
17 p_con_name,
18 p_con_start,
19 p_con_end,
20 p_con_loc,
21 p_con_spec
22 );
23
24 END;
25 /
Procedure created.
Testing:
SQL> BEGIN
2 add_consultant('Bigfoot',trunc(SYSDATE),NULL,'France','Fashion');
3 END;
4 /
PL/SQL procedure successfully completed.
SQL> SELECT * FROM lds_consultant;
CONSULTANT_ID CST_NAME START_DATE LEAVE_DATE LOCATION SPECIALIST_AREA
------------- -------------------- ---------- ---------- -------------------- --------------------
1 Littlefoot 13.05.2018 Croatia IT
2 Bigfoot 13.05.2018 France Fashion
SQL>
If you're on 12c database version, use the identity column:
CREATE TABLE lds_consultant (
consultant_id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,,
cst_name VARCHAR2(20),
start_date DATE,
leave_date DATE,
location VARCHAR2(20),
specialist_area VARCHAR2(20)
);
The procedure would look like the one in the second (trigger) example, i.e. you don't need to reference the consultant_id column. As I run 11g XE on my laptop, I can't post the execution, but I'm sure you can do it yourself if necessary (and , of course, if you're on 12c).

How to change PL/SQL function call when function is no longer pipelined?

I have PL/SQL function looking like:
FUNCTION get_agent_statistics ( id NUMBER
RETURN agent_stats_t
PIPELINED;
And I select from it (iBatis code):
SELECT * FROM table(pkg.get_agent_statistics(#id#))
How should I change this select if I'll remove PIPELINED statement from function?
If you'll get working compiled procedure without PIPELINED statement, you don't need to change your SELECT. See this - http://www.oracle-base.com/articles/misc/pipelined-table-functions.php
When you remove PIPELINED clause from the function declaration, function ceases to be a PIPELINED table function and as a result you will have to modify the body of the function to convert it to a TABLE function, if you still want to use it the from clause of the query, or a simple function, which you wont be able to use in the from clause of a query.
Addendum
Could I select something from non-pipelined function?
Yes, if you have a TABLE function, otherwise no. Here is a couple of examples:
-- prerequisites
SQL> create or replace type T_rows as object(
2 e_name varchar2(21),
3 e_lname varchar2(21)
4 )
5 /
Type created
SQL> create or replace type T_tab is table of t_rows
2 /
Type created
-- PIPELINED TABLE function
SQL> create or replace function GetEnames
2 return T_Tab
3 pipelined
4 is
5 l_etab t_tab := t_tab();
6 begin
7 for i in (select first_name
8 , last_name
9 from employees)
10 loop
11 pipe row(t_rows(i.first_name, i.last_name));
12 --l_etab.extend;
13 --l_etab(l_etab.last) := t_rows(i.first_name, i.last_name);
14 end loop;
15 return ;--l_etab;
16 end;
17 /
Function created
SQL> select *
2 from table(getenames)
3 where rownum <= 5;
E_NAME E_LNAME
--------------------- ---------------------
Steven King
Neena Kochhar
Lex De Haan
Alexander Hunold
Bruce Ernst
-- non-pipelined table function
SQL> create or replace function GetEnames
2 return T_Tab
3
4 is
5 l_etab t_tab := t_tab();
6 begin
7 for i in (select first_name
8 , last_name
9 from employees)
10 loop
11 --pipe row(t_rows(i.first_name, i.last_name));
12 l_etab.extend;
13 l_etab(l_etab.last) := t_rows(i.first_name, i.last_name);
14 end loop;
15 return l_etab;
16 end;
17 /
Function created
SQL> select *
2 from table(getenames)
3 where rownum <= 5;
E_NAME E_LNAME
--------------------- ---------------------
Steven King
Neena Kochhar
Lex De Haan
Alexander Hunold
Bruce Ernst
SQL>

How to call a function in a package

I'm doing the following but it doesnt work
select package_name.function_name(param,param) from dual
I'm calling a function that returns a cursor so im guessing "from dual" is the problem
is there another way of doing it?
I presume you mean a Ref Cursor. This is a PL/SQL construct which acts as a pointer to a set of records returned by a query. This means it has to be interpreted by the client which runs the query. For instance, we can map a Ref Cursor to a JDBC or ODBC ResultSet.
There is certainly nothing wrong with your basic statement. Here is a function similar to your own:
SQL> desc get_emps
FUNCTION get_emps RETURNS REF CURSOR
Argument Name Type In/Out Default?
------------------------------ ----------------------- ------ --------
P_DNO NUMBER(2) IN
P_SORT_COL VARCHAR2 IN DEFAULT
P_ASC_DESC VARCHAR2 IN DEFAULT
SQL>
I can easily call this in a wider PL/SQL block:
SQL> declare
2 rc sys_refcursor;
3 begin
4 rc := get_emps(50);
5 end;
6 /
PL/SQL procedure successfully completed.
SQL>
However, SQL*PLus can handle CURSOR constructs natively:
SQL> select get_emps(50) from dual
2 /
GET_EMPS(50)
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
8060 VERREYNNE PLUMBER 8061 08-APR-08 4000 50
8061 FEUERSTEIN PLUMBER 7839 27-FEB-10 4500 50
8085 TRICHLER PLUMBER 8061 08-APR-10 3500 50
8100 PODER PLUMBER 8061 3750 50
SQL>
This statement also runs in SQL Developer, although the result set is laid out in an ugly fashion.
So, if you are having problems with your function, the questions are:
What client environment are you using?
In what precise fashion does it "not work"? Please describe the observed behaviour, including any error messages?
Also give us environment details such as the version of the database, the OS, etc.
Having read your other question on this topic I thought the problem might be due to the use of a User-Defined Ref Cursor (rather than the built-in). However, that doesn't make any difference. This packaged function:
SQL> create or replace package emp_rc_utils as
2
3 type emp_rc is ref cursor return emp%rowtype;
4
5 function get_emps
6 ( p_dno in emp.deptno%type
7 )
8 return emp_rc;
9 end;
10 /
Package created.
SQL> create or replace package body emp_rc_utils as
2
3 function get_emps
4 ( p_dno in emp.deptno%type
5 )
6 return emp_rc
7 is
8 return_value emp_rc_utils.emp_rc;
9 begin
10
11 open return_value for select * from emp where deptno = p_dno;
12
13 return return_value;
14 end get_emps;
15
16 end emp_rc_utils;
17 /
Package body created.
SQL>
Still works...
SQL> declare
2 rc sys_refcursor;
3 begin
4 rc := emp_rc_utils.get_emps(50);
5 end;
6 /
PL/SQL procedure successfully completed.
SQL> select emp_rc_utils.get_emps(50) from dual
2 /
EMP_RC_UTILS.GET_EMP
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
8085 TRICHLER PLUMBER 8061 08-APR-10 3500 50
8060 VERREYNNE PLUMBER 8061 08-APR-08 4000 50
8061 FEUERSTEIN PLUMBER 7839 27-FEB-10 4500 50
8100 PODER PLUMBER 8061 3750 50
SQL>
You can do this via a refcursor call or populate a user defined table and return it as follows:
create or replace
function getRef return sys_refcursor
is
l_ref sys_refcursor;
begin
open l_ref for
select 1 a, 'a' c from dual
union all
select 2 a, 'b' c from dual
union all
select 3 a, 'c' c from dual
union all
select 4 a, 'd' c from dual;
return l_ref;
end getRef;
/
select getref() from dual;
GETREF()
--------
A C
---------------------- -
1 a
2 b
3 c
4 d
--you'll notice this isn't the most user-friendly result set if you look at it in SQL Developer or whatno
--drop function getRef;
you can also use the 'table' if you are passing back a table collection as such
create or replace type lookup_row as
object ( a number, c varchar2(20) );
/
create or replace type lookups_tab as
table of lookup_row;
/
create or replace
function getUserDefinedTableType return lookups_tab
is
lTestTypeTable lookups_tab;
begin
SELECT lookup_row(a,c)
bulk collect INTO lTestTypeTable
from
(select 1 a, 'a' c from dual
union all
select 2 a, 'b' c from dual
union all
select 3 a, 'c' c from dual
union all
select 4 a, 'd' c from dual);
return lTestTypeTable;
end getUserDefinedTableType;
/
select * from table(getUserDefinedTableType());
--this returns it in a more user friendly manner
--http://www.oreillynet.com/pub/a/network/2003/01/22/feuerstein.html?page=2
--http://stackoverflow.com/questions/3150137/converting-oracle-query-into-user-defined-types-in-pl-sql/3152885#3152885
A C
---------------------- --------------------
1 a
2 b
3 c
4 d
have you tried:
myCursor := package_name.function_name(param,param);
this would have to be from within a test block or a stored procedure.