Select a Dynamic Query
Hello, I have a table with a serie of selects storage into a column, they are VARCHAR2 type and I have a package that retunrs in a function the result of any of this querys, but I want to select them in the SQL command line like
SQL> Select * from (PKG.Function(Cod) )
The result of the function is a query but in VARCHAR2.
That's one, the another is, if there is not a way to do that, I can create a Function that returns a Cursor and them select it in the SQL command line like before.
I now that I can do this with a Function call TABLE, but the problem is that I must create a object over the Data Base, It have the specification of the columns returned by the CURSOR. The problem is that I can't create that object every time I insert a new query and if any of the others querys changes then I must change the object I somenthing more Dynamic. Thank you for your answers.
Hello, Alex...sorry I didn't answer before.
1) I saw your suggestion but I need it in a Select setence.
2) Well I was looking something like that, not exactly a Ref Cursor but something symilar.
3) I have a table, and in this table I have differents selects, they are I kind of "services" used for reportes, etc., recently I need to do another query but using one of this queries in my "From" sentece, but I don't want to rewrite the query because if someone modify that query I need to modify mine too, so I was thinking may be Oracle have something that can execute that query, convert it into table and then used in my select. I now that a can use the function "TABLE", but I'll like something more dynamic, not just only for my select, for any of those selects or new ones.
Thank you for your answer Alex and if you have any idea I appreciate.
Similar Messages
-
DYNAMIC QUERY FOR INSERT USING SELECT
Hi All,
I am facing an issue...I am un bale to do an dynamic query. i have explained my code and the sample create, insert statements. I shud insert values in a table using a select statement dynamically..
create table listing (tel_no varchar2(16), list_key varchar2(30));
create table dummy_extract ( extract_name varchar2(10),extract_query varchar2(400),extract_date date );
create table dummy_query (tel_no varchar2(16), list_key varchar2(30));
insert into listing (tel_no ,header_key) values ('123456','123.23');
insert into dummy_extract (extract_name,extract_query,extract_date) values ('SP','SELECT TEL_NO, LIST_KEY FROM LISTING','10-DEC-2010');
SET SERVEROUTPUT ON
declare
CURSOR CUR_QUERY IS
SELECT * FROM DUMMY_EXTRACT ;
V_STMT VARCHAR2(4000);
BEGIN
FOR I IN CUR_QUERY LOOP
V_STMT := 'INSERT INTO DUMMY_QUERY VALUES ' ||(I.EXTRACT_QUERY ) ;
EXECUTE IMMEDIATE V_STMT using i.extract_query;
DBMS_OUTPUT.PUT_LINE (V_STMT);
END LOOP;
END ;Hi Blue shadow and Saubik,
I tried my query.It shows missing expression...Could you tell me the reason...
SET SERVEROUTPUT ON
declare
CURSOR CUR_QUERY IS
SELECT * FROM DUMMY_EXTRACT ;
V_STMT VARCHAR2(4000);
BEGIN
FOR I IN CUR_QUERY LOOP
--V_STMT := 'INSERT INTO'|| DUMMY_QUERY ||'VALUES ' ||(I.EXTRACT_QUERY ) ;
EXECUTE IMMEDIATE 'INSERT INTO DUMMY_QUERY VALUES ' ||(I.EXTRACT_QUERY ) ;
DBMS_OUTPUT.PUT_LINE (V_STMT);
END LOOP;
END ;
Error report:
ORA-00936: missing expression
ORA-06512: at line 14
00936. 00000 - "missing expression"
*Cause:
*Action: -
Dynamic query table for report based on LOV selected
Hi,
Need some suggestion and guidance how to dynamically query table via lov for report .
Scenario:
Table, TABLE_LIST, has tablename (table in DB) and filter (for where clause) column. The TABLENAME_LOVE is derived from table TABLE_LIST.
SELECT TABLENAME D, TABLENAME R FROM TABLE_LIST
In Page 2,a page select list item,P2_TABLENAME to use TABLENAME_LOV
All data in tables in the table_list have identical structure (columns, triggers, primary key, and so on).
I want to have the report region query from the table based on selected LOV.
Example,
Tablename Filter
TB1
CD2 ACTIVE='Y'
When select TB1, the report regin will query based on TB1.
When select CD2, the report regin will query based on CD2 WHERE ACTIVE='Y'
Question:
How can I query based on &P2_TABLENAME. WHERE &P2_FILTER.
Like
select col1, col2 from &P2_TABLENAME WHERE &P2FILTER
Greatly appreciate any suggestion and some guidance.
TigerwapaHi,
You should always post your Apex version, DB version and other information as suggested in the FAQ.
And the moment you talk report you should state whether it is IR or Classic.
As for your query, have you explored the Report type "SQL Query (PL/SQL function body returning SQL query)" ?
That might be a good fit for what you are trying to achieve.
Regards, -
Build dynamic query depending upon selection of table and columns
Hi ,
I want your views on following requirement :
we r doing generic export to excel functionality .
1.User will select multiple tables and according to tables ,columns on that table will select
2.There can be multiple table
3.depending upon column and table selection , we have to build dynamic query and execute .
Please let me know is it possible .If yes then please tell me how to do above requirement.
Thanks in advanceHi,
Identifiers cannot be used as bind variables, query are parsed
before evaluate bind variables. Identifiers like table name.
For excel you can use some like this:
SET MARKUP HTML ON ENTMAP ON SPOOL ON PREFORMAT OFF
SPOOL test_xls.xls
SELECT colum1||chr(9)||columN FROM tableName;
or CSV:
SELECT colum1|| ',' ||columN FROM tableName;
SPOOL OFF
SET MARKUP HTML OFF ENTMAP OFF SPOOL OFF PREFORMAT ON
For construct the query i suggest to read "Dynamic SQL Statements":
http://www.java2s.com/Tutorial/Oracle/0440__PL-SQL-Statements/0300__Dynamic-SQL.htm
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/dynamic.htm
http://docs.oracle.com/cd/B10500_01/appdev.920/a96590/adg09dyn.htm
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:227413938857
--sgc -
How to find table name(s) in a dynamic query
In one of our (9iAS PORTAL)applications, any user can able to run their query statment and get output. All queries will be executed as dynamic SQL thru' a common shema/user who has 'SELECT' privilege on all tables but all users don't have this privilege on all tables. Now, before executing any query I need to find out what are the table name(s) used in this query to check the privilege for the respective user. How do I extract all table names being used in a dynamic query?.
Thanks
-KrishnamurthyI guess that his users log in to application first, then application uses one account to log in to database, so application are not direct database user since all users share the same account to database. If so, when a user lgins in, you may write it down from application to a database audit table, and you need to write down the dynamic query to the database audit table too, then you may query that audit table to find out. up to here, it looks that your application has to do more to assign what role to a user running the application, since database does not know what user is assessing it.
-
Hi all;
Can u please help me on the following dynamic query code ? I know I am missing the single quote around 2 dates but could not figure out where to put it ! I have tried putting 2 or 3 quotes around 2 bind vars but to no avail.
Want to create a dynamic query to simulate the the following:
select
EMPNO,ENAME,JOB,MGR,HIREDATE from emp where HIREDATE >= to_date('01/01/1981','MM/DD/YYYY') and HIREDATE <= to_date('12/31/1982','MM/DD/YYYY');
dynamic code:
declare
v_q varchar2(4000);
begin
v_q :='select EMPNO,ENAME,JOB,MGR,HIREDATE from emp ';
V_q := V_Q
|| 'where HIREDATE >= '
|| 'to_date(' || :P_DATE1 || ',' ||'''MM/DD/YYYY''' || ' )'
|| 'and HIREDATE <= '
|| 'to_date(' || :P_DATE2 || ',' ||'''MM/DD/YYYY''' || ' )';
-- end the sql
v_q := v_q ||';';
dbms_output.put_line ('V_Q is ' || V_Q);
end;
Thanks.
Zendeclare
v_q varchar2(4000);
v_rec emp%rowtype;
v_cur sys_refcursor;
begin
v_q :='select EMPNO,ENAME,JOB,MGR,HIREDATE from emp ';
V_q := V_Q || 'where HIREDATE >= to_date(:P_DATE1,''MM/DD/YYYY'') and HIREDATE <= to_date(:P_DATE2,''MM/DD/YYYY'')';
dbms_output.put_line ('V_Q is ' || V_Q);
open v_cur
for v_q
using '01/01/1981',
'12/31/1982';
loop
fetch v_cur
into v_rec.empno,
v_rec.ename,
v_rec.job,
v_rec.mgr,
v_rec.hiredate;
exit when v_cur%notfound;
dbms_output.put_line('empno = ' || v_rec.empno);
dbms_output.put_line('ename = ' || v_rec.ename);
dbms_output.put_line('job = ' || v_rec.job);
dbms_output.put_line('mgr = ' || v_rec.mgr);
dbms_output.put_line('hiredate = ' || to_char(v_rec.hiredate,'MM/DD/YYYY'));
dbms_output.put_line('====================');
end loop;
close v_cur;
end;
V_Q is select EMPNO,ENAME,JOB,MGR,HIREDATE from emp where HIREDATE >=
to_date(:P_DATE1,'MM/DD/YYYY') and HIREDATE <= to_date(:P_DATE2,'MM/DD/YYYY')
empno = 7499
ename = ALLEN
job = SALESMAN
mgr = 7698
hiredate = 02/20/1981
====================
empno = 7521
ename = WARD
job = SALESMAN
mgr = 7698
hiredate = 02/22/1981
====================
empno = 7566
ename = JONES
job = MANAGER
mgr = 7839
hiredate = 04/02/1981
====================
empno = 7654
ename = MARTIN
job = SALESMAN
mgr = 7698
hiredate = 09/28/1981
====================
empno = 7698
ename = BLAKE
job = MANAGER
mgr = 7839
hiredate = 05/01/1981
====================
empno = 7782
ename = CLARK
job = MANAGER
mgr = 7839
hiredate = 06/09/1981
====================
empno = 7839
ename = KING
job = PRESIDENT
mgr =
hiredate = 11/17/1981
====================
empno = 7844
ename = TURNER
job = SALESMAN
mgr = 7698
hiredate = 09/08/1981
====================
empno = 7900
ename = JAMES
job = CLERK
mgr = 7698
hiredate = 12/03/1981
====================
empno = 7902
ename = FORD
job = ANALYST
mgr = 7566
hiredate = 12/03/1981
====================
empno = 7934
ename = MILLER
job = CLERK
mgr = 7782
hiredate = 01/23/1982
====================
PL/SQL procedure successfully completed.
SQL> SY. -
Dynamic Query to display a page of records at a time
I need some help creating procedure with a dynamic query that will query a table and pass out a certain number of records (like records 101 - 200 of 20,000). This procedure will receive the column names, table name, where clause, page number and number of records per page. It will then pass back the requested records to be displayed on a PHP page.
Pseudo Code:
Select Dynamic_Columns, ROWNUM
Into Dynamic_Pl_Sql_Table
From Dynamic_Table
Where Dynamic_Where_Clause
Total_Records_Out := Dynamic_PL_Sql_Table.Count
Modulus := Mod(Total_Records_Out, Total_Records_Per_Page_In)
Total_Pages_Out := (Total_Records_Out - Modulus) / Total_Records_Per_Page_In
If Modulus > 0 Then
Total_Pages_Out + 1
End If
Row_Start = Page_Number_In * Total_Records_Per_Page_In
Row_End = Row_Start + Total_Records_Per_Page_In
Results_Out = Dynamic_Pl_Sql_Table(Row_Start ... Row_End)
Any help with this will be appreciated!Maybe this will help you
1) If the Serial is 0 then page break
2) total_rows gives you total number of rows selected.
3) you can apply where clause to this and it will give you appropriate records.
select empno, ename, sal,
mod(row_number() over (order by null),5) serial,
count(*) over () tot_rows from emp ed
EMPNO ENAME SAL SERIAL TOT_ROWS
7369 SMITH 800 1 14
7499 ALLEN 1600 2 14
7521 WARD 1250 3 14
7566 JONES 2975 4 14
7654 MARTIN 1250 0 14
7698 BLAKE 2850 1 14
7934 MILLER 1300 2 14
7788 SCOTT 3000 3 14
7839 KING 5000 4 14
7844 TURNER 1500 0 14
7876 ADAMS 1100 1 14
7900 JAMES 950 2 14
7902 FORD 3000 3 14
7782 CLARK 2450 4 14
14 rows selected.SS -
Dynamic Query
When I run the following dynamic query in the stored procedure and try to build the report then I get the following error Rep:1401 Fatal PL/SQL error occured, Ora-00936 Missing expression. When I am generating the report standalone using the following query , everything is working fine but in Stored procedure , it's giving me the above error, pls help.
create or replace package REP_DELIVERY_LOC_STATISTICS is
TYPE REP_DELIVERY_LOC_STAT_rec IS RECORD(
p_coordinating_facility_id sis_education_pgm_session.coordinating_facility_id%TYPE,
p_PSE_MUNICIPALITY_ID pse_education_pgm_session.PSE_MUNICIPALITY_ID%TYPE,
p_pse_education_pgm_session_id sis_education_pgm_session.pse_education_pgm_session_id%TYPE,
p_course_session_id course_session.course_session_id%TYPE);
TYPE REP_DELIVERY_LOC_STAT_cur IS REF CURSOR RETURN REP_DELIVERY_LOC_STAT_rec;
Type REP_DELIVERY_LOC_STAT_cur_Dyn is REF CURSOR;
FUNCTION REP_DELIVERY_LOC_STATISTICS(p_college_id IN pse_education_pgm_session.delivery_institution_id%TYPE,
p_start_date IN pse_education_pgm_session.session_strt_dte%TYPE,
p_end_date IN pse_education_pgm_session.session_strt_dte%TYPE,
p_coord_facility_join IN varchar2) return REP_DELIVERY_LOC_STAT_cur_Dyn;
end REP_DELIVERY_LOC_STATISTICS;
create or replace package body REP_DELIVERY_LOC_STATISTICS is
FUNCTION REP_DELIVERY_LOC_STATISTICS(p_college_id IN pse_education_pgm_session.delivery_institution_id%TYPE,
p_start_date IN pse_education_pgm_session.session_strt_dte%TYPE,
p_end_date IN pse_education_pgm_session.session_strt_dte%TYPE,
p_coord_facility_join varchar2) return REP_DELIVERY_LOC_STAT_cur_Dyn IS
REP_DELIV_LOC_STAT_CUR_Dyn_Q REP_DELIVERY_LOC_STAT_cur_Dyn;
BEGIN
OPEN REP_DELIV_LOC_STAT_CUR_Dyn_Q FOR
'SELECT distinct
seps.coordinating_facility_id,
peps.PSE_MUNICIPALITY_ID,
seps.pse_education_pgm_session_id,
cs.course_session_id
FROM pse_education_pgm_session peps,
sis_education_pgm_session seps,
course_session cs,
facility fac,
desc_sis_reporting_area depa,
desc_sis_reporting_type dept,
pse_education_program pep
WHERE peps.delivery_institution_id (+) = ' || p_college_id
|| ' and peps.session_strt_dte between ' ||p_start_date||' and ' || p_end_date
|| ' and seps.coordinating_facility_id = fac.facility_id (+)
and seps.pse_education_pgm_session_id (+) = peps.pse_education_pgm_session_id
and seps.pse_education_pgm_session_id = cs.pse_education_pgm_session_id (+)
and pep.pse_education_program_id = peps.pse_education_program_id
and dept.desc_sis_reporting_area_id = depa.desc_sis_reporting_area_id
and pep.desc_sis_reporting_type_id = dept.desc_sis_reporting_type_id
and dept.desc_sis_reporting_area_id = depa.desc_sis_reporting_area_id
and fac.desc_facility_id in (2,3)' || NVL (p_coord_facility_join, '1=1');
return REP_DELIV_LOC_STAT_CUR_Dyn_Q;
END;
end REP_DELIVERY_LOC_STATISTICS;I would sugest to grab a book like
Inside Microsoft SQL Server 2008 T-SQL Querying (chapter 12 - Graphs, Trees, Hierarchies and Recursive Queries) or
Joe Celko's Trees and Hierarchies in SQL for Smarties to get familiar with how model hierarchies using SQL.
What is the meaning of the asterisks in the path?
Here is a dirty example using the Adjacency List model.
SET NOCOUNT ON;
USE tempdb;
GO
CREATE TABLE dbo.T1 (
id int NOT NULL UNIQUE CLUSTERED,
name varchar(50),
rootid int NULL
INSERT INTO dbo.T1 (id,name,rootid)
SELECT 1, 'animals', NULL
UNION ALL
SELECT 2, 'mamal', 1
UNION ALL
SELECT 3, 'cephalopod mollusc', 1
UNION ALL
SELECT 4, 'salt water fish', 1
UNION ALL
SELECT 5, 'fresh water fish', 1
UNION ALL
SELECT 6,'whale', 2
UNION ALL
SELECT 7,'pirana', 5
UNION
SELECT 8,'shark', 4
UNION
SELECT 9, 'octopus', 3;
GO
WITH Tree AS (
SELECT
id, name, rootid,
CAST('/' + [name] + '/' AS varchar(900)) AS mat_path
FROM
dbo.T1
WHERE
rootid IS NULL
UNION ALL
SELECT
C.id, C.name, C.rootid, CAST(P.mat_path + C.name + '/' AS varchar(900))
FROM
Tree AS P
INNER JOIN
dbo.T1 AS C
ON P.id = C.rootid
SELECT
FROM
Tree
ORDER BY
mat_path;
GO
DROP TABLE dbo.T1;
GO
Excuse my poor knowledge of zoology or animal biology.
AMB
Some guidelines for posting questions...
AYÚDANOS A AYUDARTE, guía básica de consejos para formular preguntas -
How to create an LOV based on a dynamic query
Hi,
Can someone tell me how to query a dynamic query for LOV. On my base page I have a dropdown-box (that will show the table names for searching) and is dynamically populated based on users access e.g. if user A logs in he may see 5 values (these values are basically table names) in a drop down if user B logs in he may see 10 values. I also have two input fields one field a user can enter value and the other field is read only and a torch icon for LOV so the user can search and select values that are populated in the input fields on the base page.
How can I have my LOV that takes in a value selected in the dropdown and anyvalue entered in one of the input fields and search in the table selected in the dropdown box.
Basically my LOV should do a search on the table and some search value passed when clicking on the torch icon. So a user can select any table-name in the drop down and my LOV should do a search only on the selected table. Once on the LOV Popup want to have a search field there but it only searched on the table selected in the dropdown on the based page. And the selected value on the LOV Popup page gets populated in fields on the base page.
Any help is appreciated.
ThanksHi,
I have created 4 SQL Based VO's with the following sqls
SELECT header_id AS ID, to_char(order_number) AS NAME
FROM oe_order_headers_all
SELECT party_id AS ID, party_name AS NAME
FROM hz_parties
SELECT quote_header_id AS ID,
(quote_number || CHR (45) || quote_version) AS NAME
FROM aso_quote_headers
SELECT sales_lead_id AS ID, to_char(lead_number) AS NAME
FROM as_sales_leadsI created on LOVRegin and have the following 2 messagestyle items now what do I set in the ViewInstance and View Attribute fields
srcid
srcname
Can you provide some sample code to set ViewUsage and whereclause that I need to put in the controller of LOVRegion.
Thanks -
Hi,
I need to write a Dynamic Query to get the data from the table by using the Input date parameters.
LIke,
SELECT* from table where date_start between to_date('12-14-2004','mm-dd-yyyy') AND
to_date('12-15-2005','mm-dd-yyyy');
How can i write the above query in dynamic sql as i will get the two dates as input in my procedure
Help me in thisOr more preferably use bind variables with the
EXECUTE IMMEDIATE as, if the query will be called
many times, the bind variables will prevent hard
parsing of the statement each time (i.e. it will be
quicker to execute).blushadow,
Yes, the execute immediate using bind variables is better/faster than not using bind variables, but your first example outperforms your second one. This is due to the fact that execute immediate really closes all cursors, and in your first example the cursors are kept open (yes, even though you issue a CLOSE cur_test) in the PL/SQL cursor cache.
SQL> create table i_links
2 as
3 select sysdate - l linkdate from (select level l from dual connect by level <= 10000)
4 /
Tabel is aangemaakt.
SQL> exec dbms_stats.gather_table_stats(user,'I_LINKS')
PL/SQL-procedure is geslaagd.
SQL> create or replace procedure test1 (start_date in date, end_date in date) as
2 CURSOR cur_test IS
3 SELECT count(*)
4 FROM i_links
5 WHERE linkdate BETWEEN start_date AND end_date;
6 v_count NUMBER;
7 begin
8 OPEN cur_test;
9 FETCH cur_test INTO v_count;
10 CLOSE cur_test;
11 --DBMS_OUTPUT.PUT_LINE('Count: '||v_count);
12 end;
13 /
Procedure is aangemaakt.
SQL> create or replace procedure test2 (start_date in date, end_date in date) as
2 v_count NUMBER;
3 begin
4 EXECUTE IMMEDIATE 'SELECT count(*) FROM i_links WHERE linkdate BETWEEN :x1 AND :x2' INTO v_count USING start_date, end_date;
5 --DBMS_OUTPUT.PUT_LINE('Count: '||v_count);
6 end;
7 /
Procedure is aangemaakt.
SQL> begin
2 -- warm up
3 test1(sysdate-365,sysdate);
4 test2(sysdate-365,sysdate);
5 -- begin test
6 runstats_pkg.rs_start;
7 for i in 1..1000
8 loop
9 test1(sysdate-365,sysdate);
10 end loop;
11 runstats_pkg.rs_middle;
12 for i in 1..1000
13 loop
14 test2(sysdate-365,sysdate);
15 end loop;
16 runstats_pkg.rs_stop(100);
17 end;
18 /
Run1 draaide in 341 hsecs
Run2 draaide in 348 hsecs
Run1 draaide in 97,99% van de tijd
Naam Run1 Run2 Verschil
STAT.session cursor cache hits 0 998 998
STAT.opened cursors cumulative 0 1,000 1,000
STAT.parse count (total) 0 1,000 1,000
LATCH.shared pool 1,047 3,043 1,996
STAT.recursive calls 3,001 1,001 -2,000
LATCH.library cache pin allocation 8 2,011 2,003
LATCH.library cache pin 2,048 6,044 3,996
LATCH.library cache 2,056 6,060 4,004
Run1 latches totaal versus run2 -- verschil en percentage
Run1 Run2 Verschil Pct
48,522 60,548 12,026 80.14%
PL/SQL-procedure is geslaagd.Regards,
Rob. -
Question on Dynamic Query Data Source and Form Folders in Oracle Forms 6i
Hi there -
I have one interesting requirement in Oracle Forms.
This is what I wanted to do.
1. Have a LOV and Go button on Form.
2. From LOV, I will select a pre-defined custom table and click Go.
3. Based on the selected custom table, I have to populate the Block (Tabular Format).
4. User should be able to do update, delete, insert on this block.
5. User should be able to use the Oracle Form folders functionality (select only necessary column and save views etc. Std folder functionality).
6. If user selects a different custom table name in the LOV on top, I need to refresh the data from the block based on this new table. Remaining functionality should be as it is (steps 3 to 5).
You can see here, I am going to have dynamic query data source (Table Name as well as column mapping) on the block. I do not know before hand how many columns the user selected table has!
This is what I have planned for this so far but I have some major questions before I can move on with this design:
1. I am going to create a table structure with fixed number of column in form (40 cols assuming that the custom table will not have more that 40 cols). (Kind of limitation but it's okay as of now).
2. Dynamically populate the block based on the table name selected by the user from LOV. Dynamically change the table column names based on the table selected etc.
3. Perform insert, update, delete using PL/SQL package.
So far it looks okay.
Now my real question is,
Can user still be able to user "Folders" functionality here? I have never done this kind of development before and I doubt the dynamic column naming, dynamic column data source will really work for "folders"!
Also, I am not really sure whether user will be able to save these "folder" queries?
Okay so form experts, can you ppl suggest me if this is really going to work? Are there any better ways to do this?
Initially I tried to do this in OA Framework but I got stuck at because as per OAF developer guide "I cannot user OAF personalization for dynamic items, regions etc".
For more info on that thread see this link...
Re: setUserCustomizable issue!
Thanks in advance for the help.Any suggestion anyone?
-
Dynamic Query in Report Builder
HI
I have a doubt:
I need to receive a parameter in my report and I need this parameter in the query, that means, I need to create a dynamic query depending on the value that I receive in one of the parameters that has my report.
I tried to use the resource of Searching by Reference Cursor tool, it is a blue circle in the Data Model View of Report Builder.
When I click this tool, I have an initial code, It is:
function QR_1RefCurDS return <RefCurType> is
begin
end;
In PL/SQL I tried to create to test and to play, this code:
Note: If you want to try only to test, it is simple and works:
create or replace package TEST_REFCURTYPE as
type refcurtype is ref cursor;
function TEST_REFCURTYPE (P_DATE_TO nvarchar2) return refcurtype;
end;
create or replace package body TEST_REFCURTYPE as
function TEST_REFCURTYPE (P_DATE_TO nvarchar2)
return refcurtype is
refcur refcurtype;
mysql varchar(1000);
begin
If P_DATE_TO is not null then
mysql := 'select '''|| P_DATE_TO ||''' from dual';
else
mysql := 'select sysdate from dual';
end if;
open refcur for mysql;
return refcur;
end;
end;
The problem is to pass this example of code to the function QR_1RefCurDS, I do not have a place to make reference to the type:
type refcurtype is ref cursor;
I tested the Unit Program in the Report Builder but it did not work, because all the code I try to write and create, for example in the Event BEFORE REPORT, it opens Funcion( ) …., and I can not make reference to the type refcurtype inside a Function( ).
Would you help me please?
Or there is another way to make a dynamic query in the Report Builder?
Sorry for my English, I am a Brazilian living in Spain.Hi,
you can use lexical parameters in your queries. Instead of a ":" use in the query before the parameter a "&". Then the parameter stands for a part of the query and not for a value (Bind parameter). In the before report trigger you can set this parameters. They can contain parts of SQL like order or where. Make sure that the default value for this lexical parameters are set to get a valid query.
SELECT ENAME, &p_column as COL2 FROM EMP &p_order
and in the trigger something like
IF :p_which_column = 1 THEN
:p_column := 'SAL'
ELSE
Saludos
Rainer -
Error in the Dynamic query in AME
Hi Experts,
I am using the below query but i am facing the error "Ensure the query selects exactly 1 column" in AME Approval group under Dynamic query.
But the query returns only one column when i ran in toad.
select 'person_id:'||a.person_id from
(SELECT to_number(EXTRACT(column_value,'/e/text()')) person_id
from (select (XXSYK_GET_PERSON_ID(:transactionId)) col1 from dual) x,
TABLE(XMLSEQUENCE(EXTRACT(XMLTYPE('<ROW><e>'||REPLACE(col1,',','</e><e>')||'</e></ROW>'),'//e')))
)A
Thanks,
SadeeshThanks !!!!
-
How to enhance Dynamic Query Object TerrSearch (Territory Management)?
Hello Friends,
In the TerrSearch dynamic query object, There are 2 fields Territory_ID and Level_ID. Now i have a requirement to Enhance the Search object using the new field called TERRITORY PATH ID. using which we can search all the entities not only for the terrritory level which we have selected (for example we have assigned the value '01' to LEVEL_ID) but also all the below territory levels of selected territory level.
If we enhance the search object structure CRMST_TMIL_SEARCH (structure of TerrSearch object) using AET to add the Z field called TERRITORY_PATH_ID then which is the suitable BADI where we can add the necessary code to select all the entities based on all the territory levels below the selected territory level.
Please guide me friends how to enhance the TerrSearch object.Hi friend,
Try using MACRO and dynamic WHERE condition.
Group simialr Select statements under a Macro.
Build a dynamic where by checking conditions
Call macro passing dynamic where condition.
TABLES afpo.
DATA: str TYPE string.
*Macro definition
DEFINE operation.
select single *
from afpo into afpo
where (&1). " Dynamic condition
END-OF-DEFINITION.
*Build dynamic WHERE by checking some conditions
*If conditon
CONCATENATE 'AUFNR = ''000000700008''' 'AND POSNR = ''0001''' INTO str SEPARATED BY space.
*Else
CONCATENATE 'AUFNR = ''000000700008''' 'AND POSNR = ''0002''' INTO str SEPARATED BY space.
*Endif.
*Call Macro passing dynamic WHERE condition
operation str. -
Dynamic query with Data Access Layer
I have a program that has a multiselect box (JSP form) to select certifications and then search to see which employee may have them.
I have no issues when searching by only one, but if I select multiple certifications from the multiselect box, it doesn't work. I've tried and tried and I can't seem to figure this out.
Below is the code for returning employees that match what certifications were chosen. Again, it works fine if only 1 was selected. I wish for it to return only the employees that match all selections.
the arguments passed to the DataAccess Layer are an array of certification ID's and the size variable is how many certifications were chosen. The for loop is supposed to dynamically append to the end of the query an extra "AND" sql operator to match up. The 3 tables selected in the query are Employee (a list of employees and ID's), Certificates (a list of possible certificates and their ID's) and Employee_Certificate (a table that matches which employees have which certificates).
What am I doing wrong?
public List certSearch(int cert[], int size) throws Exception{
// connection instance
ArrayList list = new ArrayList();
Connection connection=null;
PreparedStatement pstatement = null;
try
list.clear();
StringBuffer queryString = new StringBuffer("SELECT * from EMPLOYEE, EMPLOYEE_CERTIFICATE, CERTIFICATE" +
" WHERE employee_certificate.employee_id = employee.employee_id " +
"AND certificate.certificate_id = employee_certificate.certificate_id ");
for (int incr = 0; incr < size; incr++){
queryString.append("AND certificate.certificate_id = " + cert[incr] + " ");
String query;
query = queryString.toString();
// Send query to database and store results.
Class.forName(Driver);
//Establish network connection to the db
connection = (Connection) DriverManager.getConnection(url, username, password);
pstatement = (PreparedStatement) connection.prepareStatement(query);
ResultSet rs = pstatement.executeQuery();
while (rs.next())
Employee emp = new Employee();
int empID=Integer.parseInt(rs.getString("employee_id"));
String first=rs.getString("first_name");
String last=rs.getString("last_name");
emp.setID(empID);
emp.setFirstName(first);
emp.setLastName(last);
list.add(emp);
catch(Exception readerr)
System.err.println("Error reading "+ readerr);
finally
try
// close the connection so it can be returned to the
// connection pool then return the SubjectCounselor instance
connection.close();
catch (SQLException ex)
System.err.println("Error reading employee data: " + ex);
return list;
}Edited by: Snadinator on Aug 1, 2009 1:35 PMYou don't get it.
This should work :
public List certSearch(int cert[], int size) throws Exception{
// connection instance
ArrayList list = new ArrayList();
Connection connection=null;
PreparedStatement pstatement = null;
try
list.clear();
String query = buildQuery(cert);
// Send query to database and store results.
Class.forName(Driver);
//Establish network connection to the db
connection = (Connection) DriverManager.getConnection(url, username, password);
pstatement = (PreparedStatement) connection.prepareStatement(query);
ResultSet rs = pstatement.executeQuery();
while (rs.next())
Employee emp = new Employee();
int empID=Integer.parseInt(rs.getString("employee_id"));
String first=rs.getString("first_name");
String last=rs.getString("last_name");
emp.setID(empID);
emp.setFirstName(first);
emp.setLastName(last);
list.add(emp);
catch(Exception readerr)
System.err.println("Error reading "+ readerr);
finally
try
// close the connection so it can be returned to the
// connection pool then return the SubjectCounselor instance
connection.close();
catch (SQLException ex)
System.err.println("Error reading employee data: " + ex);
return list;
// I used the MySQL syntax; if it doesn't work : just enclose the values by single quotes
private String buildQuery(int[] cert) {
StringBuffer queryString = new StringBuffer("SELECT * from EMPLOYEE, EMPLOYEE_CERTIFICATE, CERTIFICATE" +
" WHERE employee_certificate.employee_id = employee.employee_id " +
"AND certificate.certificate_id = employee_certificate.certificate_id " +
"AND certificate.certificate_id IN ( ");
queryString.append(cert[0]);
for (int i = 1; i < cert.length; i++) {
queryString.append(" ,");
queryString.append(cert);
queryString.append(" )");
return queryString.toString();
Maybe you are looking for
-
I have my select statement but I want to make order by 2 things(parameters) that the user choose. I have my parameter as list of values where i have the constant value FIRSTNAME and the constant value DATE. I have something like this select * from TA
-
Has anyone restored from Time Machine and Application permissions okay?
Greetings Apple Discussions: Has anyone restored their system from Time Machine yet and had a successful restore of their application permissions from Time Machine? I just wanted to get confirmation.
-
Can't locate Private folder to delete files
After getting a warning that my startup disk was almost full, I discovered that the reason was one very large folder that contained most of the contents of a previous computer. I had put it there three years ago when I bought this MacBook and forgot
-
11.1.3 - Reporting - User Defined Member Lists
I exported a report from our production environment which is version 9.3.1 and imported into our development environment which is version 11.1.3 via Workspace and the user defined member list was not imported. Is there a way to have them included whe
-
New (and old) battery drains at 1% per 90 seconds
My battery for my late 2008 macbook (aluminum) was draining at a rate of 1% charge every 90 seconds or so. One time recently, I received a warning at the battery icon saying "replace soon" or something of the sort...so I assumed it was the battery. I