Subquery in the From Clause
I have a query the contains a subquery in the from clause. The problem is how to join one of the tables in the subquery to one of the main tables. If I hard a value, the query runs, but using a table.column produced an "invalid column name" error.
Examples of both are below.
This one works
SELECT a.pay_rate, a.bill_rate, a.frequency, c.value
FROM SYSADM.ps_pb_wkord_sq_rte a, SYSADM.ps_md_erncd_action b,
SELECT DISTINCT z.value
FROM SYSADM.ps_md_erncd_action z
WHERE z.md_action = 'CALC_BURD' AND
z.system_id = 'PB' AND
z.erncd = 'REG' AND **This is the line in question**
z.effdt = (
SELECT MAX(z_ed.effdt)
FROM SYSADM.ps_md_erncd_action z_ed
WHERE z.setid = z_ed.setid AND
z.erncd = z_ed.erncd AND
z.effdt = z_ed.effdt AND
z.system_id = z_ed.system_id AND
z.md_action = z_ed.md_action AND
z_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY'))) c
WHERE a.erncd = b.erncd AND
b.effdt = (
SELECT MAX(b_ed.effdt)
FROM SYSADM.ps_md_erncd_action b_ed
WHERE b.setid = b_ed.setid AND
b.erncd = b_ed.erncd AND
b.effdt = b_ed.effdt AND
b.system_id = b_ed.system_id AND
b.md_action = b_ed.md_action AND
b_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY')) AND
a.group_id = 'PSD01' AND
a.workorder_no = 'H00034758' AND
a.assignment_no = 'H00034758-001' AND
b.system_id = 'PB' AND
b.md_action = 'EARN_TYPE' AND
b.value = 'R';
This one produces the error
SELECT a.pay_rate, a.bill_rate, a.frequency, c.value
FROM SYSADM.ps_pb_wkord_sq_rte a, SYSADM.ps_md_erncd_action b,
SELECT DISTINCT z.value
FROM SYSADM.ps_md_erncd_action z
WHERE z.md_action = 'CALC_BURD' AND
z.system_id = 'PB' AND
z.erncd = a.erncd AND **This is line in question**
z.effdt = (
SELECT MAX(z_ed.effdt)
FROM SYSADM.ps_md_erncd_action z_ed
WHERE z.setid = z_ed.setid AND
z.erncd = z_ed.erncd AND
z.effdt = z_ed.effdt AND
z.system_id = z_ed.system_id AND
z.md_action = z_ed.md_action AND
z_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY'))) c
WHERE a.erncd = b.erncd AND
b.effdt = (
SELECT MAX(b_ed.effdt)
FROM SYSADM.ps_md_erncd_action b_ed
WHERE b.setid = b_ed.setid AND
b.erncd = b_ed.erncd AND
b.effdt = b_ed.effdt AND
b.system_id = b_ed.system_id AND
b.md_action = b_ed.md_action AND
b_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY')) AND
a.group_id = 'PSD01' AND
a.workorder_no = 'H00034758' AND
a.assignment_no = 'H00034758-001' AND
b.system_id = 'PB' AND
b.md_action = 'EARN_TYPE' AND
b.value = 'R';
Any help is greatly appreciated.
Thanks,
JD Lippard
Hi JD,
your code is very difficult to read to i will give you some general information.
SELECT t1.c1,t1.c2
FROM table t1
, (SELECT t2.col1 alias1
, t2.col2 alias2
, a.s.o.
FROM anytable t2
) tablealias
WHERE t1.c1 = tablealias.alias1
You can select any columns inside this 'dynamic view' whichever you need for a join. Independent if you print them or not.
But you cannot join INSIDE this dynamic view to outer tables like
SELECT t1.c1,t1.c2
FROM table t1
, (SELECT t2.col1 alias1
, t2.col2 alias2
, a.s.o.
FROM anytable t2
WHERE t1.c2 = t2.col2
) tablealias
WHERE bla
Maybe it helps a bit.
Cheers,
Udo
Similar Messages
-
Can I put a subquery in the where clause, on the left side on the operator?
This is a multi-row query.
Like this,
select a.col1, a.col2, b.col1, b.col2,
my_function(a.date1, b.date2) AS GROSSDAYS
from table1 a
where ( select ( a.date1 - b.date2 ) as range
from table1 a
join table2 b
on a.col3 = b.col3
where rownum =1
in ( 1,2,3)
and a.col1 = b.col2I need to use a subquery because the column I need does not exist in the table, and I cannot make any changed to the table structure.
Is what I'm doing possible?
The subquery is the same as the function I have in the Select clause.I tried a subquery in the where clause, but now I'm getting a missing expression error!
SELECT
r.complete_flag, r.order_num, r.referral_num, TRUNC(r.referral_datetime) AS referral_datetime,
r.clinic_specialty, a.appointment_datetime, TRUNC(a.appointment_date_made) AS appt_datemade, a.appointment_status_id,
scref.scr_rules.calcatcdays(r.referral_datetime,a.appointment_date_made) AS ATCDays -- returns difference between two dates
FROM
referral r,
( SELECT referral_num,appointment_datetime, appointment_date_made, appointment_status_id
FROM ( SELECT referral_num, appointment_datetime, appointment_date_made, appointment_status_id,
ROW_NUMBER() OVER (PARTITION BY referral_num
ORDER BY appointment_datetime) rn
FROM appointment
WHERE rn = 1
a
WHERE r.order_num IS NOT NULL
AND ( SELECT adays -- THIS IS WHERE I'M GETTING A MISSING EXPRESSION ERROR!!!
FROM ( SELECT scref.scr_rules.calcatcdays(r.referral_datetime,a.appointment_date_made) AS adays
FROM referral r
JOIN appointment a
ON a.referral_num = r.referral_num
WHERE ROWNUM = 1
WHERE adays
) = 3
AND r.referral_num = a.referral_num(+)
AND TRUNC(r.referral_datetime) >= TO_DATE('01-JUL-05','DD-MON-YY')
AND TRUNC(r.referral_datetime) <= TO_DATE('31-JUL-05','DD-MON-YY') -
Can a subquery in the select clause return more than one field?
Something like this:
select ename,
(select dname, loc from dept where e.deptno = deptno) as (dname,loc)
from emp eA simple way to find out is to test it. In my tests below, the original query produces an error that says it didn't find FROM where it expected. Eliminating "as (dname,loc)" produces an error about too many values. Putting only one value in the subquery in the select clause works, whether it is dname or loc. Concatenating the two columns as dname || ' ' || loc to produce one value in the subquery in the select clause works. Using two separate subqueries, one for dname and one for loc works. And, lastly, a cursor statement with both values works, although the output is a little hard to read. This may be different in newer versions. I am using Oracle 8.1.7. It may be different in 9i. I was unable to locate any documentation on the cursor statement or cursor operator which I have also heard it called. I only knew to try it because I have seen it used. I looked up the SELECT syntax in the 9i SQL Reference and there was no mention of cursor in the select clause. Can anyone provide a link to some documentation on this? I vaguely recall reading something that said that, other than outputting from SQL*Plus as below, it wasn't yet compatible with anything else, like you can't use it in PL/SQL, but I can't remember where I read it.
SQL> -- 2 values in subquery in select clause:
SQL> select ename,
2 (select dname, loc from dept where e.deptno = deptno) as (dname,loc)
3 from emp e
4 /
(select dname, loc from dept where e.deptno = deptno) as (dname,loc)
ERROR at line 2:
ORA-00923: FROM keyword not found where expected
SQL> select ename,
2 (select dname, loc from dept where e.deptno = deptno)
3 from emp e
4 /
(select dname, loc from dept where e.deptno = deptno)
ERROR at line 2:
ORA-00913: too many values
SQL> -- 1 value in subquery in select clause:
SQL> select ename,
2 (select dname from dept where e.deptno = deptno)
3 from emp e
4 /
ENAME (SELECTDNAMEFR
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING ACCOUNTING
TURNER SALES
ADAMS RESEARCH
JAMES SALES
FORD RESEARCH
MILLER ACCOUNTING
14 rows selected.
SQL> select ename,
2 (select loc from dept where e.deptno = deptno)
3 from emp e
4 /
ENAME (SELECTLOCFRO
SMITH DALLAS
ALLEN CHICAGO
WARD CHICAGO
JONES DALLAS
MARTIN CHICAGO
BLAKE CHICAGO
CLARK NEW YORK
SCOTT DALLAS
KING NEW YORK
TURNER CHICAGO
ADAMS DALLAS
JAMES CHICAGO
FORD DALLAS
MILLER NEW YORK
14 rows selected.
SQL> select ename,
2 (select dname || ' ' || loc from dept where e.deptno = deptno)
3 from emp e
4 /
ENAME (SELECTDNAME||''||LOCFROMDEP
SMITH RESEARCH DALLAS
ALLEN SALES CHICAGO
WARD SALES CHICAGO
JONES RESEARCH DALLAS
MARTIN SALES CHICAGO
BLAKE SALES CHICAGO
CLARK ACCOUNTING NEW YORK
SCOTT RESEARCH DALLAS
KING ACCOUNTING NEW YORK
TURNER SALES CHICAGO
ADAMS RESEARCH DALLAS
JAMES SALES CHICAGO
FORD RESEARCH DALLAS
MILLER ACCOUNTING NEW YORK
14 rows selected.
SQL> select ename,
2 (select dname from dept where e.deptno = deptno),
3 (select loc from dept where e.deptno = deptno)
4 from emp e
5 /
ENAME (SELECTDNAMEFR (SELECTLOCFRO
SMITH RESEARCH DALLAS
ALLEN SALES CHICAGO
WARD SALES CHICAGO
JONES RESEARCH DALLAS
MARTIN SALES CHICAGO
BLAKE SALES CHICAGO
CLARK ACCOUNTING NEW YORK
SCOTT RESEARCH DALLAS
KING ACCOUNTING NEW YORK
TURNER SALES CHICAGO
ADAMS RESEARCH DALLAS
JAMES SALES CHICAGO
FORD RESEARCH DALLAS
MILLER ACCOUNTING NEW YORK
14 rows selected.
SQL> -- cursor statement:
SQL> select ename,
2 cursor (select dname, loc from dept where e.deptno = deptno)
3 from emp e
4 /
ENAME CURSOR(SELECTDNAME,L
SMITH CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
RESEARCH DALLAS
1 row selected.
ALLEN CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
SALES CHICAGO
1 row selected.
WARD CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
SALES CHICAGO
1 row selected.
JONES CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
RESEARCH DALLAS
1 row selected.
MARTIN CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
SALES CHICAGO
1 row selected.
BLAKE CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
SALES CHICAGO
1 row selected.
CLARK CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
ACCOUNTING NEW YORK
1 row selected.
SCOTT CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
RESEARCH DALLAS
1 row selected.
KING CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
ACCOUNTING NEW YORK
1 row selected.
TURNER CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
SALES CHICAGO
1 row selected.
ADAMS CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
RESEARCH DALLAS
1 row selected.
JAMES CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
SALES CHICAGO
1 row selected.
FORD CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
RESEARCH DALLAS
1 row selected.
MILLER CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
DNAME LOC
ACCOUNTING NEW YORK
1 row selected.
14 rows selected. -
Is there a way to use dynamic built string in the "from" clause
Hi all, im having one problem and now, im not sure how to solve it easily at all... :) Is there someone that would be so kind and put a eye on it? ..thx
I have plsql proc, in which i have a list of table_names. For each of that table i need to run a query that will retrieve me a list of values and for each of that value i need to do something.
If i can be more specific about the problem -> each of that table is built as key_column, value_columns, day,starttime. For a key per table there are 4 records per hour - every quarter. Im truncating those quarters to full-quarter (minutes => 0->14 = 0min; 15->29 = 15min, 30->44 = 30, 45->59=45)
example
i get for one key and specific hour four records at 15:01;15:16;15:31;15:46 => i truncate em to 15:00;15:15;15:30;15:45..Sometimes there is a problem with the tool that is generating those data for me, and one quarter could be moved a little - so i get data like 15:01;15:16;15:29;15:46 => after i truncate the times i get duplicates in second quarter. It also can happen like this : 23:00; 23:14; 23:29; 23:44; 23:59 => totaly bad => cos the last one supposed to be as 0:00 next day, ..and 23:14 as 23:15...So...that was a problem - and solution -> i wanted to create plsql that will find those hours in each table i ve defined, and for each problem hour i make some fixes - update the bad time ...
..and i have problem - can i put an dynamic built table_name in the "from" clause?
example how i wanted to do that:
declare
type t_objectName is table of varchar2(030) index by pls_integer;
l_tableName t_objectName;
begin
l_tableName(1) := 'tmphlrgl';
l_tableName(2) := 'tmprcfgl';
l_tableName(3) := 'tmprcfbs';
l_tableName(4) := 'tmpvlrgl';
for i in (select evtime from (select day,trunc_quarter(evtime) evtime,m_id from l_tableName(i) group by day,trunc_quarter(evtime),m_id having count(*)>1) order by evtime) loop
--some other conditions and the update...
end loop;
end;
/I cannot use the l_tableName(i) for FROM ...get an error...I was thinking to build it as dynamic sql and execute immediate into some kind of object that can store mutliple lines, from which i would in the FOR cycle get the data...But im not sure if this could be done in plsql...
thanks for your time and help..
d.declare
c sys_refcursor;
begin
for i in 1..4 loop
open c for 'day,trunc_quarter(evtime) evtime,m_id
from ' || l_tableName(i) ||
'group by day,trunc_quarter(evtime),m_id having
count(*)>1) order by evtime';Just to high light SELECT is missing that all
OPEN c FOR ' SELECT day,trunc_quarter(evtime) evtime,m_id
FROM' || l_tableName(i) ||
'GROUP BY day,trunc_quarter(evtime),m_id HAVING count(*)>1) ORDER BY evtime'; -
Is it possible to create a view where table in the From clause changes name
is it possible to create a view from a from a table like this
create view my_view as select id, col1, col2, result from <<my_latest_cacahe_table>>;
the table in the from clause changes the name .
I have another table which indicates the the latest name of my cache tables. Always there are two records there. The latest one and previous one.
select * from cache_table_def
table_name cache_table_name refresh_date
my_table cache_table245 1/23/2012
my_table cache_table235 1/22/2012
create table cache_table_def (table_name varchar2(25), cache_table_name varchar2(25), refresh_date date);
insert into cache_table_def values( 'my_table','cache_table245','23-jan-2012');
insert into cache_table_def values ( 'my_table','cache_table546','22-jan-2012');
create table cache_table245 (id number, col1 varchar2(50), col2 varchar2(20), result number);
insert into cache_table245 values(1, 'test123', 'test345',12.12);
insert into cache_table245 values (2, 'test223', 'test245',112.12);
create table cache_table235 (id number, col1 varchar2(50), col2 varchar2(20), result number);
insert into cache_table235 values (1, 'test123', 'test345',92.12);
insert into cache_table235 values (2, 'test223', 'test245',222.12);
what I need to do is find the latest cache_table name for my_table and use that in my view defintion
When user select from the the view it always reurns the data from the latest cache_table
is it possible to do something like this in oracle 11g?
I have no control on the cache tables names. that is why I need to use the latest name from the table.
Any ideas really appreciated.I've worked up an example that does what you ask. It uses the SCOTT schema EMP table. Make two copies of the EMP table, EMP1 and EMP2. I deleted dept 20 from emp1 and deleted dept 30 from emp2 so I could see that the result set really came from a different table.
-- create a context to hold an environment variable - this will be the table name we want the view to query from
create or replace context VIEW_CTX using SET_VIEW_FLAG;
-- create the procedure specified for the context
- we will pass in the name of the table to query from
create or replace procedure SET_VIEW_FLAG ( p_table_name in varchar2 default 'EMP')
as
begin
dbms_session.set_context( 'VIEW_CTX', 'TABLE_NAME', upper(p_table_name));
end;
-- these are the three queries - one for each table - none of them will return data until you set the context variable.
select * from emp where 'EMP' = sys_context( 'VIEW_CTX', 'TABLE_NAME' );
select * from emp1 where 'EMP1' = sys_context( 'VIEW_CTX', 'TABLE_NAME' );
select * from emp2 where 'EMP2' = sys_context( 'VIEW_CTX', 'TABLE_NAME' )
-- this is how you set the context variable depending on the table you want the view to query
exec set_view_flag( p_table_name => 'EMP' );
exec set_view_flag( p_table_name => 'EMP1' );
exec set_view_flag( p_table_name => 'EMP2');
-- this will show you the current value of the context variable
SELECT sys_context( 'VIEW_CTX', 'TABLE_NAME' ) FROM DUAL
-- this is the view definition - it does a UNION ALL of the three queries but only one will actually return data
CREATE VIEW THREE_TABLE_EMP_VIEW AS
select * from emp where 'EMP' = sys_context( 'VIEW_CTX', 'TABLE_NAME' )
union all
select * from emp1 where 'EMP1' = sys_context( 'VIEW_CTX', 'TABLE_NAME' )
union all
select * from emp2 where 'EMP2' = sys_context( 'VIEW_CTX', 'TABLE_NAME' )
-- first time - no data since context variable hasn't been set yet
SELECT * FROM THREE_TABLE_EMP_VIEW
-- get data from the EMP table
exec set_view_flag( p_table_name => 'EMP' );
SELECT * FROM THREE_TABLE_EMP_VIEW
-- get data from the EMP2 table
exec set_view_flag( p_table_name => 'EMP2');
SELECT * FROM THREE_TABLE_EMP_VIEW
For your use case you just have to call the context procedure whenever you want to switch tables. You can union all as many queries as you want and can even put WHERE clause conditions based on other filtering criteria if you want. I have used this approach with report views so that one view can be used to roll up report data different ways or for different regions, report periods (weekly, quarterly, etc). I usually use this in a stored procedure that returns a REF CURSOR to the client. The client requests a weekly report and provides a date, the procedure calculates the START/END date based on the one date provided and sets context variables that the view uses in the WHERE clause for filtering.
For reporting it works great! -
CAN I PASS A TABLE NAME AS A VARIABLE IN THE FROM CLAUSE?
For some reason, I am trying to use a variable name containing the actual table name in the from clause and it won't allow me. I keep getting the error saying I need to declare the variable I'm using eventhough I've used it in another statement that is not the FROM clause.
Example
SELECT count(col1), sum(col2)
FROM v_table_name;
v_table_name was declared as:
v_tablename VARCHAR2(20);
v_tablename := real_table_name;
Is it not allowed to use variables in the FROM clause or am I missing something here?You can use the Forms "From Clause Query" as the datasource for the data block. Then you can change the QUERY_DATA_SOURCE_NAME using set_block_property, so you can use any SQL statement you like. Of course you must name/alias the columns in a consistent manner so that the number of database items on the block matches those being queried.
-
CASE in the FROM clause ?
Hello, I need to query a table which (unfortunately) its name is depended on the date. (Year, Month, and every 15 days (Fortnight FN)
My tables is STAT_VEHICLES_YY_MM and if it refers to the fortnight report it becomes STAT_VEHICLES_YY_MM15
For example this fortnight (15 of July report) will be STAT_VEHICLES_09_0815 and the 1st of this month report was on STAT_VEHICLES_09_08 table.
My query so far is:
ACCEPT YY prompt 'Please enter current year in YY format:'
ACCEPT MM prompt 'Please enter current month in the MM format:'
SELECT COUNT(*) "STAT VEH. NEW LIC."
FROM STAT_VEHICLES_&YY._&MM
WHERE NR=3;
I tried using something like
ACCEPT FN prompt 'Is this a fortnight report? (Y/N): '
SELECT…
FROM
CASE
WHEN &FN = Y THEN STAT_VEHICLES_&YY._&MM.15
WHEN &FN = y THEN STAT_VEHICLES_&YY._&MM.15
WHEN &FN = N THEN STAT_VEHICLES_&YY._&MM
WHEN &FN = n THEN STAT_VEHICLES_&YY._&MM
END
WHERE…
But I don’t think that CASE will work in the FROM clause
My next though is OUTER JOIN and here is where I need your help people.
Thank youObviously this is extreemly poor design, and it should have been implemented by partitioning 1 table.
In that case Oracle would have automatically choosen the right partition!!!
What you can do is
column table_name new_value tablename
ACCEPT YY prompt 'Please enter current year in YY format:'
ACCEPT MM prompt 'Please enter current month in the MM format:'
select stat_vehicles_&YY._&MM table_name
from dual;
select count(*)
from &_table_name
where nr=3;
You would need to use &_table_name everywhere.
Hth
Sybrand Bakker
Senior Oracle DBA -
In the following SQL SELECT statement, what does the
px-granule(0, block_range, dynamic) in the FROM clause reference.
This select statement was copied from the sql analyze tool within
OEM 2.2.
SELECT /*+ Q524000 NO_EXPAND ROWID(A1) */ A1."PROCESSING_DATE"
C0,
A1."PRCSNG_SEQUENCE_NR_IDENTIFIER" C1,
A1."TUI_ID" C2,NVL(A1."RECORD_TYPE_CODE",' ') C3,
NVL(A1."CONDITION_CODE",' ') C4,
NVL(A1."PURPOSE_CODE",' ') C5,
NVL(A1."DOCUMENT_IDENTIFIER",' ') C6,
NVL(A1."NIIN_IDENTIFIER",' ') C7,
NVL(RTRIM(A1."DOCUMENT_NUMBER_IDENTIFIER"),' ') C8,
NVL(A1."SUFFIX_CODE",' ') C9,
NVL(A1."UNIT_OF_ISSUE_CODE",' ') C10,
NVL(A1."PLUS_MINUS_CODE",' ') C11,
NVL(A1."TRANSACTION_QUANTITY_CHAR_TEXT",' ') C12,
NVL(A1."TRANSACTION_REVERSAL_CODE",' ') C13,
NVL(A1."ON_HAND_QUANTITY_CHAR_TEXT",' ') C14,
NVL(A1."SITE_CODE",' ') C15,
A1."RECORD_TYPE_CODE" C16,
NVL(TO_CHAR(TRUNC(A1."REPAIR_SEQUENCE_NR_IDENTIFIER")),' ') C17,
NVL(A1."COGNIZANCE_SYMBOL",' ') C18,
NVL(A1."FSC_CODE",' ') C19
FROM "OPS$DWTLOD"."TLOD_UNION_ITEMS" PX_GRANULE(0, BLOCK_RANGE,
DYNAMIC) A1
WHERE A1."REGION_IDENTIFIER_CODE"=5 AND
A1."PROCESSING_DATE"<=:B1 AND
NVL(A1."NIIN_IDENTIFIER",' ') LIKE '000457162' AND
NVL(RTRIM(A1."DOCUMENT_NUMBER_IDENTIFIER"),' ') LIKE '%'
AND A1."PROCESSING_DATE">=:B2 AND A1."PROCESSING_DATE"<=:B3 AND
NVL(A1."NIIN_IDENTIFIER",' ') LIKE '000457162' AND
NVL(RTRIM(A1."DOCUMENT_NUMBER_IDENTIFIER"),' ') LIKE '%'
Thanks,
GilDECLARE
highestlid locations.location_id%TYPE;
BEGIN
SELECT
max(location_id)
INTO
highestlid
FROM
locations;
highestlid:=highestlid+1;
ADDLOCATION(highestlid,'Lucan');
END;
/ -
I want to use a dynamic schema name in the from clause but its not working.
DECLARE
vblQueryName VARCHAR2(20);
vblSchemaName VARCHAR2(20);
BEGIN
SELECT CurrentSchemaName INTO vblSchemaName FROM HR_989_SCHEMA;
vblQueryName:='060_525_020';
INSERT /*+ APPEND(HP_ELIGIBILITIES,4) */ INTO HP_ELIGIBILITIES
LVL1ID,
LVL1Desc,
LVL2ID,
LVL2Desc,
LVL3ID,
LVL3Desc,
LVL4ID,
LVL4Desc
SELECT /*+ PARALLEL(a,4) */
LVL1ID,
LVL1Desc,
LVL2ID,
LVL2Desc,
LVL3ID,
LVL3Desc,
LVL4ID,
LVL4Desc
FROM
bold vblSchemaName.HP_ELIGIBILITIES a
WHERE
UPPER(LVL2ID) = 'XX' ;
COMMIT;
DBMS_OUTPUT.PUT_LINE( 'Query Executed: ' || vblqueryName);
INSERT INTO HP_QUERYEXECLOG(QueryName) VALUES(vblQueryName);
EXCEPTION WHEN NO_DATA_FOUND THEN NULL;
END;
I want to create a rules table so that the schema name in front of the table name in the from clause can be controlled by a separate table that is maintained but its not working . Help and your valuable inputs needed for this issueI want to use a dynamic schema name in the from clauseyou can alternatively set the current schema as e.g. in:
declare
vblqueryname varchar2 (20);
vblschemaname varchar2 (20);
begin
select currentschemaname into vblschemaname from hr_989_schema;
vblqueryname := '060_525_020';
execute immediate 'alter session set current_schema=' || vblschemaname;
insert /*+ APPEND(HP_ELIGIBILITIES,4) */
into hp_eligibilities (lvl1id,
lvl1desc,
lvl2id,
lvl2desc,
lvl3id,
lvl3desc,
lvl4id,
lvl4desc
select /*+ PARALLEL(a,4) */
lvl1id,
lvl1desc,
lvl2id,
lvl2desc,
lvl3id,
lvl3desc,
lvl4id,
lvl4desc
from hp_eligibilities a
where upper (lvl2id) = 'XX';
commit;
dbms_output.put_line ('Query Executed: ' || vblqueryname);
insert into hp_queryexeclog (queryname)
values (vblqueryname);
exception
when no_data_found
then
null;
end; -
Hello all,
i'm getting error when i try to write sub query in having clause. check out my query
select ROUND( Count( distinct Sales2011_DIVDPTA.DIVDPTA_Item_Dept ),0) AS "F1" , ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0) AS "F2"
from Sales2011.Sales2011_JT
INNER JOIN Sales2011.Sales2011_DG1 On Sales2011.Sales2011_DG1.DG1_ID =Sales2011.Sales2011_JT.DG1_ID
LEFT JOIN Sales2011.Sales2011_DIVDPTA On nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DIVISION,' ')=nvl(Sales2011.Sales2011_DG1.Item_Division,' ')
AND nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DEPT,' ')=nvl(Sales2011.Sales2011_DG1.Item_Dept,' ')
having ( ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0) in ( 0)
But it is not executed if I use the sub query in having clause
select ROUND( Count( distinct Sales2011_DIVDPTA.DIVDPTA_Item_Dept ),0) AS "F1" , ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0) AS "F2"
from Sales2011.Sales2011_JT
INNER JOIN Sales2011.Sales2011_DG1 On Sales2011.Sales2011_DG1.DG1_ID =Sales2011.Sales2011_JT.DG1_ID
LEFT JOIN Sales2011.Sales2011_DIVDPTA On nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DIVISION,' ')=nvl(Sales2011.Sales2011_DG1.Item_Division,' ')
AND nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DEPT,' ')=nvl(Sales2011.Sales2011_DG1.Item_Dept,' ')
having ( ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0)
in ( select ROUND( Count(
Sales2011.Sales2011_DG1.Item_Season ),0) from Sales2011.Sales2011_DG1 )
Error at Command Line:1 Column:0
Error report:
SQL Error: ORA-00979: not a GROUP BY expression
00979. 00000 - "not a GROUP BY expression"
*Cause:
*Action:any help ???Sorry unintentionally i have posted my question here.
will you please elaborate this? Becoz i'm not using group by clause in both query. First query run successfully but as i put sub query in having clause it raised an error. will you tell where i'm committing mistake?
Aggregates in the HAVING clause do not need to appear in the SELECT list. If the HAVING clause contains a subquery, the subquery can refer to the outer query block if and only if it refers to a grouping column.Edited by: Oracle Studnet on Aug 14, 2011 11:28 PM -
Using a Procedure in the FROM clause of a query
Is it possible to use a Procedure that accepts multiple parameters and returns multiple parameters in the FROM section of a query?
I have a Procedure that formats a postal address from BS7666 format into an Oracle Apps friendly format.
I'd like to be able to select the data from the source, feed it through this procedure and output it as part of a Materialised View.
PROCEDURE Format_llpg_Address
In_Loc IN VARCHAR2,
In_Description IN VARCHAR2,
In_County IN VARCHAR2,
In_Town IN VARCHAR2,
In_PostTown IN VARCHAR2,
In_Saon_Start_num IN NUMBER,
In_Saon_Start_Suffix IN VARCHAR2,
In_Saon_End_num IN NUMBER,
In_Saon_End_Suffix IN VARCHAR2,
In_Saon_Text IN VARCHAR2,
In_Paon_Start_num IN NUMBER,
In_Paon_Start_Suffix IN VARCHAR2,
In_Paon_End_num IN NUMBER,
In_Paon_End_Suffix IN VARCHAR2,
In_Paon_Text IN VARCHAR2,
In_PostCode IN VARCHAR2,
Out_Address1 OUT NOCOPY VARCHAR2,
Out_Address2 OUT NOCOPY VARCHAR2,
Out_Address3 OUT NOCOPY VARCHAR2,
Out_Town OUT NOCOPY VARCHAR2,
Out_County OUT NOCOPY VARCHAR2,
Out_PostCode OUT NOCOPY VARCHAR2)
Many Thanks,
Jason.You should look at [pipelined functions|http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28370/tuning.htm#i52954]
Adrian Billington has a number of excellent articles on pipelined functions.
Here's a [link to one of them|http://www.oracle-developer.net/display.php?id=207]
Edited by: dombrooks on Oct 12, 2009 4:45 PM -
Two variables in the name of a table in the FROM clause.
Hello,
I ve got a problem making this work:
SELECT *
FROM tablename_YY_MM
(This is part of the script I need to use YY and MM in various tables)
I need to find a way so the script will ask me every time about the YY and MM
For example the current table name is "tablename_09_08" next month it will be "tablename_09_09"
It looks simple but I can't make it work. It seems to be a problem with concatanation || and the underscore _
Looks like it should be done with PL/SQL ?
If anyone can help it will be much appreciated.
Thank you.
Edited by: user1067236 on Aug 11, 2009 2:21 AM
Edited by: user1067236 on Aug 11, 2009 2:23 AMHi,
That's easy to do using substitution variables in SQL*Plus:
SELECT *
FROM tablename_&year_num._&month_num;Note the . after &year_num; it is necessary to indicate that the next _ is not part of the preceding name.
You can also use the SQL*Plus ACCEPT command to prompt the user for values, with a detailed message.
ACCEPT year_num PROMPT "Please enter year number (2 digits only, such as 09): "Edited by: Frank Kulash on Aug 11, 2009 5:29 AM -
Can't get query to work. table alias in subquery in FROM clause
How can I rearrange this query to work?
SELECT
TO_CHAR(dt.date_time, 'YYYY-MM-DD') start_date,
(SELECT COUNT(*) FROM
(SELECT DISTINCT a.non_asp, a.start_time, a.end_time
FROM appointments a
WHERE a.start_time >= dt.date_time AND a.start_time < dt.date_time + 1
) num_overlap
FROM
table(times_pkg.between_times(TO_DATE('2010-05-30'),
TO_DATE('2010-07-03'), 60*24, 'Y')) dtbetween_times is a table function that returns times at given intervals.
I am trying to get a count of distinct (non_asp, start_time, end_time) sets that fall on each day.
However, it doesn't recognize dt.date_time in the FROM clause.Hi,
A sub-query can be correlated only to its immediate parent. You're trying the correlate the SELECT DISTINCT sub-query to its grandparent.
You can re-write the sub-query as a join, like this:
SELECT TO_CHAR(dt.date_time, 'YYYY-MM-DD') start_date,
a.num_overlap
FROM table ( times_pkg.between_times ( TO_DATE('2010-05-30'),
TO_DATE('2010-07-03'),
60*24,
'Y'
) dt
JOIN (
SELECT start_time,
end_time,
COUNT (DISTINCT non_asp) AS num_overlap
FROM appointments
) a ON a.start_time >= dt.date_time
AND a.start_time < dt.date_time + 1
;You could also eliminate the extra level between the SELECT DISTINCT sub-query and the main query by using SELECT (DISTINCT ...). -
How to give the list.tablename in from clause
Hi,
I am getting error invalid table name when I give list_item.tablename in from clause
ex :
q1:= 'select * from &p1_list.tablename';
return q1;
here p1_list is the list of schema values.
It worked fine when I give the type SQL Query. If I give the same thing in
SQL Query(PL/SQL function body returning SQL QUERY I am getting above error
Please help me.
Thanks,
RekhaI have a LOV defined in a page which lists the schema names. My report query should use the selected schema , i.e. say the LOV item is named P5_ENVID, and the table name is emp then my sql query should be of the form,
select * from <P5_ENVID>.emp ;
Questions:
1. for Type "SQL Query", is it possible to use variables in the FROM clause?
2. I have tried :P5_ENVID.. , &P5_ENVID and v('P5_ENVID') , but they all return a parse error.
3. Do I have to use type PL/SQL funtion body returning sql query ?
4. if I have to do 3, then could you pls point me to appropriate documentation with the usage of it
Thanks -
Hi,
some of my complex extractions that I am currently working on require nested SELECT statements. As far as I can see OpenSQL only supports subqueries in the WHERE clause, not in the FROM clause. Is this assumptions correct or is there a way around it? I have managed to use Native SQL for these nested expressions but the preference of the client is to use OpenSQL.
Any ideas?
Thanks,
TobiasHi
In from clause you can use join.
You can read data from more than one database table in a single SELECT statement by using inner or left outer joins in the FROM clause.
The disadvantage of using joins is that redundant data is read from the hierarchically-superior table if there is a 1:N relationship between the outer and inner tables. This can considerably increase the amount of data transferred from the database to the application server. Therefore, when you program a join, you should ensure that the SELECT clause contains a list of only the columns that you really need. Furthermore, joins bypass the table buffer and read directly from the database. For this reason, you should use an ABAP Dictionary view instead of a join if you only want to read the data.
The runtime of a join statement is heavily dependent on the database optimizer, especially when it contains more than two database tables. However, joins are nearly always quicker than using nested SELECT statements.
thanks
jagan
Maybe you are looking for
-
File Format Mismatch while update into Internal table using RFC_REMOTE_FILE
Hi All, I used RFC_REMOTE_FILE to communicate with the presentation server in Background Mode. I connected successfully and got output too. But my requirement is to update the .csv file into internal tables. With RFC_REMOTE_FILE i can get the data as
-
Safari update 4.02 corruption
I downloaded 4.02 and installed it. My boot drive is now unbootable. I have run DiskUtility, TechTool Pro 5, Drive Genius 2, and Diskwarrior 4.1.1 to no avail. What is the story with the update? It trashed my system.
-
space designer always sounds ****** once ive bounced out of logic. for one, the reverb is a ton stronger on the final product, and for another, the quality has gone down the toilet- really it sounds awful until i turn it down enough so that its out o
-
In solving a problem with OSX 4.11, if I Archive & Install, will I lose my mail in the Eudora folders, or will they all be archived as well? I'm using Eudora 6.2 paid version. Thanks!
-
Firstly, I'm not a DBA, I'm a developer who has been waiting for weeks for the sysadmins to fix a DB they know nothing about. We run an Oracle 9i database and forms server on Solaris 9. On one machine everything works fine, and on another machine (wh