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 you
Obviously 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
Similar Messages
-
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! -
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'; -
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.
-
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; -
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 LippardHi 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 -
Update statement that includes case, decode and from clause
hello
I've the following code. I ran this code in 9i and got the errror SQL command not properly ended. Can I use FROM clause in an update statement?
CREATE OR REPLACE procedure NRI
IS
BEGIN
UPDATE IEB2 SET SDI =
(CASE PSDI WHEN '11' THEN '16'
WHEN '13' THEN '38'
WHEN '14' THEN '18'
WHEN '23' THEN '21'
WHEN '24' THEN '21'
WHEN '31' THEN '27'
WHEN '32' THEN '37'
WHEN '33' THEN '38'
WHEN '34' THEN '37'
WHEN '43' THEN '46'
WHEN '53' THEN '45'
WHEN '55' THEN '48'
WHEN '60' THEN '54'
WHEN '61' THEN '57'
WHEN '62' THEN '54'
WHEN '63' THEN '56'
WHEN '64' THEN '52'
WHEN '70' THEN '21'
WHEN '77' THEN '25'
WHEN '78' THEN '41'
WHEN '80' THEN '79'
WHEN '85' THEN '75'
WHEN '87' THEN '73'
WHEN '15' THEN '15'
WHEN '51' THEN '51'
WHEN '88' THEN '88'
WHEN '00' THEN '00'
WHEN '99' THEN '99'
WHEN '12' THEN DECODE(C.R_ID, 'N', '16','18')
ELSE 'NONE' END)
FROM D1.C C
WHERE EXISTS
(SELECT 1
FROM D1.SD A, D2.SDP B, D1.C C
WHERE A.SDN = B.DN
AND B.SDI = '000000'
AND B.PFI = 'W'
AND B.CID = C.CID
AND A.SDN = '0001500721');
END;Your parenthesis look a tad messed up ... think this fixes them.
CREATE OR REPLACE procedure NRI
IS
BEGIN
UPDATE IEB2 SET SDI =
SELECT
CASE PSDI
WHEN '11' THEN '16'
WHEN '13' THEN '38'
WHEN '14' THEN '18'
WHEN '23' THEN '21'
WHEN '24' THEN '21'
WHEN '31' THEN '27'
WHEN '32' THEN '37'
WHEN '33' THEN '38'
WHEN '34' THEN '37'
WHEN '43' THEN '46'
WHEN '53' THEN '45'
WHEN '55' THEN '48'
WHEN '60' THEN '54'
WHEN '61' THEN '57'
WHEN '62' THEN '54'
WHEN '63' THEN '56'
WHEN '64' THEN '52'
WHEN '70' THEN '21'
WHEN '77' THEN '25'
WHEN '78' THEN '41'
WHEN '80' THEN '79'
WHEN '85' THEN '75'
WHEN '87' THEN '73'
WHEN '15' THEN '15'
WHEN '51' THEN '51'
WHEN '88' THEN '88'
WHEN '00' THEN '00'
WHEN '99' THEN '99'
WHEN '12' THEN DECODE(C.R_ID, 'N', '16','18')
ELSE 'NONE'
END
FROM D1.C C
WHERE EXISTS
SELECT 1
FROM D1.SD A, D2.SDP B, D1.C C
WHERE A.SDN = B.DN
AND B.SDI = '000000'
AND B.PFI = 'W'
AND B.CID = C.CID
AND A.SDN = '0001500721'
END; -
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 -
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 -
Curious about this From clause in Oracle XE
SQL view of query Builder gives the following:
select "EMPLOYEES"."EMPLOYEE_ID" as "EMPLOYEE_ID",
"EMPLOYEES"."FIRST_NAME" as "FIRST_NAME",
"EMPLOYEES"."LAST_NAME" as "LAST_NAME"
from "EMPLOYEES" "EMPLOYEES"
Why does the from clause showing "EMPLOYEES" "EMPLOYEES"?
In the SQL Commands of the SQL the folowing query
select "EMPLOYEES"."EMPLOYEE_ID" as "EMPLOYEE_ID",
"EMPLOYEES"."FIRST_NAME" as "FIRST_NAME",
"EMPLOYEES"."LAST_NAME" as "LAST_NAME"
from "EMPLOYEES
gives the same result and so does
select "EMPLOYEES"."EMPLOYEE_ID" as "EMPLOYEE_ID",
"EMPLOYEES"."FIRST_NAME" as "FIRST_NAME",
"EMPLOYEES"."LAST_NAME" as "LAST_NAME"
from "EMPLOYEES" "EMPLOYEES"
What is the significence of the second "Employees" in the FROM clause.Other interesting feature is the double quotes
although the one above works as well.
Why is this?Habit.
Some developers come from environments that support mixed case identifiers (table and column names). These developers sometimes go out of their way to force Oracle to use mixed case identifiers, and that requires double quotes.
So Oracle seems to have gotten into the habit of surrounding all identifiers (coming from generated code) with double quotes to keep these developers (who usually have other porting issues anyway) from having to trace those identifier issues. -
It is possible changed the SQL statement below to repeat only once USUARIO table in the FROM clause ?
SELECT U_PEND.NOME AS USUARIO_PEND
, U_DECLINADO.NOME AS USUARIO_DECLINADO
, U_REVISADO.NOME AS USUARIO_REENVIADO
, U_EMITIDO.NOME AS USUARIO_EMITIDO
, U_CANCELADO.NOME AS USUARIO_CANCELADO
, U_RECEBIDO.NOME AS USUARIO_RECEBIDO
, PP.NUMERO AS NUMERO_PROPOSTA
, C.CODIGO AS COOPERATIVA
, S.NOME AS SEGURADORA
, P.NOME AS PRODUTO_NOME
, GL.DATA_ENVIO AS DATA_ENVIO
, PP.OID_MOTIVO_DECLINIO AS OID_MOTIVO_DECLINIO
, MD.DESCRICAO AS DESCRICAO_MOTIVO_DECLINIO
, SUBSTR(PA.CODIGO, 6, 2) AS CODIGO_PONTO_ATENDIMENTO
, PD.NOME_DOCUMENTO
, PS.OID
FROM SIS_OWNER.SEGURADORA S
, PRODUTO P
, PRODUTO_SEGURADORA PS
, USUARIO U_PEND
, USUARIO U_DECLINADO
, USUARIO U_REVISADO
, USUARIO U_EMITIDO
, USUARIO U_CANCELADO
, USUARIO U_RECEBIDO
, GERACAO_LOTE GL
, COOPERATIVA C
, MOTIVO_DECLINIO MD
, PONTO_ATENDIMENTO PA
, PROTOCOLO_DOCUMENTO PD
, PROTOCOLO_PROPOSTA PP
WHERE PP.OID_PRODUTO_SEGURADORA = PS.OID
AND PS.OID_SEGURADORA = S.OID
AND PS.OID_PRODUTO = P.OID
AND PP.OID_USUARIO_MOV_PEND = U_PEND.OID(+)
AND PP.OID_USUARIO_MOV_DECLINADO = U_DECLINADO.OID(+)
AND PP.OID_USUARIO_MOV_REENVIADO = U_REVISADO.OID(+)
AND PP.OID_USUARIO_MOV_EMITIDO = U_EMITIDO.OID(+)
AND PP.OID_USUARIO_MOV_CANCELADO = U_CANCELADO.OID(+)
AND PP.OID_USUARIO_MOV_RECEBIDO = U_RECEBIDO.OID(+)
AND PP.OID_GERACAO_LOTE = GL.OID(+)
AND PP.OID_COOPERATIVA = C.OID(+)
AND PP.OID_MOTIVO_DECLINIO = MD.OID(+)
AND PP.OID_PONTO_ATENDIMENTO = PA.OID(+)
AND PP.OID_PROTOCOLO_DOCUMENTO = PD.OID(+)
AND PP.OID = 1704719 ;Edited by: Luciana T. Angeli on Jul 16, 2010 9:58 AM
Edited by: Luciana T. Angeli on Jul 16, 2010 10:02 AMHi,
Yes, you can do that, but I'm not sure it will be any more efficient, or otherwise better, than what you're doing now.
Since you didn't post CREATE TABLE and INSERT statements for sample data, I'll use tables in the scott schema to illustrate.
The following uses 3 copies of the empgrade table, similar to the way you use several copies of the usario table:
SELECT e.empno, eg.grade AS empno_g
, e.sal, sg.grade AS sal_g
, e.mgr, mg.grade AS mgr_g
, d.dname
FROM scott.emp e
JOIN scott.salgrade eg ON e.empno BETWEEN eg.losal AND eg.hisal
JOIN scott.salgrade sg ON e.sal BETWEEN sg.losal AND sg.hisal
LEFT OUTER JOIN scott.salgrade mg ON e.mgr BETWEEN mg.losal AND mg.hisal
JOIN scott.dept d ON e.deptno = d.deptno
ORDER BY e.empno
;Output:
EMPNO EMPNO_G SAL SAL_G MGR MGR_G DNAME
7369 5 800 1 7902 5 RESEARCH
7499 5 1600 3 7698 5 SALES
7521 5 1250 2 7698 5 SALES
7566 5 2975 4 7839 5 RESEARCH
7654 5 1250 2 7698 5 SALES
7698 5 2850 4 7839 5 SALES
7782 5 2450 4 7839 5 ACCOUNTING
7788 5 3000 4 7566 5 RESEARCH
7839 5 5000 5 ACCOUNTING
7844 5 1500 3 7698 5 SALES
7876 5 1100 1 7788 5 RESEARCH
7900 5 950 1 7698 5 SALES
7902 5 3000 4 7566 5 RESEARCH
7934 5 1300 2 7782 5 ACCOUNTINGThe problem is that you may need 3 different values of the grade column, from 3 different rows of salgrade, for each row of emp.
You can get all 3 grades at once as separate rows, then pivot the results to make them 3 different columns:
WITH all_grades AS
SELECT e.empno, e.sal, e.mgr, e.deptno
, MIN (CASE WHEN e.empno BETWEEN g.losal AND g.hisal THEN grade END) AS empno_g
, MIN (CASE WHEN e.sal BETWEEN g.losal AND g.hisal THEN grade END) AS sal_g
, MIN (CASE WHEN e.mgr BETWEEN g.losal AND g.hisal THEN grade END) AS mgr_g
FROM scott.emp e
JOIN scott.salgrade g ON e.empno BETWEEN g.losal AND g.hisal
OR e.sal BETWEEN g.losal AND g.hisal
OR e.mgr BETWEEN g.losal AND g.hisal
GROUP BY e.empno, e.sal, e.mgr, e.deptno
SELECT a.empno
, a.empno_g
, a.sal
, a.sal_g
, a.mgr
, a.mgr_g
, d.dname
FROM all_grades a
JOIN scott.dept d ON a.deptno = d.deptno
ORDER BY a.empno
; -
Need help with writing a query with dynamic FROM clause
Hi Folks,
I need help with an query that should generate the "FROM" clause dynamically.
My main query is as follows
select DT_SKEY, count(*)
from *???*
where DT_SKEY between 20110601 and 20110719
group by DT_SKEY
having count(*) = 0
order by 1; The "from" clause of the above query should be generated as below
select 'Schema_Name'||'.'||TABLE_NAME
from dba_tables
where OWNER = 'Schema_Name'Simply sticking the later query in the first query does not work.
Any pointers will be appreciated.
Thanks
rogers42Hi,
rogers42 wrote:
Hi Folks,
I need help with an query that should generate the "FROM" clause dynamically.
My main query is as follows
select DT_SKEY, count(*)
from *???*
where DT_SKEY between 20110601 and 20110719
group by DT_SKEY
having count(*) = 0
order by 1; The "from" clause of the above query should be generated as below
select 'Schema_Name'||'.'||TABLE_NAME
from dba_tables
where OWNER = 'Schema_Name'
Remember that anything inside quotes is case-sensitive. Is the owner really "Schema_Name" with a capital S and a capital N, and 8 lower-case letters?
Simply sticking the later query in the first query does not work.Right; the table name must be given when you compile the query. It's not an expression that you can generate in the query itself.
Any pointers will be appreciated.In SQL*Plus, you can do something like the query bleow.
Say you want to count the rows in scott.emp, but you're not certain that the name is emp; it could be emp_2011 or emp_august, or anything else that starts with e. (And the name could change every day, so you can't just look it up now and hard-code it in a query that you want to run in the future.)
Typically, how dynamic SQL works is that some code (such as a preliminary query) gets some of the information you need to write the query first, and you use that information in a SQL statement that is compiled and run after that. For example:
-- Preliminary Query:
COLUMN my_table_name_col NEW_VALUE my_table_name
SELECT table_name AS my_table_name_col
FROM all_tables
WHERE owner = 'SCOTT'
AND table_name LIKE 'E%';
-- Main Query:
SELECT COUNT (*) AS cnt
FROM scott.&my_table_name
;This assumes that the preliminary query will find exactly one row; that is, it assumes that SCOTT has exactly one table whose name starts with E. Could you have 0 tables in the schema, or more than 1? If so, what results would you want? Give a concrete example, preferably suing commonly available tables (like those in the SCOTT schema) so that the poepl who want to help you can re-create the problem and test their ideas.
Edited by: Frank Kulash on Aug 11, 2011 2:30 PM -
How to programmatically count from a dynamic from clause ?
Hi all,
My report contains a user-parameter , say :from_clause, which will receive the from clause of a query from a forms application. We can have for example :from_clause = "from t_table where column_1 = value_1 order by column_2". The "from" keeword is included in the parameter value. In the before report trigger I want to make a count based on that from clause. How to achieve this goal ?
Thank you very much indeed.Hi,
It won't work. You need a control flow case, unless you want to use a hack (internal API) with OutcomeUtils.getActivityRequestOutcome(activityId).
FacesContext context = FacesContext.getCurrentInstance();
NavigationHandler handler = context.getApplication().getNavigationHandler();
handler.handleNavigation(context, null, OutcomeUtils.getActivityRequestOutcome("YourViewId"));
context.renderResponse();Regards,
~ Simon
Maybe you are looking for
-
Vista prompts "Do you want to scan and fix (iPod Name)"
My wife has a new T61 ThinkPad running Vista pro. Previously we connected her iPod to an XP desktop. With this new laptop it regularly prompts with a message "Do you want to scan and fix" the connected iPod, with the options to "Scan and fix (recomme
-
i would be thankful, if somebody could help me.
-
Lightroom 4.2 will not import from Canon 5D Mark III
When trying to import photos from my Canon 5D Mark III into Lightroom 4.2, the import usually freezes up at some arbitrary point. It will either crash lightroom altogether, or it will have a message saying "could not import all files, files could no
-
HT3708 Can I not paste a URL into the field? It keeps beeping at me.
Whenever I try to paste a URL into the link field, I get the beep alert. Does Apple seriously expect people to type in entire URLs?
-
MacBookPro power adapter for UK and Europe
I am going to be spending a semester in the UK and was wondering where I could find a adapter for my power cable.