index of dynamic query uses
I forgot how to use sql and Oracle dynamic index was linked.For example I would like to have the query like this:
open v_search_results for
'select * from T1, T2, ..., TN
where T1.Col1 = ....
and ...
and TN.ColM like ....
';
(Please note that I have the query as a string inside the symbols apostrophs.)Suggest I index on the columns of the tables T1, T2,..., TN.
These indices are used if someone now opens the cursor "v_search_results" variable to retrieve these data? Or the engine database ignores indexes in dynamic queries?
Execution plan will not change between static and dynamic SQL. It's all SQL for oracle. If the CBO decides if the use of the Index is the right thing to do so it will use.
Tags: Database
Similar Questions
-
Dynamic query using no PL/SQL. Is this Possible?
Hello world
According can the innery query result, we have a different external query I want to know if it is possible with the PL/SQL.
Example:
It's my inner query:
with q1 as
(select
cases where x > 500 then 0
1 other
end value
Of
Table 1)
This is where I stopped, I want to just run either of these queries according to the value.
I know that I can do using PL/SQL, but I want to know if we can do it with pure SQL
Something like that to happen:
What value = 0: run this query: select * from table2
What value = 1: run this query: select * from table2, table3 join using (col1)
Thank you.
VKSure. A bit far from updated him->
satyaki> satyaki> satyaki>select * from v$version; BANNER ---------------------------------------------------------------- Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod PL/SQL Release 10.2.0.3.0 - Production CORE 10.2.0.3.0 Production TNS for 32-bit Windows: Version 10.2.0.3.0 - Production NLSRTL Version 10.2.0.3.0 - Production Elapsed: 00:00:01.82 satyaki> satyaki> satyaki>select k.deptno, 2 k.empno, 3 k.ename, 4 k.job, 5 k.mgr, 6 k.hiredate, 7 k.sal, 8 k.comm, 9 null dname, 10 null loc 11 from emp k 12 where &eid = 0 13 union all 14 select * 15 from ( 16 select * 17 from emp 18 join dept 19 using (deptno) 20 ) 21 where &eid = 1; Enter value for eid: 0 old 12: where &eid = 0 new 12: where 0 = 0 Enter value for eid: 0 old 21: where &eid = 1 new 21: where 0 = 1 DEPTNO EMPNO ENAME JOB MGR HIREDATE SAL COMM DNAME LOC ---------- ---------- ---------- --------- ---------- --------- ---------- ---------- -------------- ------------- 10 9999 SATYAKI SLS 7698 02-NOV-08 55000 3455 10 7777 SOURAV SLS 14-SEP-08 45000 3400 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 20 7566 JONES MANAGER 7839 02-APR-81 2975 30 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7698 BLAKE MANAGER 7839 01-MAY-81 2850 10 7782 CLARK MANAGER 7839 09-JUN-81 4450 20 7788 SCOTT ANALYST 7566 19-APR-87 3000 10 7839 KING PRESIDENT 17-NOV-81 7000 30 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 20 7876 ADAMS CLERK 7788 23-MAY-87 1100 DEPTNO EMPNO ENAME JOB MGR HIREDATE SAL COMM DNAME LOC ---------- ---------- ---------- --------- ---------- --------- ---------- ---------- -------------- ------------- 30 7900 JAMES CLERK 7698 03-DEC-81 950 20 7902 FORD ANALYST 7566 03-DEC-81 3000 13 rows selected. Elapsed: 00:00:00.32 satyaki>/ Enter value for eid: 1 old 12: where &eid = 0 new 12: where 1 = 0 Enter value for eid: 1 old 21: where &eid = 1 new 21: where 1 = 1 DEPTNO EMPNO ENAME JOB MGR HIREDATE SAL COMM DNAME LOC ---------- ---------- ---------- --------- ---------- --------- ---------- ---------- -------------- ------------- 10 9999 SATYAKI SLS 7698 02-NOV-08 55000 3455 ACCOUNTING NEW YORK 10 7777 SOURAV SLS 14-SEP-08 45000 3400 ACCOUNTING NEW YORK 10 7782 CLARK MANAGER 7839 09-JUN-81 4450 ACCOUNTING NEW YORK 10 7839 KING PRESIDENT 17-NOV-81 7000 ACCOUNTING NEW YORK 20 7566 JONES MANAGER 7839 02-APR-81 2975 RESEARCH DALLAS 20 7876 ADAMS CLERK 7788 23-MAY-87 1100 RESEARCH DALLAS 20 7788 SCOTT ANALYST 7566 19-APR-87 3000 RESEARCH DALLAS 20 7902 FORD ANALYST 7566 03-DEC-81 3000 RESEARCH DALLAS 30 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 SALES CHICAGO 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 SALES CHICAGO 30 7698 BLAKE MANAGER 7839 01-MAY-81 2850 SALES CHICAGO DEPTNO EMPNO ENAME JOB MGR HIREDATE SAL COMM DNAME LOC ---------- ---------- ---------- --------- ---------- --------- ---------- ---------- -------------- ------------- 30 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 SALES CHICAGO 30 7900 JAMES CLERK 7698 03-DEC-81 950 SALES CHICAGO 13 rows selected. Elapsed: 00:00:00.24 satyaki>
Kind regards.
LOULOU.
-
Need help tuninng a dynamic query
Hello
We have following question
Select s.* s bose_sites.registration_crm_serial_number
R2 bose_sites.registration_crm_serial_number left on join
s.serialnr = r2.shipserialnr
where s.shipserialnr is null
and (r2.serialnr = ' 052378332000138AE' or (s.serialnr =)
(( "052378332000138AE" and s.shipserialnr is null))
which takes about 40 seconds to execute with the values highlighted in bold being dynamic values
If anyone can help reduce the run time on this request.
There are indexes created on table
INDEX_NAME INDEX_TYPE
------------------------------ ---------------------------
IDX_REG_CRM_SER_NUM_CPC NORMAL
IDX_REG_CRM_SER_NUM_SHIPDATE NORMAL
IDX_REG_CRM_SER_NUM_PARENT_ID NORMAL
IDX_REG_CRM_SER_NUM_ID NORMAL
is it possible that we can capture a dynamic query using DBMS_SQLTUNE
all suggestions will be useful.
Hello
You have one table here
-------------------------------------------------------------------------------
Schema name: SYS
SQL ID: cf2875zz4q4nd
SQL text: select s.* bose_sites.registration_crm_serial_number s
R2 bose_sites.registration_crm_serial_number left on join
s.serialnr = r2.shipserialnr
where s.shipserialnr is null
and (r2.serialnr = '052378332000138AE' or (s.serialnr =
S.shipserialnr and "052378332000138AE" is null))
-------------------------------------------------------------------------------
then why don't you go for a simple query
HTH
-
Index of feature based using SYS_XQSUBSTRAFT
running on 11.2.0.2
I was wondering if this could be a recommended approach to use SYS_XQSUBSTRAFT in a FBI to satisfy a xmlquery using substring-after on a column in a xmlquery? I test, and the optimizer uses the index, but don't know if I'll run into problems in later versions of the Oracle, if/when xmlparser and rewrite engine is updated?
I am selecting from the relational tables using fn:collection (with xmltype xml binary column) and must instr of relational columns in the context of xmlquery... running an explain plan on my query revealed that substring-after has been rewritten to call the SYS_XQSUBSTRAFT function.
Thanks for the tips
I was wondering if this could be a recommended approach to use SYS_XQSUBSTRAFT in a FBI to satisfy a xmlquery using substring-after on a column in a xmlquery?
Well, initially I would have said it's a bad idea, because Oracle has always insisted on not depend on the underlying implementation.
However, it's OK to use XMLQuery in a FBI, like this:
SQL > create table sample_data (str varchar2 (7));
Table created.
SQL > start
2
3 insert into sample_data values (' ABC 123' ");
4 insert into sample_data values ("XYZ-123'");
5 insert into sample_data values (' ABC-456' ");
6 insert into sample_data values (' ABC-789' ");
7
8 end;
9.
PL/SQL procedure successfully completed.
SQL > commit;
Validation complete.
SQL > create index sample_data_ix1 on sample_data)
() 2 xmlcast
3 xmlquery ('substring-after($str, "-")"incidentally as 'str' content return str)
4 as varchar2 (4000)
5 )
6 );
The index is created.
SQL >
SQL >
SQL > set lines 200
SQL > define pages 100
SQL > set autotrace on explain
SQL > select xmlquery)
2 ' for $i in fn:collection("oradb:/DEV/SAMPLE_DATA") / ROW
3 where substring-after($i/STR, "-") = "123".
4 return $i"
5 content of return
(6) as a result
7 double;
RESULT
------------------------------------------------------------------------------------------------
ABC-123 XYZ-123 Execution plan
----------------------------------------------------------
Hash value of plan: 2484218877
------------------------------------------------------------------------------------------------
| ID | Operation | Name | Lines | Bytes | Cost (% CPU). Time |
------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1. | 2 (0) | 00:00:01 |
| 1. GLOBAL TRI | | 1. 2007 | | |
| 2. TABLE ACCESS BY INDEX ROWID | SAMPLE_DATA | 1. 2007 | 2 (0) | 00:00:01 |
|* 3 | INDEX RANGE SCAN | SAMPLE_DATA_IX1 | 1. | 1 (0) | 00:00:01 |
| 4. QUICK DOUBLE | | 1. | 2 (0) | 00:00:01 |
------------------------------------------------------------------------------------------------
Information of predicates (identified by the operation identity card):
---------------------------------------------------
3 - access (SYS_XQSUBSTRAFT("STR",'-') = '123')
Note
-----
-dynamic sample used for this survey (level = 2)
And the funny thing is that Oracle has in fact already rewritten index function:
SQL > select dbms_metadata.get_ddl ('INDEX', 'SAMPLE_DATA_IX1') of double;
DBMS_METADATA. GET_DDL ('INDEX', 'SAMPLE_DATA_IX1')
--------------------------------------------------------------------------------
CREATING INDEX 'DEV '. "' SAMPLE_DATA_IX1 ' ON 'DEV '. "" SAMPLE_DATA "(SYS_XQSUBSTRAFT ("))
((STR','-'))
PCTFREE, INITRANS 10 2 MAXTRANS 167 COMPUTE STATISTICS
STORAGE (INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645)
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS USER_TABLES 1, DEFAULT FLASH_CACHE
FAILURE BY DEFAULT CELL_FLASH_CACHE)
TABLESPACE 'USERS '.
so I guess that your approach is OK, in principle.
Now, I'm wondering no doubt creating an XML related on a pure relational table index.
Have you thought about using SQL/XML XMLElement, XMLAgg etc. instead of fn:collection() features and send it to your main XQuery?
-
Collection of the dynamic query
Hi All-
I'm trying to get the value of the collection through the dynamic query but I am facing some problem please let me know that I hurt.
Created a function like below to run the dynamic query to select statement
create or replace FUNCTION rfunGetColumnValue ( ColumnName VARCHAR2, TableName VARCHAR2, DefaultValue OUT VARCHAR2, Criteria VARCHAR2) RETURN VARCHAR2 IS ReturnValue VARCHAR2 (32767 byte) ; Stmt VARCHAR2 (32767 byte) ; BEGIN stmt := 'begin select '|| ColumnName || ' into :1 from table(:2) ' ||NVL ( Criteria, ' ') || ' Fetch First Row only ; EXCEPTION WHEN OTHERS THEN :2 := SQLERRM; end;' ; dbms_output.put_line (stmt) ; EXECUTE IMMEDIATE stmt USING OUT ReturnValue, OUT DefaultValue; --select Valueinto into Returnvalue from dual; RETURN ReturnValue; END;
Now, I created a folder in the Package
create or replace PACKAGE Collection_PKG is type Bank_rec is RECORD ( SNO NUMBER(10), BANKID NUMBER(5), BANKNAME VARCHAR2(50), BANKSC VARCHAR2(50), ADDEDIT varchar2(1), COMPID number(5), ISBULK number(1), ROWNO number(10), ERROR VARCHAR2(500) ); TYPE Bank_tbl IS TABLE OF Bank_rec; --type Bank_cur is ref cursor return Bank_rec; end Collection_PKG; end Collection_PKG; end Collec tion_PKG;
Now, when I'm Trying the code below
DECLARE V_EXECQUERYPARAM XMLTYPE:= XMLTYPE('<QueryParam> <BankXML> <Bank> <BankID>0</BankID> <BankSC><![CDATA[RCB]]></BankSC> <BankName><![CDATA[Royal challenger Bank]]></BankName> <IsBulk>0</IsBulk> <AddEdit>A</AddEdit> </Bank> </BankXML> </QueryParam>'); BEGIN Rspbanksave( v_SPParamList => V_EXECQUERYPARAM ); END;
create or replace PROCEDURE rspBankSave ( v_SPParamList XMLTYPE DEFAULT NULL) IS V_Addedit VARCHAR2 (1 CHAR) ; Bank_tbl Collection_PKG.BANK_TBL := Collection_PKG.BANK_TBL () ; BEGIN SELECT Row_number () OVER (ORDER BY 1), XT.BankID, XT.BankName, XT.BankSC, XT.AddEdit, v_CompID, XT.IsBulk, CAST (0 AS NUMBER (5)), CASE WHEN MBank.BankID IS NOT NULL THEN CASE WHEN XT.BankSC = MBank.BankSC AND XT.BankName = MBank.BankName THEN 'R104|Entry Already Exist,R114|Short Code Already Exist' WHEN XT.BankSC = MBank.BankSC THEN 'R114|Short Code Already Exist' WHEN XT.BankName = MBank.BankName THEN 'R104|Entry Already Exist' END ELSE NULL END Bulk collect INTO Bank_tbl FROM XMLTABLE ('//QueryParam/BankXML/Bank' PASSING v_SPParamList COLUMNS BankID NUMBER (5) PATH 'BankID', BankName VARCHAR2 ( 50) PATH 'BankName', BankSC VARCHAR2 ( 50) PATH 'BankSC', AddEdit VARCHAR2 ( 1) PATH 'AddEdit', IsBulk NUMBER (1) PATH 'IsBulk') XT LEFT JOIN MBank ON XT.BankID != MBank.BankID AND v_CompID = MBank.CompID AND (XT.BankSC = MBank.BankSC OR XT.BankName = MBank.BankName) ; v_TotalRowCount := SQL%ROWCOUNT; IF (v_TotalRowCount > 0) THEN BEGIN V_Addedit:=rfunGetColumnValue (ColumnName=> 'Upper(AddEdit)',TableName=>'table(Bank_tbl)',DefaultValue=>'',Criteria =>''); END; --SQL Code here END IF; END rspBankSave;
As I've suggested before:
To get the name of the table the column
and as others have:
Type global temporary Tables vs. table
If you give more context, more information about the bigger picture, more information about what you're trying to do and why you're going down the road you go down, you can return more useful information. But you seem reluctant to do.
For the moment, your recent posts seem to just raise the same type of question - why are you doing this?
The normal way to return data to a client is a refcursor.
It is the most effective way.
Not through collections that you seem to be put on the must-do approach.
-
Query using progressive relaxation take more time for execution
HI gurus,
I'm creating a query using the context and the progressive relaxation index
I had started using progressive relaxation after obtaining the forum entries {: identifier of the thread = 2333942}. With the help of progressive relaxation takes more than 7 seconds for each request. Is there a way we can improve the query performance?
create table test_sh4 (text1 clob,text2 clob,text3 clob); begin ctx_ddl.create_preference ('nd_mcd', 'multi_column_datastore'); ctx_ddl.set_attribute ('nd_mcd', 'columns', 'replace (text1, '' '', '''') nd1, text1 text1, replace (text2, '' '', '''') nd2, text2 text2'); ctx_ddl.create_preference ('test_lex1', 'basic_lexer'); ctx_ddl.set_attribute ('test_lex1', 'whitespace', '/\|-_+'); ctx_ddl.create_section_group ('test_sg', 'basic_section_group'); ctx_ddl.add_field_section ('test_sg', 'text1', 'text1', true); ctx_ddl.add_field_section ('test_sg', 'nd1', 'nd1', true); ctx_ddl.add_field_section ('test_sg', 'text2', 'text2', true); ctx_ddl.add_field_section ('test_sg', 'nd2', 'nd2', true); end; create index IX_test_sh4 on test_sh4 (text3) indextype is ctxsys.context parameters ('datastore nd_mcd lexer test_lex1 section group test_sg') ; alter index IX_test_sh4 REBUILD PARAMETERS ('REPLACE SYNC (ON COMMIT)') ;-- sync index on every commit. SELECT SCORE(1) score,t.* FROM test_sh4 t WHERE CONTAINS (text3, ' <query> <textquery> <progression> <seq>{GIFT GRILL STAPLES CARD} within text1</seq> <seq>{GIFTGRILLSTAPLESCARD} within nd1</seq> <seq>{GIFT GRILL STAPLES CARD} within text2</seq> <seq>{GIFTGRILLSTAPLESCARD} within nd2</seq> <seq>((%GIFT% and %GRILL% and %STAPLES% and %CARD%)) within text1</seq> <seq>((%GIFT% and %GRILL% and %STAPLES% and %CARD%)) within text2</seq> <seq>((%GIFT% and %GRILL% and %STAPLES%) or (%GRILL% and %STAPLES% and %CARD%) or (%GIFT% and %STAPLES% and %CARD%) or (%GIFT% and %GRILL% and %CARD%)) within text1</seq> <seq>((%GIFT% and %GRILL% and %STAPLES%) or (%GRILL% and %STAPLES% and %CARD%) or (%GIFT% and %STAPLES% and %CARD%) or (%GIFT% and %GRILL% and %CARD%)) within text2</seq> <seq>((%STAPLES% and %CARD%) or (%GIFT% and %GRILL%) or (%GRILL% and %CARD%) or (%GIFT% and %CARD%) or (%GIFT% and %STAPLES%) or (%GRILL% and %STAPLES%)) within text1</seq> <seq>((%STAPLES% and %CARD%) or (%GIFT% and %GRILL%) or (%GRILL% and %CARD%) or (%GIFT% and %CARD%) or (%GIFT% and %STAPLES%) or (%GRILL% and %STAPLES%)) within text2</seq> <seq>((%GIFT% , %GRILL% , %STAPLES% , %CARD%)) within text1</seq> <seq>((%GIFT% , %GRILL% , %STAPLES% , %CARD%)) within text2</seq> <seq>((!GIFT and !GRILL and !STAPLES and !CARD)) within text1</seq> <seq>((!GIFT and !GRILL and !STAPLES and !CARD)) within text2</seq> <seq>((!GIFT and !GRILL and !STAPLES) or (!GRILL and !STAPLES and !CARD) or (!GIFT and !STAPLES and !CARD) or (!GIFT and !GRILL and !CARD)) within text1</seq> <seq>((!GIFT and !GRILL and !STAPLES) or (!GRILL and !STAPLES and !CARD) or (!GIFT and !STAPLES and !CARD) or (!GIFT and !GRILL and !CARD)) within text2</seq> <seq>((!STAPLES and !CARD) or (!GIFT and !GRILL) or (!GRILL and !CARD) or (!GIFT and !CARD) or (!GIFT and !STAPLES) or (!GRILL and !STAPLES)) within text1</seq> <seq>((!STAPLES and !CARD) or (!GIFT and !GRILL) or (!GRILL and !CARD) or (!GIFT and !CARD) or (!GIFT and !STAPLES) or (!GRILL and !STAPLES)) within text2</seq> <seq>((!GIFT , !GRILL , !STAPLES , !CARD)) within text1</seq> <seq>((!GIFT , !GRILL , !STAPLES , !CARD)) within text2</seq> <seq>((?GIFT and ?GRILL and ?STAPLES and ?CARD)) within text1</seq> <seq>((?GIFT and ?GRILL and ?STAPLES and ?CARD)) within text2</seq> <seq>((?GIFT and ?GRILL and ?STAPLES) or (?GRILL and ?STAPLES and ?CARD) or (?GIFT and ?STAPLES and ?CARD) or (?GIFT and ?GRILL and ?CARD)) within text1</seq> <seq>((?GIFT and ?GRILL and ?STAPLES) or (?GRILL and ?STAPLES and ?CARD) or (?GIFT and ?STAPLES and ?CARD) or (?GIFT and ?GRILL and ?CARD)) within text2</seq> <seq>((?STAPLES and ?CARD) or (?GIFT and ?GRILL) or (?GRILL and ?CARD) or (?GIFT and ?CARD) or (?GIFT and ?STAPLES) or (?GRILL and ?STAPLES)) within text1</seq> <seq>((?STAPLES and ?CARD) or (?GIFT and ?GRILL) or (?GRILL and ?CARD) or (?GIFT and ?CARD) or (?GIFT and ?STAPLES) or (?GRILL and ?STAPLES)) within text2</seq> <seq>((?GIFT , ?GRILL , ?STAPLES , ?CARD)) within text1</seq> <seq>((?GIFT , ?GRILL , ?STAPLES , ?CARD)) within text2</seq> </progression> </textquery> <score datatype="FLOAT" algorithm="default"/> </query>',1) >0 ORDER BY score(1) DESC
Progressive relaxation works best when you select only a limited number of lines. If you retrieve ALL the rows that satisfy the query, then every step of easing should run without worrying.
If you collect - say - the first 10 results, then if the first step in the relaxation gives 10 results so there is no need to execute the next step (actually, due to the internal buffering, which won't be exactly true but he is theoretically correct).
The easiest way to proceed is to reformulate the query in the form
SELECT * FROM)
(Score select (1) SCORE, t.* FROM test_sh4 t WHERE CONTAINS (Text3, '))
(1) > 0 ORDER BY score (1) DESC
...
)
WHERE ROWNUM<=>=>You have discovered that wildcards don't work too well, unless you use SUBSTRING_INDEX. I encourage you to avoid completely if possible, or push down much lower in the progressive relaxation. Usually, GIFT % is a useful term (matches GIFTS, GIFTED, etc.), DON % is generally more effective.
There are a lot of steps in your progressive relaxation. It you want to reduce the number of steps, you can change:
((GIFT and percent of the GRID and STAPLES % and CARD %)) in Text1
((GIFT and percent of the GRID and STAPLES % and CARD %)) in Text2 TO
((CADEAU % et % de la GRILLE et AGRAFES % et CARTE %) * 2) within Text1 ACCUM ((GIFT and percent of the GRID and STAPLES % and CARD %)) in Text2 I don't know if it would have performance benefits - but it is worth trying to see.
-
dynamic query for package does not work
Dear members,
I have problems with a package in the creation and analysis of a dynamic query in the WHERE clause. Here is an example of what I'm trying to do:
PROCEDURE test_status_proc)
wtd_cursor ON cur_type
date_1 IN date
date_2 IN DATE
status in VARCHAR2,
flag in VARCHAR2)
IS
status_sql VARCHAR2 (250): = NULL;
flag_sql Varchar2 (100): = NULL;
BEGIN
Status of the IF = 'A' THEN
lv_status_sql: = 'A ';
lv_flag_sql: = 'Y ';
END IF;
Status of the 'I' = IF THEN
lv_status_sql: = 'A ';
lv_flag_sql: = 'n';
END IF;
Status of the 'R' = IF THEN
lv_status_sql: = "R";
lv_flag_sql: ='* ';
END IF;
Status of the IF = n THEN
lv_status_sql: = 'n';
lv_flag_sql: ='* ';
END IF;
IF status_code = 'IRN' THEN
"lv_status_sql: = '('' N'','' R'');
lv_status_sql: = lv_status_sql | ' OR (s.status = s.flag = "A" AND "N")';
lv_usecalc_sql: ='* ';
END IF;
Status of the = IF'* ' THEN
lv_status_sql: ='* ';
lv_flag_sql: ='* ';
END IF;
OPEN FOR Test_cursor
SELECT * from test_status s
WHERE
s.Daytime BETWEEN date_1 AND date_2
S.status AND decode (lv_status_sql,'* ', s.status, lv_status_sql)
S.flag AND decode (lv_flag_sql,'* ', s.flag, lv_flag_sql);
The problem I have is especially with the condition 'IRN '. The suite WHERE the part of the clause looks like the following in the lv_status_sql, but the query returns all the values:
-(', 'R') OR (s.status = 'A' AND s.flag =' only)
Any help would be much appreciated.
Kind regardsdreporter wrote:
Thanks for your reply and I completely understand your frustration. The problem is sometimes it is very difficult to describe all of the problem due to several reasons. Please take a look at my last post to see if that makes sense.
If you really need SQL dynamic - true dynamic SQL which includes dealing with dynamic number of bind variables - then DBMS_SQL are an excellent interface to use.
You can generate the dynamic SQL statement based on the question of whether the filter criteria is null (do not use) or not null (use as a predicate). For example
if someParam10 is not null then // someParam10 needs to be used as a filter predicate dynamicSQL := dynamicSQL || ' and some_col_10 = :someParam10 '; end if;
This statement can then be analyzed using the DBMS_SQL interface. The binding of values uses the same logic that was used to create predicates. For example
if someParam10 is not null then // someParam10 is used and needs to be bound DBMS_SQL.Bind( myCursor, 'someParam10', someParam10 ); end if;
So, with this approach simplistic, you can easily create a dynamic SQL with variable predicates, dynamically bind these and run the slider.
Bind variables are used in the dynamic SQL statements, as there are very few threats of SQL injection. And the basic principles observed for shareable SQL creation - the same set of parameters not null to filter, will result in the same SQL statement, which allows the cursor within the Pool shared for this SQL statement to be reused.
So, technically, dynamic SQL is not a major problem (if used correctly). The major problem is that if really necessary to address the requirements of the business at hand.
The problem I have with many comments here want to use dynamic SQL statements, is that it is used as one would use a file i/o interface.
For file IO you want standard Open(), Read(), Write() and Close() calls. And you, the appellant, simply pass the name of the file and the data to write or to receive the data read.
Similarly, these posters want to use SQL to open a table and read and write the data column - and do it by calling simply (and dynamically) by specifying the name of the table and column. Approaches to dynamic SQL based on one such concept is wrong. And shows that much of the ignorance of what a RDBMS is and how to use an RDBMS.
-
Hi all;
Can u please help me on the following dynamic query code? I know that I'm missing the single quote around 2 dates, but could not understand where to put it! I tried to put 2 or 3 citations around 2 bind vars but in vain.
To create a dynamic query to simulate the following:
Select
EMPNO, ENAME, JOB, MGR, HIREDATE from emp where HIREDATE > = to_date('01/01/1981','MM/DD/YYYY') and DATERECRUTEMENT < = to_date('12/31/1982','MM/DD/YYYY');
dynamics of code:
declare
v_q varchar2 (4000);
Start
v_q: = "select ENAME, JOB, MGR, EMPNO, 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 of the sql
v_q: = v_q | « ; » ;
dbms_output.put_line ("East V_Q" |) V_Q);
end;
Thank you.
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.
-
Sort on dynamic query problem!
Hello
I have a dynamic query written in pl/sql, when I check "Sort" for each field in the report attribute, error message resurrected as "ORA-01785: ORDER BY item must include the number of an expression in the SELECT list.
If I do not check sort, it works very well. In my applications, I need all the fields sorted by user, how do I solve this problem?
My query as below:
declare
Ask varchar2 (2000): = "select";
s_class varchar2 (1000);
cursor c1 is select * from demo_preference;
Start
for c1_val looping c1
If c1_val.login is not null then
query: query = | » ' || 'login ' | ',';
end if;
If c1_val.id is not null then
query: query = | » ' || 'id ' | ',';
end if;
.......
end loop;
query: = SUBSTR (query, 1, length (query)-1);
s_class: = ' (NVL (: P2_class, "%" |)) ''null%'') = ''%'' || "zero percent" OR
EXISTS (SELECT 1 FROM apex_collections WHERE collection_name = "P2CLASSCOL" AND class = c001))';
query: query = | » ' || ' from ming.reg_report_view1 where '.
|| ' ' || s_class;
Return (Query);
end;Maybe the internal column used when you clicked the sort is not indicated in the report. Try to use aliases when you build the query string, it might help apex internally to identify a column even if its order is changed to another user. After all, the order of the columns in the code is dynamic and I assume that even the number of displayed columns can vary that could sort on a column that is identified by a number not valid.
How about somewhere, displaying the report query so that you know what is the exact query processing, it could give you the best information on the problem.
If the problem persists, use a collection that is extracted these record using the same query string, then replace the report to view the collection and then set the sort column on. This way Summit could get confused about which columns are being sorted and it would just sort on a c001... C050 column as if it were a string (Yes problems with the number of sort columns when you do this).
-
30EA2 - UNIT TESTING - value dynamic query truncating dates time.
So I use the installation of SQL Developer Unit Testing (very nice by the by) for a bit now and just recently upgraded to the latest beta version (3.0.02.83). Looks like a bug has been introduced by which the dynamic query of value are truncate all time of all DATE data type information.
This causes sadness serious for my current test cases and for me since I have to go back to the previous beta version :)I noticed that, in the new 30EA2 parameter:
AddVMOption - Doracle.jdbc.mapDateToTimestamp = false
has been introduced by default in
[SQLDEveloper_install_dir]/sqldeveloper/bin/sqldeveloper.conf
Perhaps it has something to do with the behavior of incorrect date, try to remove the parameter and check again.
-
Hai I want dynamic query for framing
HORN must be updated using dynamic queryCREATE TABLE PI4 (COR varchar2(1),dep varchar2(3),cod_rc varchar2(2)) insert into pi4(dep,cod_rc) values('A01','5C') insert into pi4(dep,cod_rc) values('DAC','5L')
as below
sql_stament is that the variable must be set to above code.UPDATE PI4 SET PI4.COR = ’O’ WHERE PI4.DEP IN ('A01','A02','A03') OR ( PI4. dep IN ('DAC','FTS','G12') AND PI4.COD_RC = '5L' )
Pls help
SCheck below the code where the CO value is assigned dynamically to a p_cor variable
DECLARE v_sql_statement VARCHAR2(32767) := NULL; p_cor VARCHAR2(10) := 'O'; BEGIN v_sql_statement := 'UPDATE PI4 SET PI4.COR ='||p_cor||' WHERE (PI4.DEP IN (''A01'',''A02'',''A03'') OR (PI4. dep IN (''DAC'',''FTS'',''G12'') AND PI4.COD_RC = ''5L''))'; EXECUTE IMMEDIATE v_sql_statement; END;
If you do not need dynamic query to perform the update:
See the code below:
DECLARE p_cor VARCHAR2(10) := 'O'; BEGIN UPDATE PI4 SET PI4.COR =p_cor WHERE PI4.DEP IN ('A01','A02','A03') OR (PI4. dep IN ('DAC','FTS','G12') AND PI4.COD_RC = '5L')); END;
Published by: AP on July 27, 2010 03:39
Published by: AP on July 27, 2010 04:51: end tag code included
-
Data model - dynamic query with parameters
Hi friends, is it possible to dynamically call a query using the parameters of the data models?
I try to have a BEEP report with data model something like that
Data model
Param1
Q1 = Select * from table 1
Q2 = Select * from table 2
If Param1 = X then
FinalQuery = Q1
On the other
FinalQuery = Q2
End
Any help is greately appreciated.
Thank you
SAI.Take a look at the following:
http://www.Oracle.com/global/de/community/BIP/tipps/dynamische_queries/index_en.html
http://blogs.Oracle.com/XmlPublisher/files/BIPublisher_dynamic_column%20Blog.PDF
Thank you!
-
How to map Dynamic Query columns on variables of forms.
Dear all,
This is a correct code for executing a dynamic query and display data.
In this program that I have defined variables ("BOLD" of police) later I binds these with the query (in the second code "BOLD").
How I can map a column in the query, in which case I don't know that the surveyed fields type?
GetData PROCEDURE IS
EXEC_SQL connection_id. PORT;
cursorID EXEC_SQL. CURSTYPE;
sqlstr VARCHAR2 (1000);
loc_ename VARCHAR2 (30);
loc_eno NUMBER;
loc_hiredate DATE;
nIgn PLS_INTEGER;
BEGIN
connection_id: = EXEC_SQL. DEFAULT_CONNECTION;
cursorID: = EXEC_SQL. OPEN_CURSOR (connection_id);
--
-assuming empno is a primary key for the table emp, where clause ensures
-only 0 or 1 row is returned
--
sqlstr: = "select ename, empno, hiredate from emp;
-sqlstr: = sqlstr. 'where empno =' | input_empno;
EXEC_SQL. PARSE (connection_id, cursorID, sqlstr, exec_sql. V7);
-EXEC_SQL. Bind_variable (connection_id, cursorID, ': bn', input_empno);
EXEC_SQL. DEFINE_COLUMN (connection_id, cursorID, 1 loc_ename, 30);
EXEC_SQL. DEFINE_COLUMN (connection_id, cursorID, 2, loc_eno);
EXEC_SQL. DEFINE_COLUMN (connection_id, cursorID, 3, loc_hiredate);
--
-do execute_and_fetch after the analysis of the statement and calling bind_variable and
-If necessary define_column
--
nIgn: = EXEC_SQL. EXECUTE_AND_FETCH (connection_id, cursorID);
IF (nIgn = 0) THEN
TEXT_IO. Put_line ('not Rec');
ELSE IF (nIgn = 1) THEN
TEXT_IO. Put_line ('found an employee');
END IF;
--
-get the values of this line
--
WHILE (EXEC_SQL. FETCH_ROWS (connection_id, cursorID) > 0) LOOP
-nRows: = nRows + 1;
EXEC_SQL. COLUMN_VALUE (connection_id, cursorID, 1, loc_ename);
EXEC_SQL. COLUMN_VALUE (connection_id, cursorID, 2, loc_eno);
EXEC_SQL. COLUMN_VALUE (connection_id, cursorID, 3, loc_hiredate);
MESSAGE(loc_ename||) e '|| loc_eno | » '|| loc_hiredate);
END LOOP;
END IF;
END;If you want to use EXEC_SQL and a dynamic query with unknown data types, but the known table name,
Then you can declare a rowtype variable
for example;NOT TESTED ---A ROUGH IDEA m_emp_row employee_master%rowtype; m_col_cnt number := 0; So when you define collumn, create a procedure to find the column name and its width if it is varchar2 with respect to the column name . Find the column details from the user_tab_columns table ... --------------------------------------------------------------------------------------------------------------------------------------------------- while m_col_cnt < 3 loop m_col_cnt := m_col_cnt +1; proc_find_col_name_width(p_qry ,p_col_no=>m_col_cnt , p_col_name,p_col_width); If p_col_name = 'EMPCODE' then EXEC_SQL.DEFINE_COLUMN(connection_id, cursorID, m_col_cnt , m_emp_row.empcode , p_col_width); elsif p_col_name ='EMPNAME' then EXEC_SQL.DEFINE_COLUMN(connection_id, cursorID, m_col_cnt , m_emp_row.empname , p_col_width); ----- ------- end if; end loop; --------------------------------------------------------------------------------------------------------------------------------------------------- --Your procedure will look like this procedure proc_find_col_name_width(p_qry varchar2,p_col_no number, p_col_name out varchar2,p_col_width out number) is m_col_name varchar2(30); Cursor c1 is Select data_length from user_tab_columns where table_name = 'yr_tab_name' and column_name = m_col_name; m_lastpos number ; m_nxtpos number ; Begin m_lastpos := instr(p_qry,',',1,p_col_no-1); m_nxtpos := instr(p_qry,',',1,p_col_no); If m_lastpos = 0 then --- if only one col m_col_name := substr(p_qry,instr(upper(P_QRY),'SELECT') + 6, instr(upper(P_QRY),'FROM') -1); else If m_nxtpos = 0 then ---if last column m_nxtpos := instr(upper(P_QRY),'FROM') -1; end if; m_col_name := substr(p_qry,m_lastpos+1,m_nxtpos); End if; m_col_name := ltrim(rtrim(m_col_name)); open c1; fetch c1 into p_col_width; close c1; p_col_name := m_col_name; END;
same thing you must apply when retrieving values using exec_sql.column_value
concerning
DoraPublished by: Dora on December 7, 2009 12:20
Published by: Dora on December 7, 2009 12:20
-
Hello
I have to generate a report that contains a query with the database link. This database link is not pre-programmed and would be taken up in another report which contans a link to this report. If this link value of database for the query could be. Can someone guide me hot to write a dynamic select statement so that I could add value of binding of database running.
Thank you
SalmanHello Salman,
You must create a report of "query SQL (PL/SQL function body return SQL query. If you create a normal report of SQL query (using any SQL statement you like - example 1 SELECT FROM DUAL), you can then change the Type of report to this parameter.
Once this is done, you can then create a string that will build the SQL query, you must - what is done when entering the parameter Source in the region in the region to replace the PL/SQL code. How this string is constructed depends on where your data is and so on, but it's just a case of gettnig correct information and concatenated into a single string that forms the SELECT statement.
For example:
DECLARE vTABLE VARCHAR2(100); vSQL VARCHAR2(1000); BEGIN vTABLE := 'MYTABLE@OTHERDB'; vSQL := 'SELECT * FROM ' || vTABLE; RETURN vSQL; END;
The PL/SQL above to build a string:
SELECT * FROM MYTABLE@OTHERDB
who then returned to Apex to generate the report. Also you should probably select the option "use generic column names (analysis of query runtime only)" under this.
Andy
-
dynamic query send multiple values dynamically
Hi all
I'm trying to run a dynamic query. Is it possible to send dynamically deptno and ename?
declare
v_sql varchar2 (4000);
v_resultCol varchar2 (100): = 'ename ';
v_col varchar2 (100): = "deptno";
number of v_num: = 30;
number of v_count;
Start
-v_sql: = 'select'. : v_resultCol |' from emp where ' | : v_col | '= '|| : v_num;
v_sql: = ' select count (ename) from emp where deptno =: a ';
run immediately v_sql in v_count using v_num;
dbms_output.put_line (v_count);
end;
/
Thank youYou can not choose a column dynamically by passing as a bind value because the binding for the name of the column would be simply considered as a string, in this case a count of the a non-empty string would be the same as count (*), a separate of a non-empty string account would be 1, and an empty string County 0 , which is not a lot get you if you try to count the number of records with non-null to a column values.
As a dynamically selected column you must can dynamicaly would build the SQL, but opens you up to SQL Injection attacks:
DECLARE v_col varchar2(100) := 'null)+max((select empno from emp where ename=''CLARK'')'; v_sql VARCHAR2(4000); v_count number; begin v_sql := 'select count('||v_col||') from emp where deptno = :a'; execute immediate v_sql into v_count using 30; dbms_output.put_line(v_count); end; /
a better approach would be to first make sure that the value of v_col is actually a column in the table:
DECLARE v_col varchar2(100) := 'null)+max((select empno from emp where ename=''CLARK'')'; v_sql VARCHAR2(4000); v_count number; begin begin select column_name into v_col from all_tab_cols where owner = 'SCOTT' and table_name='EMP' and column_name = v_col; exception when NO_DATA_FOUND then v_col := '*'; end; v_sql := 'select count('||v_col||') from scott.emp where deptno = :a'; execute immediate v_sql into v_count using 30; dbms_output.put_line(v_count); end; /
Use a box or decode statement in your selection to determine which column to use based on a variable binding:
DECLARE v_col varchar2(100) := 'COMM'; v_sql VARCHAR2(4000); v_count number; begin v_sql := 'select count(case :col_name '|| 'when ''ENAME'' then ename '|| 'when ''COMM'' then to_char(COMM) '|| 'end) '|| 'from scott.emp where deptno = :a'; execute immediate v_sql into v_count using v_col, 30; dbms_output.put_line(v_count); end; /
Published by: Sentinel on October 16, 2008 14:48
Maybe you are looking for
-
Pavilion dv7-6b57nr: misdiagnosis of bios Insydeh20 501 / recovery has not re details save
Case: 3024768463Wiping driveRecovery retriedReceived the error found no indicator is set to unit, use EEPROM to set sku = 2CTO error condition has been detected in the phase of factory update I tried to get like 10 times with disk ordered Hp recov.Tr
-
histogram with just a few columns from a table
I want to get a histogram of a few columns from a table (4 - 6-... 22)
-
Why hasn't MX320 Solution Menu scan option
When I initially installed my MX320 in Windows Home Premium, I installed the Menu Solution and used successfully to scan documenets and back up the files on my computer for several years. After my mother destroyed auto map, I put together a new compu
-
I found an old vista home basic dvd with a key, how can check whether key works, but not install it? some dvd install can be live boot from themselves too [password required for a direct start?]?
-
Hello I have read several posts on ContentHandler and attachments of managers (KB "How - to create a Manager custom attachment on the BlackBerry"), but I couldn't even find a solution to my problem. Is there a way to call the Blackberry attachment pr