Using Dynamic Query in For Loop
I have a doubt whether i can use the result from dynamic query in the for loop.
for example,
declare
v_sql varchar2(1000);
v_Id INTEGER;
begin
v_sql := 'select id from table1 where id in ('||v_Id||')';
FOR i in vsql LOOP
dbms_output.put_line(i.id);
end loop;
end;
The above query is possible ?
And here's a basic example of opening up a cursor for your dynamic query...
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_sql varchar2(2000);
3 v_cur sys_refcursor;
4 i emp.sal%type;
5 begin
6 v_sql := 'select sal from emp';
7 open v_cur for v_sql;
8 loop
9 fetch v_cur into i;
10 exit when v_cur%NOTFOUND;
11 dbms_output.put_line('Salary: '||i);
12 end loop;
13* end;
SQL> /
Salary: 800
Salary: 1600
Salary: 1250
Salary: 2975
Salary: 1250
Salary: 2850
Salary: 2450
Salary: 3000
Salary: 5000
Salary: 1500
Salary: 1100
Salary: 950
Salary: 3000
Salary: 1300
PL/SQL procedure successfully completed.
SQL>
Similar Messages
-
Geting ORA 936 -while building dynamic query in for loop.
HI,
I hav written a SP and its compiled and giving me the results for the data I am quering but giving ORA936 - missing expressin and giving ORA 6512 at 2 lines. Please help me me out where I am going wrong.
CREATE OR REPLACE TYPE LIST as VARRAY(5000) of NUMBER;
CREATE OR REPLACE PROCEDURE test( V_id IN LIST,
v-fdate IN DATE,
v-tdate IN DATE,
v_flg IN CHAR)
AS
TYPE opfld IS RECORD (
FID TAB.ID%TYPE,
FCURR TAB.CURR %TYPE,
FCNT TAB.CNT%TYPE,
FTOT TAB.TOT%TYPE );
TYPE OPLIST IS REF CURSOR;
Rc oplist;
Edtab opfld;
Selstr VACHAR2(200);
Whstr1 VACHAR2(200);
Whstr2 VACHAR2(200);
Whstr3 VACHAR2(200);
Whstr VACHAR2(200);
Grpstr VACHAR2(200);
Andstr VACHAR2(200);
Fullstr VACHAR2(200);
BEGIN
Selstr := ‘SELECT col1,col2,sum(col3),sum(col4) from tab1 ’;
Whstr1 := ‘ WHERE tdate BETWEEN TO_DATE(‘||’’’’||vfdate||’’’’||’)’;
Whstr2: = ‘ AND TO_DATE(‘||’’’’||vtdate||’’’’||’)’;
Whstr := whstr1||whstr2;
Grpstr := ‘GROUP BY col1,col2’;
IF v_flg IS NOT NULL THEN
Whstr3 := whstr||’AND FLAG = ‘||v_flg;
else
Whstr3 := whstr ;
END IF;
FOR I IN 1..id.COUNT LOOP
BEGIN
Andstr := ‘ AND id =’|| v_id(i);
Whstr := whstr3 || andstr ;
Fullstr := selstr||whstr||grpstr;
OPEN rc for fullstr;
LOOP
FETCH rc into edtab
EXIT when rc%NOTFOUND;
END LOOP;
Andstr := ‘’;
Whstr :=’’;
END; ---BEGIN of FOR loop
END LOOP; -- for end
CLOSE rc;
END; -- proc end
Created above SP and its compiled. When I try to execute the SP with below code I am getting--
DECLARE
V_t LIST;
BEGIN
V_t:= LIST();
V_t.EXTEND(10);
V_t(1) := 10;
V_t(2) := 20;
Test(v_t,’25-APR-2012’,’30-APR-2012’,’Y’);
END;
The SP is building correct dynamic querry and its getting executed for id = 10 and 20, giving the correct results but though I defined only 2 ids while executing and written FOR lOOP upto ID.COUNT its building query for third time and that time its not getting id, so for the third time the last part of where clause is built like
SELECT.....
WHERE....
AND id = (its taking blank here)
GROUP BY ...;
and thus its giving me ORA 936 missing expression and ORA 06152 at line of RECORD TYPE declaration and line of OPEN rc for fullstr;
ERROR at line 1
ORA 00936 misssing expresiion
ORA 006152 at line 9
ORA 006512 at line 87
I hav put DBMS_OUTPUT statements @ every build of dynamic wuery and its correct. here I have not copid the code I hav typed hereso not wriiten DBMS_OUTPUT.
I tried lot of ways redefining Andstr := ‘’;
Whstr :=’’; after for endloop but its giving the same error. is this because I am using varray? If am providing 2 ids in anonymous block then how its building query for third blank ID value.
Please help me out here..
Thanks a lot..>
I hav written a SP and its compiled and giving me the results for the data I am quering
>
Then you should have posted the one that compiles and gives you results.
The code you posted will not compile without errors. Edit your original post and provide the corrected code.
When you do please add \ tags on the line before and after the code to preserve formatting. See the FAQ for details. -
How to use dynamic query for Result table
Hello Experts,
I want to use dynamic query and then display the result in the assignment block.
Using dynamic query BTQAct and BTQRAct and base on some search criteria i want tofilter and then append the result in the result table of that custom context node, and then it should display the result in the view in UI.
SO can you please provide me the samplle code on how to use the dynamic query and append in the result table.
Regards.Hi,
Please find below sample code:
data: query TYPE REF TO cl_crm_bol_dquery_service,
result TYPE REF TO if_bol_bo_col.
DATA: lt_params TYPE crmt_name_value_pair_tab,
lwa_params TYPE crmt_name_value_pair.
query = cl_crm_bol_dquery_service=>get_instance( 'BTQAct' ). " Get instance of dynamic query
Set general query parameter for maximum number of hits
lwa_params-name = 'MAX_HITS' .
lwa_params-value = '50'.
APPEND lwa_params TO lt_params.
query->set_query_parameters( it_parameters = lt_params ).
query->add_selection_param( iv_attr_name = 'OBJECT_ID'
iv_sign = 'I'
iv_option = 'EQ'
iv_low = <lv_objectid>
iv_high = '' ). " Set your search criteria. Repeat this code if you have multiple parameters
"You can find possible search options for a query object in GENIL_BOL_BROWSER
result ?= query->get_query_result( ). " Get result from your search query
me->typed_context-> <your result context node>->set_collection( result ).
Here you will have to create a context node in your view which would refer to query result object like for BTQAct its BTQRAct
Hope this helps.
e Regards,
Bhushan -
Converting rows to columns using dynamic query.
I am trying to use the below code that I founnd on the web to conver rows to columns. the reason that I want to use dynamic query is that the number of rows are not know and changes.
declare
lv_sql varchar2(32767) := null ;
begin
lv_sql := 'SELECT Iplineno ';
for lv_rec in (SELECT distinct vendor from bidtabs where letting = '10021200' and call ='021')
loop
lv_sql := lv_sql
|| CHR(10)
|| ', MAX( DECODE( vendor, '
|| chr(39)
|| lv_rec.vendor
|| CHR(39)
|| ', bidprice, NULL ) ) as "'
|| lv_rec.vendor
|| '" ' ;
end loop;
lv_sql := lv_sql
|| CHR(10)
|| 'FROM bidtabs where letting = ''10021200'' and call = ''021'' and lineflag = ''L'' '
|| CHR(10)
|| 'GROUP BY iplineno ;' ;
here is the result
BIDPRICE CALL IPLINENO LETTING VENDOR
9,585 021 0010 10021200 C0104
1,000 021 0020 10021200 C0104
1,000 021 0030 10021200 C0104
17 021 0040 10021200 C0104
5 021 0050 10021200 C0104
11,420 021 0010 10021200 K0054
1,100 021 0020 10021200 K0054
1,100 021 0030 10021200 K0054
5 021 0040 10021200 K0054
3 021 0050 10021200 K0054
8,010 021 0010 10021200 V070
900 021 0020 10021200 V070
1,320 021 0030 10021200 V070
11 021 0040 10021200 V070
3 021 0050 10021200 V070
and here is the desired output
CALL IPLINENO LETTING C0104 K0054 V070
021 0010 10021200 9,585 11,420 8,010
021 0020 10021200 1,000 1,100 900
021 0030 10021200 1,000 1,100 1,320
021 0040 10021200 17 5 11
021 0050 10021200 5 3 3Here is the error message I am getting:
RA-06550: line 22, column 43:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
begin case declare end exception exit for goto if loop mod
null pragma raise return select update while with
<an identifier> <a double-quoted delimited-identifier>
<a bind variable> << close current delete fetch lock insert
open rollback savepoint set sql execute commit forall merge
pipe -
How do we use if statement in labview?moreover can i use if statement inside for loop?
how do we use if statement in labview?moreover can i use if statement inside for loop?
The if statement in LabVIEW is the Case structure. You can find that on the Structures palette right next to the For Loop. If you're still on the same subject about terminating a for loop early, then what you do is enclose your functions inside the loop with a case statment and make one of the case's empty except for one or more constants that you might have to wire. Hopefully, the attached picture will explain what I mean. Also, as I mentioned in one of your other posts, I think this technique is not as good as using a while loop. The array in the attached example is the same size no matter what and you may have to handle stripping extra or invalid elements.
Attachments:
For_Loop_with_Case.jpg 21 KB -
How to use Add Query Criteria for the MySQL data Base in Netbeans ?
How to use Add Query Criteria for the MySQL data Base in Netbeans Visual web pack.
When the Query Criteria is add like
SELECT ALL counselors.counselors_id, counselors.first_name, counselors.telephone,counselors.email
FROM counselors WHERE counselors.counselors_id = ?
when i run this Query in the Query Window
i get a error message Box saying
Query Processing Error Parameter metadata not available for the given statement
if i run the Query with out Query Criteria its working fine.*I am glad I am not the only one who have this problem. Part of issue has been described as above, there are something more in my case.
Whenever I try to call ****_tabRowSet.setObject(1, userDropList.getSeleted()); I got error message as shown below:*
The Java codes are:
public void dropDown1_processValueChange(ValueChangeEvent event) {
Object s = this.dropDown1.getSelected();
try {
this.User_tabDataProvider1.setCursorRow(this.User_tabDataProvider1.findFirst("User_Tab.User_ID", s));
this.getSessionBean1().getTrip_tabRowSet1().setObject(1, s);
this.Trip_tabDataProvider1.refresh();
} catch (Exception e) {
this.log("Error: ", e);
this.error("Error: Cannot select user"+e.getMessage());
SQL statement for Trip_tabRowSet:
SELECT ALL Trip_Tab.Trip_Date,
Trip_Tab.User_ID,
Trip_Tab.Destination
FROM Trip_Tab
WHERE Trip_Tab.User_ID = ?
Error messages are shown below:
phase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl@5abf3f) threw exception: com.sun.rave.web.ui.appbase.ApplicationException: java.sql.SQLException: No value specified for parameter 1 java.sql.SQLException: No value specified for parameter 1
com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.cleanup(ViewHandlerImpl.java:559)
com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.afterPhase(ViewHandlerImpl.java:435)
com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:274)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:140)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:397)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184)
com.sun.webui.jsf.util.UploadFilter.doFilter(UploadFilter.java:240)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:216)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:216)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:276)
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:536)
org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:240)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:179)
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:73)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:182)
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
com.sun.enterprise.web.VirtualServerPipeline.invoke(VirtualServerPipeline.java:120)
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:939)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:137)
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:536)
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:939)
org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:239)
com.sun.enterprise.web.connector.grizzly.ProcessorTask.invokeAdapter(ProcessorTask.java:667)
com.sun.enterprise.web.connector.grizzly.ProcessorTask.processNonBlocked(ProcessorTask.java:574)
com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:844)
com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask(ReadTask.java:287)
com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(ReadTask.java:212)
com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:252)
com.sun.enterprise.web.connector.grizzly.WorkerThread.run(WorkerThread.java:75)
tandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.sql.SQLException: No value specified for parameter 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:1674)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:1622)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1332)
at com.sun.sql.rowset.internal.CachedRowSetXReader.readData(CachedRowSetXReader.java:193)
at com.sun.sql.rowset.CachedRowSetXImpl.execute(CachedRowSetXImpl.java:979)
at com.sun.sql.rowset.CachedRowSetXImpl.execute(CachedRowSetXImpl.java:1439)
at com.sun.data.provider.impl.CachedRowSetDataProvider.checkExecute(CachedRowSetDataProvider.java:1274)
at com.sun.data.provider.impl.CachedRowSetDataProvider.setCursorRow(CachedRowSetDataProvider.java:335)
at com.sun.data.provider.impl.CachedRowSetDataProvider.setCursorIndex(CachedRowSetDataProvider.java:306)
at com.sun.data.provider.impl.CachedRowSetDataProvider.getRowCount(CachedRowSetDataProvider.java:639)
at com.sun.webui.jsf.component.TableRowGroup.getRowKeys(TableRowGroup.java:1236)
at com.sun.webui.jsf.component.TableRowGroup.getFilteredRowKeys(TableRowGroup.java:820)
at com.sun.webui.jsf.component.TableRowGroup.getRowCount(TableRowGroup.java:1179)
at com.sun.webui.jsf.component.Table.getRowCount(Table.java:831)
at com.sun.webui.jsf.renderkit.html.TableRenderer.renderTitle(TableRenderer.java:420)
at com.sun.webui.jsf.renderkit.html.TableRenderer.encodeBegin(TableRenderer.java:143)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:810)
at com.sun.webui.jsf.component.Table.encodeBegin(Table.java:1280)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:881)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:889)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:889)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:889)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:889)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:889)
at com.sun.faces.application.ViewHandlerImpl.doRenderView(ViewHandlerImpl.java:271)
at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:182)
at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.renderView(ViewHandlerImpl.java:285)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:133)
at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:244)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:140)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:397)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184)
at com.sun.webui.jsf.util.UploadFilter.doFilter(UploadFilter.java:240)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:216)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:216)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:276)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:536)
at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:179)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:73)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:182)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
at com.sun.enterprise.web.VirtualServerPipeline.invoke(VirtualServerPipeline.java:120)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:939)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:137)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:536)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:939)
at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:239)
at com.sun.enterprise.web.connector.grizzly.ProcessorTask.invokeAdapter(ProcessorTask.java:667)
at com.sun.enterprise.web.connector.grizzly.ProcessorTask.processNonBlocked(ProcessorTask.java:574)
at com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:844)
at com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask(ReadTask.java:287)
at com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(ReadTask.java:212)
at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:252)
at com.sun.enterprise.web.connector.grizzly.WorkerThread.run(WorkerThread.java:75)
Also when I tried to update my MYSQL connector / J driver to version 5.1.5 from 5.0.5 (NB 5.5.1) and 5.0.7 (NB 6.1), I could not get it work (looooong time to search some JDBC classes and with no response in the end) on both of my Netbean 5.5.1(on PC) and Netbean 6.1(on laptop) IDEs.
Could anybody look into this issue.
Many thanks
Edited by: linqing on Nov 22, 2007 4:48 AM -
How to use reverse function in FOR loop
Hi,
Can we use REVERSE function in for loop.
If so can u please give an explanation with some example.
Thanks in advance.
Satya.In SQL you could do this...
SQL> ed
Wrote file afiedt.buf
1 select empno, ename, replace(sys_connect_by_path(ch,'|'),'|') as rev_ename
2 from (
3 select empno, ename, case when rn <= length(ename) then substr(ename, length(ename)-rn+1, 1) else null end as ch, rn
4 from emp
5 ,(select rownum as rn from dual connect by rownum <= (select max(length(ename)) from emp))
6 where case when rn <= length(ename) then substr(ename, length(ename)-rn+1, 1) else null end is not null
7 )
8 where connect_by_isleaf = 1
9 connect by empno = prior empno and rn = prior rn + 1
10 start with rn = 1
11* order by empno
SQL> /
EMPNO ENAME REV_ENAME
7369 SMITH HTIMS
7499 ALLEN NELLA
7521 WARD DRAW
7566 JONES SENOJ
7654 MARTIN NITRAM
7698 BLAKE EKALB
7782 CLARK KRALC
7788 SCOTT TTOCS
7839 KING GNIK
7844 TURNER RENRUT
7876 ADAMS SMADA
7900 JAMES SEMAJ
7902 FORD DROF
7934 MILLER RELLIM
14 rows selected.
SQL> -
Revision: 11999
Revision: 11999
Author: [email protected]
Date: 2009-11-19 11:37:09 -0800 (Thu, 19 Nov 2009)
Log Message:
Fixed: ASC-3889 - Using setting in a for loop causes Verify error
Notes: emit pop after callstatic to a void function to balance the stack.
Reviewer: jodyer+
Testing: asc,tamarin,flex checkin tests
Ticket Links:
http://bugs.adobe.com/jira/browse/ASC-3889
Modified Paths:
flex/sdk/trunk/modules/asc/src/java/macromedia/asc/semantics/CodeGenerator.javaBlacklisting the ahci module does indeed get rid of the error. Would be nice to figure out why it was conflicting with the ahci module though.
I have not yet tried the 173xx drivers, but the latest drivers for the Quadro FX 580 are the 256.53 drivers according to nvidia.
Posted at the nV forums (http://www.nvnews.net/vbulletin/showthread.php?t=155282), so we'll see what they suggest. -
Finding minimum value in each row using dynamic query
need to find the minimum and maximum value from each row using dynamic query
[from curr] will be given as input
TukyDECLARE @t TABLE(a INT,b INT,c INT);
INSERT @t VALUES(1,2,3),(9,8,7),(4,6,5);
SELECT *
, ( SELECT MAX(val)
FROM (VALUES (a)
, (b)
, (c)
) AS value(val)
) AS MaxVal
, ( SELECT MIN(val)
FROM (VALUES (a)
, (b)
, (c)
) AS value(val)
) AS MinVal
FROM @t;
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
How to use three part name with using dynamic query.
Dear all, (sqlserver 2008 express r2)
q1)following is showing error, is it possible to accomplish the task with out using dynamic query.
DECLARE @A VARCHAR(100)
DECLARE @A1 VARCHAR(100)
SET @A='DB1'
SET @A1='DBO'
SELECT * FROM @[email protected]
q2) table value function is not accepting dynamic query , is there any way to do this task.
yours sincerleyCertain parts in an SQL query like FROM tablename cannot be local variables. In such a case, dynamic SQL can be applied:
http://www.sqlusa.com/bestpractices/dynamicsql/
As noted above, more information needed to decide if dynamic SQL the correct solution in this instance.
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
Best practice: Using break statement inside for loop
Hi All,
Using break statment inside FOR loop is a best practice or not?
I have given some sample code:
1. With break statement
2. With some boolean variable that decide whether to come out of the loop or not.
for(int i = 0; i < 10; i++){
if(i == 5){
break;
boolean breakForLoop = false;
for(int i = 0; i < 10 && !breakForLoop; i++){
if(i == 5){
breakForLoop = true;
The example may be a stupid one. But i want to know which one is good?
Thanks and Regards,
Ashok kumar B.Actually, it's bad practice to use break anywhere other than in conjunction with a switch statement.Presumably, if you favour:
boolean test = true;
while (test)
test = foo && bar;
if (test)
}overfor (;;)
if (! ( foo && bar) ) break;
}then you also favour
boolean test = foo && bar;
if (test)
}overif (foo && bar)
}Or can you justify your statement with any example which doesn't cause more complexity, more variables in scope, and multiple assignments and tests? -
How to use dynamic query for this ??
hi , i am new to ABAP. i got a requirement to write dynamic query for the following code.
kindly address. two set of queries are same.but condition is different.
.IF p_psd EQ ' '.
*C--End of change DF 1232137- (Transport # :CIDK980530 )
*C--FETCH THE Deliverd Quantiity and Material Number
SELECT aufnr "ORDER number
wemng "Quantity of goods received for the order item
matnr "MATERIAL NUMBER
pwerk "PLANT
dauat "Order Type
FROM afpo
INTO TABLE t_afpo
WHERE aufnr IN s_order
AND wemng IN s_dqt
AND matnr IN s_matnr
AND pwerk IN s_plant
AND dauat = c_ro.
IF sy-subrc = 0.
SORT t_afpo BY aufnr matnr pwerk.
*C--FETCH THE OBJECT NUMBER
SELECT aufnr "ORDER number
objnr "Object number
FROM aufk
INTO TABLE t_aufk
FOR ALL ENTRIES IN t_afpo
WHERE aufnr = t_afpo-aufnr.
IF sy-subrc = 0.
SORT t_aufk BY aufnr objnr.
*C--FETCH THE Target Quantiity
SELECT aufnr "ORDER number
gamng "Total order quantity target quantity
FROM afko
INTO TABLE t_afko
FOR ALL ENTRIES IN t_afpo
WHERE aufnr = t_afpo-aufnr
AND gamng IN s_tqt.
IF sy-subrc = 0.
SORT t_afko BY aufnr .
ENDIF.
ENDIF.
ELSE.
MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
LEAVE LIST-PROCESSING.
ENDIF.
*C--Begin of change DF 1232137- (Transport # :CIDK980530 )
ENDIF.
IF p_psd EQ c_x.
SELECT aufnr "ORDER number
wemng "Quantity of goods received for the order item
matnr "MATERIAL NUMBER
pwerk "PLANT
dauat "Order Type
FROM afpo
INTO TABLE t_afpo
WHERE aufnr IN s_order
AND wemng > 0
AND matnr IN s_matnr
AND pwerk IN s_plant
AND dauat = c_ro.
if sy-subrc = 0.
*C--FETCH THE OBJECT NUMBER
IF NOT t_afpo[] IS INITIAL.
SORT t_afpo BY aufnr matnr pwerk.
SELECT aufnr "ORDER number
objnr "Object number
FROM aufk
INTO TABLE t_aufk
FOR ALL ENTRIES IN t_afpo
WHERE aufnr = t_afpo-aufnr.
IF sy-subrc = 0.
SORT t_afko BY aufnr gamng.
ELSE.
MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
LEAVE LIST-PROCESSING.
ENDIF.
ENDIF.
IF NOT t_afpo[] IS INITIAL.
*C--FETCH THE Target Quantiity
SELECT aufnr "ORDER number
gamng "Total order quantity target quantity
FROM afko
INTO TABLE t_afko
FOR ALL ENTRIES IN t_afpo
WHERE aufnr = t_afpo-aufnr
AND gamng <> t_afpo-wemng .
IF sy-subrc = 0.
SORT t_afko BY aufnr gamng.
ELSE.
MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
LEAVE LIST-PROCESSING.
ENDIF.
ENDIF.
ELSE.
MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
LEAVE LIST-PROCESSING.
ENDIF.
Edited by: Thomas Zloch on Jan 5, 2011 1:30 PM please use code tagsHi 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. -
Process having dynamic subqery in for loop cursor
I created a process that puts all retrieved rows into a collection. Users can select on quite a few columns, say unit, last_name, shift, etc. When the query is built based on users' inputs, I can't get it working using a For Loop Cursor (code 3.). But I tried and found out that sample 1 is working while sample 2 is not.
Can anyone please help? give advices or point to the right direction?
Thanks very much in advance!!!
DC
sample 1, works:
begin
:P8_TEST_CURSOR := '';
for c in ( select ename from emp ) loop
:P8_TEST_CURSOR := :P8_TEST_CURSOR || ', ' || c.ename;
end loop;
end;
sample 2, does not work:
declare
q varchar2(2000) := 'select ename from emp';
begin
:P8_TEST_CURSOR := '';
for c in q loop
:P8_TEST_CURSOR := :P8_TEST_CURSOR || ', ' || c.ename;
end loop;
end;
code 3, my actually pursuing code, sorry it's long:
declare
q varchar2(2000);
v_unit_id cpd_units.id%TYPE;
begin
q := 'select distinct e.user_id
, nvl(to_char(law_common.get_star_no(e.id)), ''-'') star_no
, nvl(e.last_nme, ''-'') last_name
, nvl(e.first_nme, ''-'') first_name
, nvl(e.MIDDLE_INITIAL, ''-'') middle_initial
, e.employee_no
, nvl(to_char(e.employee_position_cd), ''-'')
, nvl(w.uod_cd, e.cpd_unit_assigned_no) unit
, nvl(w.watch_cd, ''-'')
from cpd_employees e, dpv2wtch w
where e.status_i = ''Y''
and nvl(e.resignation_date, sysdate) >= sysdate
and e.employee_position_cd in (''9112'', ''9152'', ''9153'', ''9155'', ''9161'', ''9164'')
and e.user_id is not null
and w.ssn_no(+) = e.ssn
and e.user_id not in (select c001
from htmldb_collections
where collection_name = ''ACTIVITY''
if :P300_STAR_NO is not NULL then
q := q || ' and e.id = law_common.get_employee_id(:P300_STAR_NO)';
--q := q || ' and law_common.get_star_no(e.id) = :P300_STAR_NO';
end if;
if :P300_EMPLOYEE_NO is not NULL then
q := q || ' and e.employee_no = :P300_EMPLOYEE_NO';
end if;
if :P300_USER_ID is not NULL then
q := q || ' and e.user_id = :P300_USER_ID';
end if;
if :P300_LAST_NAME is not NULL then
q := q || ' and upper(e.last_nme) like ''' || upper(:P300_LAST_NAME) || '%''';
end if;
if :P300_FIRST_NAME is not NULL then
q := q || ' and upper(e.first_nme) like ''' || upper(:P300_FIRST_NAME) || '%''';
end if;
if :P300_EMPLOYEE_POSITION_CD is not NULL then
q := q || ' and e.employee_position_cd = :P300_EMPLOYEE_POSITION_CD';
end if;
if :P300_UNIT is not NULL then
q := q || ' and nvl(w.uod_cd, e.cpd_unit_assigned_no) = :P300_UNIT';
end if;
if :P300_WATCH_CD <> 'NULL' then
q := q || ' and w.watch_cd = :P300_WATCH_CD';
end if;
--htp.p('Limit Unit '||:P0_LIMIT_UNIT);
/* authorization of editing OWN, UNIT, or ALL recs */
if substr(:P0_PERMISSION, 1, 5) = 'QUERY' then
q := q || ' and e.user_id = v(''FLOW_USER'')';
elsif substr(:P0_PERMISSION, -4, 4) = 'UNIT' then
q := q || ' and coalesce(w.uod_cd, e.cpd_unit_assigned_no)= :P0_LIMIT_UNIT ';
end if;
htp.p('q: ' || q);
cursor q_c is q;
for c in ( q_c ) loop /* HOW CAN BE DYNAMIC ???? */
l_seq_id := htmldb_collection.add_member(
p_collection_name => 'OFFICER_ACTIVITY'
, p_c001 => c.user_id
, p_c002 => c.star_no
, p_c003 => c.last_name
, p_c004 => c.first_name
, p_c005 => c.middle_initial
, p_c006 => c.employee_no
, p_c007 => c.employee_position_cd
, p_c008 => c.unit
, p_c009 => c.watch_cd
, p_c050 => :P0_APP_USER
end loop;
end;Come back to solve my need. I get the working test process:
declare
type ty_cursor is ref cursor;
my_cursor ty_cursor;
my_rec emp%rowtype;
l_num number := 7900;
q varchar2(2000) ;
l_using varchar2(200) := null;
begin
:P8_TEST_CURSOR := '';
q := 'select * from emp';
if :P8_ENAME is not null then
q := q || ' where ename like :P8_ENAME';
l_using := ':P8_ENAME';
end if;
if l_using is not null then
open my_cursor for q using :P8_ENAME; --l_using;
else
open my_cursor for q;
end if;
loop
fetch my_cursor into my_rec;
exit when my_cursor%notfound;
:P8_TEST_CURSOR := :P8_TEST_CURSOR || ', ' || my_rec.empno;
end loop;
end;
But I need
open my_cursor for q using l_using;
to be working since my application has several searchable columns for users and I have to put users' input search into l_using. It does NOT work: q got 'select * from emp where ename like :P8_ENAME' and l_using got ':P8_ENAME' at "open ...." statement.
How can I get this cursor opened dynamically?
Thanks again!
DC -
Help! Inaccessible iterator when using dynamic query
Hi!
I have a problem retreiving results from a dynamic query into sqlj iterator.
I consulted the Oracle App Dev Guide and Oracle SQLJ Dev Guide and wrote the following code:
<PRE>
package pmServer;
#sql iterator LocIterator (int id, String name);
public class pmRISDImpl
public int GetLocations(...)
LocIterator locIt;
String q = "select ID, NAME from PMADM.LOCATIONS";
#sql
BEGIN
open :OUT locIt for :q;
END;
</PRE>
When I try to compile it using tools provided by JDeveloper ver 3.2.2.(Build 915) for JDK 1.2.2 I get error for #sql statement:
Inaccessible Java type for host item locIt (at position #1): pmServer.LocIterator
and warning:
Type pmServer.LocIterator of host item locIt (at position #1) is not permitted in JDBC. This will not be portable.
Althow the code is identcal to those demonstrated in Oracle document "Oracle8 i
SQLJ Developers Guide and Reference
Release 3 (8.1.7)
July 2000
Part No. A83723-01" pp 12-67 (PL/SQL in SQLJ for Dynamic SQLDynamicDemo.sqlj). There it looks like
<PRE>
private static void dynamicSelectMany(String what_cond)
throws SQLException {
System.out.println("dynamic multi-row query on table emp");
Employees empIter;
// table/column names cannot be bind args in dynamic PL/SQL, so
// build up query as Java string
String query = "select ename, sal from emp " +
(((what_cond == null) | | (what_cond.equals(""))) ? "" :
(" where " + what_cond)) +
"order by ename";
#sql {
begin
open :OUT empIter for -- opening ref cursor with dynamic query
:query;
-- can have USING clause here if needed
end;
while (empIter.next()) {
System.out.println("Employee " + empIter.ename() +
" has salary " + empIter.sal() );
empIter.close();
</PRE>
Please guide me what should I do to get it working.
nullIn the CAST statement the SQLJ runtime must be able to produce an instance of you SQLJ iterator using Java reflection.
This necessitates that the iterator class must be accessible by public.
You have two options:
(1) Declare the iterator public. This requires that you put it in its own file LocIterator.sqlj:
#sql public iterator LocIterator (int id, String name);
(2) Declare the iterator as an inner class. In this case you want to make it public static (that is it does not require an instance of the outer class in scope). You might write the following.
package pmServer;
public class pmRISDImpl
#sql public static iterator LocIterator (int id, String name);
(3) If you are using Oracle 9i you have another option. You can embed dynamic SQL fragments directly in your SQLJ code and do not need to use the CAST:
public int GetLocations(...)
LocIterator locIt;
String q = "PMADM.LOCATIONS";
#sql locIt = { select ID, NAME from :{q} }; // Note new syntax :{q} for embedding SQL source code
} -
Ref Cursor Using Dynamic Query
Hi,
I need to use the ref cursor to fetch result from dynamic query.
e.g.
Open ref_test_tbl for Select * from tbl1 where tbl1.field1= :1
and tbl1.field2 =:2 using i_v1,i_v2;
The thing is i_v1, i_v2 are dynamic.
i.e. using clause can include i_v3, i_v4 also.
How to include dynamic variables in the using clause.
thanks> How to include dynamic variables in the using clause.
Cannot using a ref cursor.. (and anyone that post code that writes dynamic PL/SQL in order to achieve this, I will call an idiot).
What you should be using in PL/SQL is a DBMS_SQL cursor. This allows you to create a fully dynamic SQL statement with bind variables. E.g.
select * from tbl1 where col1 = :1
select * from tbl1 where col2 = :1 order by 2
select * from tbl1 where col3 between :0 and :1
Using this dynamically created SQL statement, you can parse it using DBMS_SQL, determine the number of bind variables, and bind each of these dynamically.
You can then execute the SQL and again, dynamically, determine just what the projection of the cursor is. How many columns are returned, their names, data types, precision and so on.
This is what APEX (see http://apex.oracle.com) use extensively in order to run SQLs and render these as reports - all dynamically.
DBMS_SQL is detailed in the [url http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sql.htm#BABEDAHF]Oracle® Database PL/SQL Packages and Types Reference manual.
Maybe you are looking for
-
Hello I try to publish a Service over the Service Registry UI but this results in a com.sap.esi.uddi.sr.api.exceptions.SRExceptionerror code: null detail message: java.lang.NullPointerException->java.lang.NullPointerException Is the problem the sche
-
Page Title not displaying correctly in browser
This was working fine quite a while, but for some reason, now it just displays a lowercase version of the page name. The source code for the page does have the proper title, so it seems like Muse is exporting it correctly, but for some reason it does
-
Automated value generation for key field in db table
Hi All I have created a table in SE11 and i want to autogenerate a value for the keyfield when the user adds a new record to the table. the keyfield is of type numc. this field represents a document id hence i do not want the user to physically enter
-
3 company codes,8 Plants,50 Slocs,19 Sales depots.
Dear All, Please help us to design the orgn structure of our client. 1. Our client is having 3 company codes. One has 6 plants and the second one and third company code has one plant each. Total 8 Plants. Storage locations 50. 2. 19 Depots ca
-
Hi All, I have a requirement to display the number of pallets in the sales order output. Actually, the conversion rule is been maintained in the material master (in units of measurement). Below is the conversion rule: 1. 12 Bottles = 1 Case 2. 12 Cas