Collect stmt
hi
collect means it adds all the numeric numeric fields based on non-numeric fields but i wnat add the single numeric field how to solve this one plz help me
Hai Kiran
go through the following Documentation
COLLECT [wa INTO] itab.
Addition
... SORTED BY f
Effect
COLLECT is used to create unique or compressed datsets. The key fields are the default key fields of the internal table itab .
If you use only COLLECT to fill an internal table, COLLECT makes sure that the internal table does not contain two entries with the same default key fields.
If, besides its default key fields, the internal table contains number fields (see also ABAP/4 number types ), the contents of these number fields are added together if the internal table already contains an entry with the same key fields.
If the default key of an internal table processed with COLLECT is blank, all the values are added up in the first table line.
If you specify wa INTO , the entry to be processed is taken from the explicitly specified work area wa . If not, it comes from the header line of the internal table itab .
After COLLECT , the system field SY-TABIX contains the index of the - existing or new - table entry with default key fields which match those of the entry to be processed.
Notes
COLLECT can create unique or compressed datasets and should be used precisely for this purpose. If uniqueness or compression are unimportant, or two values with identical default key field values could not possibly occur in your particular task, you should use APPEND instead. However, for a unique or compressed dataset which is also efficient, COLLECT is the statement to use.
If you process a table with COLLECT , you should also use COLLECT to fill it. Only by doing this can you guarantee that
the internal table will actually be unique or compressed, as described above and
COLLECT will run very efficiently.
If you use COLLECT with an explicitly specified work area, it must be compatible with the line type of the internal table.
Example
Compressed sales figures for each company
DATA: BEGIN OF COMPANIES OCCURS 10,
NAME(20),
SALES TYPE I,
END OF COMPANIES.
COMPANIES-NAME = 'Duck'. COMPANIES-SALES = 10.
COLLECT COMPANIES.
COMPANIES-NAME = 'Tiger'. COMPANIES-SALES = 20.
COLLECT COMPANIES.
COMPANIES-NAME = 'Duck'. COMPANIES-SALES = 30.
COLLECT COMPANIES.
The table COMPANIES now has the following appearance:
NAME SALES
Duck 40
Tiger 20
Addition
... SORTED BY f
Effect
COLLECT ... SORTED BY f is obsolete and should no longer be used. Use APPEND ... SORTED BY f which has the same meaning.
Note
Performance
The cost of a COLLECT in terms of performance increases with the width of the default key needed in the search for table entries and the number of numeric fields with values which have to be added up, if an entry is found in the internal table to match the default key fields.
If no such entry is found, the cost is reduced to that required to append a new entry to the end of the table.
A COLLECT statement used on a table which is 100 bytes wide and has a key which is 60 bytes wide and seven numeric fields is about approx. 50 msn (standardized microseconds).
Note
Runtime errors
COLLECT_OVERFLOW : Overflow in integer field when calculating totals.
COLLECT_OVERFLOW_TYPE_P : Overflow in type P field when calculating totals.
Thanks & regards
Sreenivasulu P
Similar Messages
-
hi all,
I am doing report in which there is opening stock , closing stock and all movement wise stock.
i am able to do all this for one material but when i am try for more than one material then value of last material is overwrite on other material.
I m using collect stmt to do sum for all movement.
plz help me.hi all,
plz see my code look like this :
TABLES : MSEG , MKPF , MAKT , MBEW.
DATA : BEGIN OF ITAB OCCURS 0,
LBKUM LIKE MSEG-LBKUM,
LBKUM1 LIKE MSEG-LBKUM,
MAKTX LIKE MAKT-MAKTX,
LGORT LIKE MSEG-LGORT,
BWART LIKE MSEG-BWART,
ZEILE LIKE MSEG-ZEILE,
MENGE LIKE MSEG-MENGE,
MEINS LIKE MSEG-MEINS,
MATNR LIKE MSEG-MATNR,
WERKS LIKE MSEG-WERKS,
SHKZG LIKE MSEG-SHKZG,
MBLNR LIKE MKPF-MBLNR,
BUDAT LIKE MKPF-BUDAT,
SIGN(2),
101_102 LIKE MSEG-MENGE,
END OF ITAB.
DATA : BEGIN OF ITAB_TOT OCCURS 0,
MATNR LIKE MSEG-MATNR,
LBKUM1 LIKE MSEG-LBKUM,
TOTAL1 LIKE MSEG-MENGE,
TOTAL1 TYPE P DECIMALS 3,
CLO TYPE P DECIMALS 3,
101_102 LIKE MSEG-MENGE,
END OF ITAB_TOT.
PARAMETERS : WERKS LIKE MSEG-WERKS DEFAULT 'BRHP' OBLIGATORY.
SELECT-OPTIONS : MATNR FOR MSEG-MATNR OBLIGATORY.
SELECT-OPTIONS: DAT FOR MKPF-BUDAT.
SELECT-OPTIONS: LGORT FOR MSEG-LGORT.
START-OF-SELECTION.
SELECT DISTINCT MSEG~MATNR
MSEG~LGORT
MSEG~BWART
MSEG~ZEILE
MSEG~MENGE
MSEG~MEINS
MSEG~WERKS
MSEG~LBKUM
MSEG~SHKZG
MKPF~MBLNR
MKPF~BUDAT
INTO CORRESPONDING FIELDS OF TABLE ITAB
FROM MSEG
INNER JOIN MKPF ON MSEG~MBLNR = MKPF~MBLNR
WHERE MSEG~MATNR IN MATNR
AND MSEG~LGORT IN LGORT
AND MSEG~WERKS EQ WERKS
AND mKPF~BUDAT IN DAT
AND MSEG~ZEILE = 1
order by mkpf~MBLNR.
LOOP AT ITAB.
IF ITAB-SHKZG = 'S'.
ITAB-SIGN = '+'.
MODIFY ITAB.
ELSE.
ITAB-SIGN = '-'.
MODIFY ITAB.
ENDIF.
ENDLOOP.
SORT ITAB BY MATNR.
LOOP AT ITAB.
IF ITAB-BWART = '121' OR ITAB-BWART = '122' .
SELECT MENGE INTO (ITAB-121_122) FROM MSEG WHERE MATNR =
ITAB-MATNR
AND MBLNR = ITAB-MBLNR
AND LGORT = ITAB-LGORT
AND WERKS = ITAB-WERKS.
AND ZEILE = ITAB-ZEILE.
MODIFY ITAB.
ENDSELECT.
ENDIF.
LOOP AT ITAB.
IF ITAB-SHKZG = 'H'.
ITAB-121_122 = ITAB-121_122 * -1.
MODIFY ITAB.
ELSE.
ITAB-121_122 = ITAB-121_122.
MODIFY ITAB.
ENDIF.
ENDLOOP.
ENDLOOP.
LOOP AT ITAB.
SELECT LBKUM INTO (ITAB-LBKUM) FROM MSEG WHERE MATNR = ITAB-MATNR
and
MBLNR = ITAB-MBLNR AND WERKS = ITAB-WERKS AND ZEILE = 1.
MODIFY ITAB.
ENDSELECT.
ENDLOOP.
SORT ITAB BY matnr mblnr.
LOOP AT ITAB.
IF ITAB[] IS NOT INITIAL.
DELETE ADJACENT DUPLICATES FROM ITAB COMPARING MATNR .
MOVE ITAB-lBKUM TO ITAB-LBKUM1.
MODIFY ITAB.
*APPEND ITAB_TOT1.
ENDIF.
ENDLOOP.
LOOP AT ITAB .
MOVE-CORRESPONDING ITAB TO ITAB_TOT.
COLLECT ITAB_TOT.
ENDLOOP.
loop at itab_tot.
write : / itab_tot-matnr , itab_tot-121_122 , itab-lbkum.
endloop.
i am not getting correct value of 121_122.
what should i do? -
COLLECT stmt - counter.
Experts,
Basically
DATA : Count TYPE i.
will work with COLLECT stmt as a counter.
I have DB structure having filed as RKE2_VVQ09 (QUAN type) in 4.6 C which was used as a counter filed in COLLECT stmt.
However in ECC 6.0, looks like is not working in COLLECT stmt as a counter.
So DDIC team have changed it in the DB structure from RKE2_VVQ09 (QUAN type) to char20, however it is not either working as a counter when we use COLLECT stmt (i did not test ).
So could you please let me know Whether RKE2_VVQ09 (QUAN type) will work with COLLECT stmt in ECC ?
or do I need to change this to INT4 ?
I Could not change in DB structure and test it ...that why I am asking for your help.
YOUR HELP WILL BE APPRECIATED.
Thanks in advance.>
sam kumar wrote:
> I Could not change in DB structure and test it ...that why I am asking for your help.
You don't have to change the DB structure. You could simply create an internal table that has fields of both types and see if either works.
Rob -
Regarding COLLECT stmt usage in an ABAP Program.
Hi All,
Could anyone please explain if the COLLECT statement really hampers the performance of the program, to a large extent.
If it is so, please explain how the performance can be improved with out using the same.
Thanks & Regards,
Goutham.COLLECT allows you to create unique or summarized datasets. The system first tries to find a table entry corresponding to the table key. (See also Defining Keys for Internal Tables). The key values are taken either from the header line of the internal table itab, or from the explicitly-specified work area wa. The line type of itab must be flat - that is, it cannot itself contain any internal tables. All the components that do not belong to the key must be numeric types ( ABAP Numeric Types).
Notes
COLLECT allows you to create a unique or summarized dataset, and you should only use it when this is necessary. If neither of these characteristics are required, or where the nature of the table in the application means that it is impossible for duplicate entries to occur, you should use INSERT [wa INTO] TABLE itab instead of COLLECT. If you do need the table to be unique or summarized, COLLECT is the most efficient way to achieve it.
If you use COLLECT with a work area, the work area must be compatible with the line type of the internal table.
If you edit a standard table using COLLECT, you should only use the COLLECT or MODIFY ... TRANSPORTING f1 f2 ... statements (where none of f1, f2, ... may be in the key). Only then can you be sure that:
-The internal table actually is unique or summarized
-COLLECT runs efficiently. The check whether the dataset
already contains an entry with the same key has a constant
search time (hash procedure).
If you use any other table modification statements, the check for entries in the dataset with the same key can only run using a linear search (and will accordingly take longer). You can use the function module ABL_TABLE_HASH_STATE to test whether the COLLECT has a constant or linear search time for a given standard table.
Example
Summarized sales figures by company:
TYPES: BEGIN OF COMPANY,
NAME(20) TYPE C,
SALES TYPE I,
END OF COMPANY.
DATA: COMP TYPE COMPANY,
COMPTAB TYPE HASHED TABLE OF COMPANY
WITH UNIQUE KEY NAME.
COMP-NAME = 'Duck'. COMP-SALES = 10. COLLECT COMP INTO COMPTAB.
COMP-NAME = 'Tiger'. COMP-SALES = 20. COLLECT COMP INTO COMPTAB.
COMP-NAME = 'Duck'. COMP-SALES = 30. COLLECT COMP INTO COMPTAB.
Table COMPTAB now has the following contents:
NAME | SALES
Duck | 40
Tiger | 20 -
Doubts in internal table logic
Hi All,
I have two internal table, according to the posnr value i need to add the kbetr value from the 2nd internal table and update the value in the 1st line internal table. below the example of my internal table. Here for the line item 0010 i need to calculate 10.0030.1011.00 and i need to add the value inthe 1st internal table kbeter_value. can anyone help this?
POSNR MATNR kbetr_value
0010 abc
0020 xyz
0030 123
POSNR KBETR
0010 10.00
0010 30.10
0010 11.00
0010 60.30
0020 12.64
0020 11.32
0030 79.46
0030 00.00
0030 45.3
by
MohanaHi Mohana,
Its very simple ..you can do it in many ways....
first one is in the second internal table use collect ....
for example : 1st internal table is itab and the second is jtab .
1. In jtab u use collect stmt to calculate the posnr values .
loop at jtab.
collect jtab . " by using this u will have 0010 111.40 in jtab
endloop.
structure of jtab will be :
0010 111.40
0020 .........
0030 ..........
2. afterwards while printing you can use read to get those :
loop at itab.
read table jtab with key posnr = itab-posnr.
if sy-subrc = 0.
itab-ksbtr-value = itab-value .
modify itab .
endif.
endloop.
Hope you got it by now...if you any problem do reply back ....
cheers,
Vishnu . -
Hi Experts,
I have an internal table with the following fields.
rollno(10) type c,
name(20) type c,
subject(10) type c,
mark(3) type c.
the values stored in the above IT will be something like:
rollno name subject mark
100 Sam Maths 80
100 Sam Science 90
100 Sam Social 100
200 Wam Maths 90
200 Wam Science 90
200 Wam Social 80
I want the o/p in an internal table like this:
rollno name Tot-mark
100 Sam 270
200 Wam 260
Please advice as to how i can acheive this
Thanks,
ManjuHi,
for the summing of marks you can use COLLECT stmt. But the field you want to add up need not be in char or string. e.g: MARKS type INT. As others are CHAR so they will act like Key for the MARKS field. take ROLLNO or NAME as key.
after addition MOVE source table to Target table(another internal table) for display.
or follow dis below mentioned code
data: begin of itab occurs 10,
roll(10),
name(5),
sub(10),
mark type i,
end of itab.
itab-roll = '100'.
itab-name = 'sam'.
itab-sub = 'math'.
itab-mark = 40.
append itab.
itab-roll = '100'.
itab-name = 'sam'.
itab-sub = 'math1'.
itab-mark = 10.
append itab.
itab-roll = '100'.
itab-name = 'sam'.
itab-sub = 'math2'.
itab-mark = 30.
append itab.
itab-roll = '200'.
itab-name = 'sam1'.
itab-sub = 'math'.
itab-mark = 50.
append itab.
itab-roll = '200'.
itab-name = 'sam1'.
itab-sub = 'math1'.
itab-mark = 20.
append itab.
itab-roll = '200'.
itab-name = 'sam1'.
itab-sub = 'math2'.
itab-mark = 60.
append itab.
itab-roll = '300'.
itab-name = 'sam2'.
itab-sub = 'math'.
itab-mark = 80.
append itab.
itab-roll = '300'.
itab-name = 'sam2'.
itab-sub = 'math1'.
itab-mark = 70.
append itab.
sort itab by roll.
loop at itab.
at new name.
sum.
Write: / itab-roll, itab-name, itab-mark.
endat.
endloop.
Reward if helpful.
Thanks.
Edited by: Sagar@MM on May 22, 2008 10:00 AM
Edited by: Sagar@MM on May 22, 2008 11:33 AM
Edited by: Sagar@MM on May 22, 2008 11:34 AM -
hi experts
I have a internal table inwhich i have many values for example
kdauf kdpos erfmg bwart
1 10 10000 601
1 10 5000 601
2 10 600 602
2 10 500 601
now i want to add erfmg values when kdauf ,kdpos and bwart are same, without using collect stmt.
i dont know how to add those values, similarly i want to subtract 601 total erfmg value from 602 total erfmg value.
Please advise me on the same.
Thanks in advance.
Regards
RajaramHi Rajaram..
This is the code without using COLLECT..
DATA : BEGIN OF ITAB2 OCCURS 0,
kdauf
kdpos
erfmg
v1
v2
end of itab2.
Hi Rajaram..
This is the code without using COLLECT..
DATA : BEGIN OF ITAB2 OCCURS 0,
kdauf
kdpos
erfmg
v1
v2
end of itab2.
Hi Rajaram..
This is the code without using COLLECT..
DATA : BEGIN OF ITAB3 OCCURS 0,
BWART
v1
v2
end of itab2.
SORT ITAB BY kdauf kdpos erfmg.
LOOP AT ITAB.
AT END OF erfmg.
SUM.
MOVE-CORRESPONDING ITAB TO ITAB2.
APPEND ITAB2.
ENDAT.
ENDLOOP.
<b>REWARD IF HELPFUL</b> -
Difference between collect and move stmts
hi
anyone plz explain...
1. Difference between collect and move stmts
2. Badi and user exit.
gowriHi,
1.COLLECT:COLLECT is used to create unique or compressed datsets. The key fields are the default key fields of the internal table itab .
If you use only COLLECT to fill an internal table, COLLECT makes sure that the internal table does not contain two entries with the same default key fields.
If, besides its default key fields, the internal table contains number fields,the contents of these number fields are added together if the internal table already contains an entry with the same key fields.
If the default key of an internal table processed with COLLECT is blank, all the values are added up in the first table line.
If you specify wa INTO , the entry to be processed is taken from the explicitly specified work area wa . If not, it comes from the header line of the internal table itab .
After COLLECT , the system field SY-TABIX contains the index of the - existing or new - table entry with default key fields which match those of the entry to be processed.
COLLECT can create unique or compressed datasets and should be used precisely for this purpose. If uniqueness or compression are unimportant, or two values with identical default key field values could not possibly occur in your particular task, you should use APPEND instead. However, for a unique or compressed dataset which is also efficient, COLLECT is the statement to use.
If you process a table with COLLECT , you should also use COLLECT to fill it. Only by doing this can you guarantee that the internal table will actually be unique or compressed, as described above and COLLECT will run very efficiently.
If you use COLLECT with an explicitly specified work area, it must be compatible with the line type of the internal table.
In 'move' the actually data copies into another data field
2.
Difference between BADI and USER-EXIT.
i) BADI's can be used any number of times, where as USER-EXITS can be used only one time.
Ex:- if your assigning a USER-EXIT to a project in (CMOD), then you can not assign the same to other project.
ii) BADI's are oops based.
A. BAdI Definition
1. SE18
2. Enter the name for the BAdI to be created in customer namespace and press "Create".
3. Enter a definition for your BAdI and on the interface tab enter a name for the BAdI interface. SAP proposes a name and it is pretty good. Meanwhile a BAdI class is also created which is not in our concern.
e.g for "ZTEST", SAP proposes "ZIF_EX_TEST" for the interface and "ZCL_EX_TEST" for the class.
4. Save your BAdI.
5. Double-click on the interface name. It will pass to a Class Builder session to make you implement your interface. If you are not familiar to the Class Builder; it's a bit like Function Builder and it will be easy to discover its procedure.
6. Save and activate your interface.
B. Calling your BAdI from an application program
1. Declare a reference variable with reference to the Business Add-In interface.
e.g. DATA exit_ref TYPE REF TO zif_ex_test.
2. Call the static method GET_INSTANCE of the service class CL_EXITHANDLER. This returns an instance of the required object.
e.g.
CALL METHOD CL_EXITHANDLER=>GET_INSTANCE
CHANGING instance = exit_ref .
3. After those two steps, you can now call all of the methods of the BAdI where it is required in your program. Make sure you specify the method interfaces correctly.
C. BAdI Implementations
1. SE19
2. Enter the name for the BAdI implementation to be created in customer namespace and press "Create".
3. It will request the BAdI definition name to which this implementation will be tied.
4. Enter a definition for your implementation and on the interface tab enter a name for the implementing class. Again SAP proposes a name and it is pretty good.
e.g for "ZIMPTEST", SAP proposes "ZCL_IM_IMPTEST".
5. Save your implementation.
6. To implement a method, just double-click on the method name and you will be taken to the Class Builder to write the code for it. Here you redefine the BAdI interface methods.
7. You must activate your implementation to make it executable. You can only activate or deactivate an implementation in its original system without modification. The activation or deactivation must be transported into subsequent systems
Regards -
declare
cursor c1 as select clb from clob_table;
type t1_t is table of clob index by binary integer;
t1 t1_t;
begin
open c1;
fetch bulk collect into t1;
close c1;
insert into some_table
(id,
clob_field)
with
x (select rownum x, trunc(dbms_random.value(1,30)) rnd from all_objects where rownum < 11);
select
x, --id
t1(rnd)
from x;
it gives error identifier 'RND' must be declared.
Any suggessions ???
Thanks for your time..I think this is enough code to generate error.
error is comming because i am going to use rnd as index of collection t1. -
Using a Collection of beans to store a result set help.
Does anyone have any sample code on the subject? This is something I wrote up, but I wanted feedback, and also an example of how to retreive data out of the array of beans in jsp
package beanpersonal;
import beandatabase.DBConnection;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.util.Collection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class PersonNew {
public PersonNew() { }
public Collection getPersondata( String alias, String password ) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Collection retValue = new ArrayList();
String query = "SELECT * FROM person WHERE (alias = ?, password = ?)";
try {
conn = DBConnection.getDBConnection();
stmt = conn.prepareStatement( query );
stmt.setString( 1, alias );
stmt.setString( 2, password );
rs = stmt.executeQuery();
while (rs.next()) {
PersonalInfo beanrow = new PersonalInfo();
beanrow.setAlias(rs.getString("alias"));
beanrow.setPassword(rs.getString("password"));
retValue.add(beanrow);
return retValue;
catch( SQLException sqle ) {
//sqle.printStackTrace();
//throw new ApplicationSpecficException("Cannot query db", sqle);
throw new RuntimeException(sqle);
finally {
try {if (rs != null) rs.close();} catch (SQLException e) {}
try {if (stmt != null) stmt.close();} catch (SQLException e) {}
try {if (conn != null) conn.close();} catch (SQLException e) {}
}sorry i only view the codes, but don't read it as a whole maybe this codes can help you..
jsp:
<%@ page contentType="text/html;charset=windows-1252"%>
<%@page import="java.util.*,mypackage.TestBean"%>
<%
String name = request.getParameter("name")!=null?request.getParameter("name"):"";
String age = request.getParameter("age")!=null?request.getParameter("age"):"";
System.out.println(name);
System.out.println(age);
Collection col = new ArrayList();
col = (Collection)session.getAttribute("col")!=null?(Collection)session.getAttribute("col"):new ArrayList();
TestBean tBean = new TestBean();
if(!name.equals(""))
tBean.setName(name);
if(!age.equals(""))
tBean.setAge(age);
if(!age.equals("") || !name.equals(""))
col.add(tBean);
session.setAttribute("col",col);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<title>untitled</title>
</head>
<body>
<form>
<table cellspacing="0" cellpadding="0" border="1" width="200">
<tr>
<td>Name</td>
<td>
<input type="text" name="name"/>
</td>
</tr>
<tr>
<td>Age</td>
<td>
<input type="text" name="age"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
<%
if(col.size()>0){
Iterator iter = col.iterator();
%>
<table cellspacing="0" cellpadding="0" border="1" width="200">
<tr>
<td>
NAME
</td>
<td>
AGE
</td>
</tr>
<%while(iter.hasNext()){
tBean = (TestBean)iter.next();
%>
<tr>
<td>
<%=tBean.getName()%>
</td>
<td>
<%=tBean.getAge()%>
</td>
</tr>
<%}%>
</table>
<%}%>
</form>
</body>
</html>TestBean.java
package mypackage;
public class TestBean
private String name;
private String age;
public TestBean()
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getAge()
return age;
public void setAge(String age)
this.age = age;
} -
Obtaining a collection as a return from an execute immediate pl/sql block
version 10.2
I need to obtain the collection back from the execute immediate of a pl/sql block:
procedure block(owner varchar2) is
stmt long;
objecttab_coll dbms_stats.objecttab;
begin
stmt := '
begin
dbms_stats.gather_schema_stats(''' || owner || '''
,options => ''LIST AUTO''
,objlist => :objecttab_coll
end;';
execute immediate stmt returning into objecttab_coll;
-- do more stuff here
end block;I have tried this + a few variations but with no luck. In looking through the docs I do not see an example. can this be done?
Thanks
OxI dont find any need for an execute immediate here. This must be just enough.
procedure block(owner varchar2)
is
objecttab_coll dbms_stats.objecttab;
begin
dbms_stats.gather_schema_stats(ownname => owner, options => 'LIST AUTO', objlist => objecttab_coll);
-- do more stuff here
end block;Thanks,
Karthick. -
How do I create a Dynamic java.sql.Date ArrayList or Collection?
I Have a MySQL table with a Datetime field with many values inserted.
I want to know which is the Best way to capture all the Inserted DB values inside a Dynamic Array.
I get errors that state that I should use Matching data-types, and plus I don't know how to create or fill a Dynamic Date ArrayList/Collection.
Please Help, I need this urgently...package pruebadedates;
import java.sql.*;
* @author J?s?
public class ClaseDeDates {
/** Creates a new instance of ClaseDeDates */
* @param args the command line arguments
public static void main(String[] args) {
java.sql.Date aDate[] = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/pruebafechas", "root", "picardias");
if(!con.isClosed()){
stmt = con.createStatement();
stmt.executeQuery ("SELECT dates FROM datestable");
rs = stmt.getResultSet();
while (rs.next())
aDate[] = rs.getDate("dates");
catch(Exception e)
System.out.println(e);
//System.out.println(aDate);
}Hi, There is my code and the errors that I get are:
found : java.sql.Date
required: java.sql.Date[]
aDate = rs.getDate("dates");
Actually I have No idea as How to get a Result set into an ArrayList or Collection. Please tell me how to do this Dynamically. I have like 25 records in that Database table, but they will grow, so I would really appreciate to know the code to do this. I suspect my problem is in the bolded part of my code.
Thank you very much Sir. -
Problem with SQL connection and a Collection
hi all,
I have two problems with sql...
1. how can I assign the values of a resultset to a collection?
2. how can I close the sql connection, because when I close the statement and connection error shows me in the resultset
thanks!Hello Pablo,
RetrivingResults In Collection:
1) use getObject method, and assign it to collection.
Collection c_obj=new ArrayList();
while(rs.next())
c_obj.add(rs.getInt(Project_ID), rs.getString(Project_Name));
Closing ResultSet
2) The close() methos of ResultSet closes the ResultSet object, like bellow
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
rs.close(); //Closes the result set -
Binds collections and forall statement
version 9.2.0.6
I would like to make this more dynamic in that the collection cList can be used only once and be used by all bind variables. The variable stmt would be dynamically generated in that case it would insert into any number of tables.
Can this be done?
Is this feature available in a newer version of Oracle?
create table d2 nologging as
select
rownum rn
,substr(dbms_random.string('x',5),1,10) v1
,sysdate d1
,round(dbms_random.value(1,10)) n1
,substr(dbms_random.string('x',5),1,10) v2
,rpad(' ',4000,' ') as concat
from dual connect by level <= 100;
-- no rows for our test
create table d3 nologging as
select
from d2 where 1 = 2;
-- setup for our test
update d2
set image = rpad(nvl(to_char(rn),' '),10,' ')
|| rpad(nvl(v1,' '),20,' ')
|| rpad(nvl(to_char(d1,'DD-MON-YYYY HH24:MI:SS'),' '),34,' ')
|| rpad(nvl(to_char(n1),' '),10,' ')
|| rpad(nvl(v2,' '),10,' ')
-- test got all locations right
select
to_number(rtrim(substr(image,1,10)))
,rtrim(substr(image,11,20))
,to_date(rtrim(substr(image,30,34)),'DD-MON-YYYY HH24:MI:SS')
,to_number(rtrim(substr(image,65,10))) AS n1
,rtrim(substr(image,75,10))
from d2;
-- here is where we do the work
declare
type charList is table of varchar2(4000);
cList charList;
d2l d2_list;
errors NUMBER;
dml_errors EXCEPTION;
PRAGMA exception_init(dml_errors, -24381);
sqlStmt varchar2(32000);
cursor cur is select image from d2;
bcLimit number := 23;
begin
sqlStmt := 'insert into d3 (rn,v1,d1,n1,v2)'
|| 'values (to_number(rtrim(substr(:a,1,10)))
,rtrim(substr(:a,11,20))
,to_date(rtrim(substr(:a,30,34)),''DD-MON-YYYY HH24:MI:SS'')
,to_number(rtrim(substr(:a,65,10)))
,rtrim(substr(:a,75,10)))';
open cur;
loop
fetch cur bulk collect into cList limit bcLimit;
exit when cList.count = 0;
begin
-- very very unfortunately the code is unable to have one using clause variable be applied to all bind variables
-- note the number of cList uses having the bind variables all name the same does not help
-- using only one gets a ORA-1008 error :(
FORALL i IN cList.FIRST..cList.LAST SAVE EXCEPTIONS execute immediate sqlstmt using cList(i),cList(i),cList(i),cList(i),cList(i);
-- FORALL i IN cList.FIRST..cList.LAST SAVE EXCEPTIONS execute immediate sqlstmt using cList(i); --< DOES NOT WORK :( I WISH IT WOULD!
EXCEPTION
WHEN dml_errors THEN
errors := SQL%BULK_EXCEPTIONS.COUNT;
dbms_output.put_line('number of errors is ' || errors);
FOR i IN 1..errors LOOP
dbms_output.put_line('Error ' || i || ' occurred during iteration ' || SQL%BULK_EXCEPTIONS(i).ERROR_INDEX);
dbms_output.put_line('Could not insert ' || cList(SQL%BULK_EXCEPTIONS(i).ERROR_INDEX));
dbms_output.put_line(SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
END LOOP;
end;
end loop;
close cur;
dbms_output.put_line('h2');
end;
/The CREATE TABLE you post for table D2 has no column called 'image'. It would help somewhat if you posted a working example.
Also I am not clear why the INSERT INTO D3 statement in the anonymous block needs to be dynamic. -
Passing values to collection.
Hi,
I am passing the values to collection through hidden fields.
Only one value is added into the collection. I am not able get the remaining field values.
I am using the application level process to add the values in collection.
any solution for this?Basically, i have a method that will return a Collection of Bean.
public Collection<PersonBean> getResults(String query) ,
in which query contains my sql select statement.
then i issued this following commands inside this method,
Statement stmt = cn,createStatement();
Resultset rs = stmt.executeQuery(query);
Then, i put the fetched records in a bean
while (rs.next()) {
personbean.setName(rs.getString("name"));
personbean.setAddress(rs.getString("address"));
Assuming i have a personBean and a DBConnection already established.
My question is how can i add each record to a collection, everytime rs.next loops, because the method will return a collection of bean.
Thank you very much. Any reply would much be appreciated
Maybe you are looking for
-
JDBC version used with JDeveloper
Hi, I am trying to connect JDeveloper with SQLite database using Generic JDBC driver. The driver I could find is JDBC 3.0 compatible. I am able to make a connection in the database navigator and browse through the database object. I am also able to c
-
Hi, I have sql query which gives output of accounts and balance. I have designed report to show chart of accounts and their balances. How can I take group total fields to show sum of each level of accounts. Level Account Header 3 Header 4 Header 5 He
-
Hi Experts, I am learning GP(Guided processor)according the document http://help.sap.com/saphelp_nw70/helpdata/en/44/0d5b8f250d5cfae10000000a155369/frameset.htmneed. I meet two question when I learn the GP. The first: This document don't tell me how
-
RWBLD60.EXE - Ordinal Not Found
"The ordinal 11100 could not be located in the dynamic link library UIW60.DLL" Report Builder won't open, when trying to open the above message is displayed and you can click OK and thats it. Help Please..
-
I have experienced error "Fatal Internal error: "oleautomgr.cpp", line 2832" during sending data to CAN card IXXAT iPCI-I XC16/PCI. LabVIEW communicates with that card by means of ActiveX methodes via "VCI Wrapper" which is COM object interface. Mas