Aggregate function in for loop insert
Hi Everyone,
Please see the below code and help me insert these string values. How can I trap that string value and insert it?
DECLARE
BEGIN
for i in (SELECT STRAGG(Q.QUESTION_CODE)
FROM QUESTION Q , TEST_CODE_CONVERSION TC
WHERE Q.ACTIVE_YN = 'Y'
AND Q.TEST_ID = TC.EAST_TEST_ID
GROUP BY Q.TEST_ID)
LOOP
INSERT INTO TEST_CODE_CONVERSION (QCODE_FOR_WEST_TEST_ID)
VALUES (___________) ;
dbms_output.put_line('1 row inserted');
END LOOP;
End;Regards,
BS2012.
Add column alias
BS2012 wrote:
Hi Everyone,
Please see the below code and help me insert these string values. How can I trap that string value and insert it?
DECLARE
BEGIN
for i in (SELECT STRAGG(Q.QUESTION_CODE) as q_code --"Alias added"
FROM QUESTION Q , TEST_CODE_CONVERSION TC
WHERE Q.ACTIVE_YN = 'Y'
AND Q.TEST_ID = TC.EAST_TEST_ID
GROUP BY Q.TEST_ID)
LOOP
INSERT INTO TEST_CODE_CONVERSION (QCODE_FOR_WEST_TEST_ID)
VALUES (___________) ;
dbms_output.put_line('1 row inserted');
END LOOP;
End;Regards,
BS2012.Actually you dont need PL/SQL for this, just a Single SQL
INSERT INTO TEST_CODE_CONVERSION (QCODE_FOR_WEST_TEST_ID)
select STRAGG(Q.QUESTION_CODE)
FROM QUESTION Q , TEST_CODE_CONVERSION TC
WHERE Q.ACTIVE_YN = 'Y'
AND Q.TEST_ID = TC.EAST_TEST_ID
-- GROUP BY Q.TEST_ID--"GROUP BY is not required, right?
{code}
Edited by: jeneesh on May 15, 2013 4:05 PM
Similar Messages
-
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> -
How to define function within for loop pls help?????
Hi this is the problem i have a class, and within that class there is an actionPerformed function, in this class i also create an instance of another class, this other class also contains an actionPerformed function, which wis executed if a jButton has been pressed, when I try to place this actionPerfromed function within a for loop of a function i get an error saying illegal start of experssion, and that the class should be defined abstract as it does not define actionPerformed, when i take it out of the for loop it compliles fine, i need the function to be placed within the for loop because it needs to know the variable of the for loop, is there anyway around this? Thanks, below is the code:
public class DisplayTransitions extends JFrame implements ActionListener
public void add()
for(int i = 0; i < char2.size(); i ++)
mPanel.add(tim[i] = new JButton("Time"));
tim.addActionListener(this);
public void actionPerformed(ActionEvent ae)
if (ae.getSource() == tim[i])
timeIncr();This is your for loop using an anonymous inner class for the listener:
for (int i = 0; i < char2.size(); i++) {
mPanel.add(tim[i] = new JButton("Time"));
tim.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == tim[i]) {
timeIncr();
Learn more about anonymous inner classes from a good Java book or the Java tutorial (try http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/nested-answers.html). -
Hi all,
I have a performance issue in the below code,where i am trying to insert the data from table_stg into target_tab and in parent_tab tables and then to child tables via cursor with bulk collect .the target_tab and parent_tab are huge tables and have a row wise trigger enabled on it .the trigger is mandatory . This timetaken for this block to execute is 5000 seconds.Now my requirement is to reduce it to 5 to 10 mins.
can someone please guide me here.Its bit urgent .Awaiting for your response.
declare
vmax_Value NUMBER(5);
vcnt number(10);
id_val number(20);
pc_id number(15);
vtable_nm VARCHAR2(100);
vstep_no VARCHAR2(10);
vsql_code VARCHAR2(10);
vsql_errm varchar2(200);
vtarget_starttime timestamp;
limit_in number :=10000;
idx number(10);
cursor stg_cursor is
select
DESCRIPTION,
SORT_CODE,
ACCOUNT_NUMBER,
to_number(to_char(CORRESPONDENCE_DATE,'DD')) crr_day,
to_char(CORRESPONDENCE_DATE,'MONTH') crr_month,
to_number(substr(to_char(CORRESPONDENCE_DATE,'DD-MON-YYYY'),8,4)) crr_year,
PARTY_ID,
GUID,
PAPERLESS_REF_IND,
PRODUCT_TYPE,
PRODUCT_BRAND,
PRODUCT_HELD_ID,
NOTIFICATION_PREF,
UNREAD_CORRES_PERIOD,
EMAIL_ID,
MOBILE_NUMBER,
TITLE,
SURNAME,
POSTCODE,
EVENT_TYPE,
PRIORITY_IND,
SUBJECT,
EXT_PRD_ID_TX,
EXT_PRD_HLD_ID_TX,
EXT_SYS_ID,
EXT_PTY_ID_TX,
ACCOUNT_TYPE_CD,
COM_PFR_TYP_TX,
COM_PFR_OPT_TX,
COM_PFR_RSN_CD
from table_stg;
type rec_type is table of stg_rec_type index by pls_integer;
v_rt_all_cols rec_type;
BEGIN
vstep_no := '0';
vmax_value := 0;
vtarget_starttime := systimestamp;
id_val := 0;
pc_id := 0;
success_flag := 0;
vstep_no := '1';
vtable_nm := 'before cursor';
OPEN stg_cursor;
vstep_no := '2';
vtable_nm := 'After cursor';
LOOP
vstep_no := '3';
vtable_nm := 'before fetch';
--loop
FETCH stg_cursor BULK COLLECT INTO v_rt_all_cols LIMIT limit_in;
vstep_no := '4';
vtable_nm := 'after fetch';
--EXIT WHEN v_rt_all_cols.COUNT = 0;
EXIT WHEN stg_cursor%NOTFOUND;
FOR i IN 1 .. v_rt_all_cols.COUNT
LOOP
dbms_output.put_line(upper(v_rt_all_cols(i).event_type));
if (upper(v_rt_all_cols(i).event_type) = upper('System_enforced')) then
vstep_no := '4.1';
vtable_nm := 'before seq sel';
select PC_SEQ.nextval into pc_id from dual;
vstep_no := '4.2';
vtable_nm := 'before insert corres';
INSERT INTO target1_tab
(ID,
PARTY_ID,
PRODUCT_BRAND,
SORT_CODE,
ACCOUNT_NUMBER,
EXT_PRD_ID_TX,
EXT_PRD_HLD_ID_TX,
EXT_SYS_ID,
EXT_PTY_ID_TX,
ACCOUNT_TYPE_CD,
COM_PFR_TYP_TX,
COM_PFR_OPT_TX,
COM_PFR_RSN_CD,
status)
VALUES
(pc_id,
v_rt_all_cols(i).party_id,
decode(v_rt_all_cols(i).product_brand,'LTB',2,'HLX',1,'HAL',1,'BOS',3,'VER',4,0),
v_rt_all_cols(i).sort_code,
'XXXX'||substr(trim(v_rt_all_cols(i).ACCOUNT_NUMBER),length(trim(v_rt_all_cols(i).ACCOUNT_NUMBER))-3,4),
v_rt_all_cols(i).EXT_PRD_ID_TX,
v_rt_all_cols(i).EXT_PRD_HLD_ID_TX,
v_rt_all_cols(i).EXT_SYS_ID,
v_rt_all_cols(i).EXT_PTY_ID_TX,
v_rt_all_cols(i).ACCOUNT_TYPE_CD,
v_rt_all_cols(i).COM_PFR_TYP_TX,
v_rt_all_cols(i).COM_PFR_OPT_TX,
v_rt_all_cols(i).COM_PFR_RSN_CD,
NULL);
vstep_no := '4.3';
vtable_nm := 'after insert corres';
else
select COM_SEQ.nextval into id_val from dual;
vstep_no := '6';
vtable_nm := 'before insertcomm';
if (upper(v_rt_all_cols(i).event_type) = upper('REMINDER')) then
vstep_no := '6.01';
vtable_nm := 'after if insertcomm';
insert into parent_tab
(ID ,
CTEM_CODE,
CHA_CODE,
CT_CODE,
CONTACT_POINT_ID,
SOURCE,
RECEIVED_DATE,
SEND_DATE,
RETRY_COUNT)
values
(id_val,
lower(v_rt_all_cols(i).event_type),
decode(v_rt_all_cols(i).product_brand,'LTB',2,'HLX',1,'HAL',1,'BOS',3,'VER',4,0),
'Email',
v_rt_all_cols(i).email_id,
'IADAREMINDER',
systimestamp,
systimestamp,
0);
else
vstep_no := '6.02';
vtable_nm := 'after else insertcomm';
insert into parent_tab
(ID ,
CTEM_CODE,
CHA_CODE,
CT_CODE,
CONTACT_POINT_ID,
SOURCE,
RECEIVED_DATE,
SEND_DATE,
RETRY_COUNT)
values
(id_val,
lower(v_rt_all_cols(i).event_type),
decode(v_rt_all_cols(i).product_brand,'LTB',2,'HLX',1,'HAL',1,'BOS',3,'VER',4,0),
'Email',
v_rt_all_cols(i).email_id,
'CORRESPONDENCE',
systimestamp,
systimestamp,
0);
END if;
vstep_no := '6.11';
vtable_nm := 'before chop';
if (v_rt_all_cols(i).ACCOUNT_NUMBER is not null) then
v_rt_all_cols(i).ACCOUNT_NUMBER := 'XXXX'||substr(trim(v_rt_all_cols(i).ACCOUNT_NUMBER),length(trim(v_rt_all_cols(i).ACCOUNT_NUMBER))-3,4);
insert into child_tab
(COM_ID,
KEY,
VALUE)
values
(id_val,
'IB.Correspondence.AccountNumberMasked',
v_rt_all_cols(i).ACCOUNT_NUMBER);
end if;
vstep_no := '6.1';
vtable_nm := 'before stateday';
if (v_rt_all_cols(i).crr_day is not null) then
insert into child_tab
(COM_ID,
KEY,
VALUE)
values
(id_val,
--'IB.Correspondence.Date.Day',
'IB.Crsp.Date.Day',
v_rt_all_cols(i).crr_day);
end if;
vstep_no := '6.2';
vtable_nm := 'before statemth';
if (v_rt_all_cols(i).crr_month is not null) then
insert into child_tab
(COM_ID,
KEY,
VALUE)
values
(id_val,
--'IB.Correspondence.Date.Month',
'IB.Crsp.Date.Month',
v_rt_all_cols(i).crr_month);
end if;
vstep_no := '6.3';
vtable_nm := 'before stateyear';
if (v_rt_all_cols(i).crr_year is not null) then
insert into child_tab
(COM_ID,
KEY,
VALUE)
values
(id_val,
--'IB.Correspondence.Date.Year',
'IB.Crsp.Date.Year',
v_rt_all_cols(i).crr_year);
end if;
vstep_no := '7';
vtable_nm := 'before type';
if (v_rt_all_cols(i).product_type is not null) then
insert into child_tab
(COM_ID,
KEY,
VALUE)
values
(id_val,
'IB.Product.ProductName',
v_rt_all_cols(i).product_type);
end if;
vstep_no := '9';
vtable_nm := 'before title';
if (trim(v_rt_all_cols(i).title) is not null) then
insert into child_tab
(COM_ID,
KEY,
VALUE )
values
(id_val,
'IB.Customer.Title',
trim(v_rt_all_cols(i).title));
end if;
vstep_no := '10';
vtable_nm := 'before surname';
if (v_rt_all_cols(i).surname is not null) then
insert into child_tab
(COM_ID,
KEY,
VALUE)
values
(id_val,
'IB.Customer.LastName',
v_rt_all_cols(i).surname);
end if;
vstep_no := '12';
vtable_nm := 'before postcd';
if (trim(v_rt_all_cols(i).POSTCODE) is not null) then
insert into child_tab
(COM_ID,
KEY,
VALUE)
values
(id_val,
'IB.Customer.Addr.PostCodeMasked',
substr(replace(v_rt_all_cols(i).POSTCODE,' ',''),length(replace(v_rt_all_cols(i).POSTCODE,' ',''))-2,3));
end if;
vstep_no := '13';
vtable_nm := 'before subject';
if (trim(v_rt_all_cols(i).SUBJECT) is not null) then
insert into child_tab
(COM_ID,
KEY,
VALUE)
values
(id_val,
'IB.Correspondence.Subject',
v_rt_all_cols(i).subject);
end if;
vstep_no := '14';
vtable_nm := 'before inactivity';
if (trim(v_rt_all_cols(i).UNREAD_CORRES_PERIOD) is null or
trim(v_rt_all_cols(i).UNREAD_CORRES_PERIOD) = '3' or
trim(v_rt_all_cols(i).UNREAD_CORRES_PERIOD) = '6' or
trim(v_rt_all_cols(i).UNREAD_CORRES_PERIOD) = '9') then
insert into child_tab
(COM_ID,
KEY,
VALUE)
values
(id_val,
'IB.Correspondence.Inactivity',
v_rt_all_cols(i).UNREAD_CORRES_PERIOD);
end if;
vstep_no := '14.1';
vtable_nm := 'after notfound';
end if;
vstep_no := '15';
vtable_nm := 'after notfound';
END LOOP;
end loop;
vstep_no := '16';
vtable_nm := 'before closecur';
CLOSE stg_cursor;
vstep_no := '17';
vtable_nm := 'before commit';
DELETE FROM table_stg;
COMMIT;
vstep_no := '18';
vtable_nm := 'after commit';
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
success_flag := 1;
vsql_code := SQLCODE;
vsql_errm := SUBSTR(sqlerrm,1,200);
error_logging_pkg.inserterrorlog('samp',vsql_code,vsql_errm, vtable_nm,vstep_no);
RAISE_APPLICATION_ERROR (-20011, 'samp '||vstep_no||' SQLERRM:'||SQLERRM);
end;
ThanksIts bit urgent
NO - it is NOT urgent. Not to us.
If you have an urgent problem you need to hire a consultant.
I have a performance issue in the below code,
Maybe you do and maybe you don't. How are we to really know? You haven't posted ANYTHING indicating that a performance issue exists. Please read the FAQ for how to post a tuning request and the info you need to provide. First and foremost you have to post SOMETHING that actually shows that a performance issue exists. Troubleshooting requires FACTS not just a subjective opinion.
where i am trying to insert the data from table_stg into target_tab and in parent_tab tables and then to child tables via cursor with bulk collect .the target_tab and parent_tab are huge tables and have a row wise trigger enabled on it .the trigger is mandatory . This timetaken for this block to execute is 5000 seconds.Now my requirement is to reduce it to 5 to 10 mins.
Personally I think 5000 seconds (about 1 hr 20 minutes) is very fast for processing 800 trillion rows of data into parent and child tables. Why do you think that is slow?
Your code has several major flaws that need to be corrected before you can even determine what, if anything, needs to be tuned.
This code has the EXIT statement at the beginning of the loop instead of at the end
FETCH stg_cursor BULK COLLECT INTO v_rt_all_cols LIMIT limit_in;
vstep_no := '4';
vtable_nm := 'after fetch';
--EXIT WHEN v_rt_all_cols.COUNT = 0;
EXIT WHEN stg_cursor%NOTFOUND;
The correct place for the %NOTFOUND test when using BULK COLLECT is at the END of the loop; that is, the last statement in the loop.
You can use a COUNT test at the start of the loop but ironically you have commented it out and have now done it wrong. Either move the NOTFOUND test to the end of the loop or remove it and uncomment the COUNT test.
WHEN OTHERS THEN
ROLLBACK;
That basically says you don't even care what problem occurs or whether the problem is for a single record of your 10,000 in the collection. You pretty much just throw away any stack trace and substitute your own message.
Your code also has NO exception handling for any of the individual steps or blocks of code.
The code you posted also begs the question of why you are using NAME=VALUE pairs for child data rows? Why aren't you using a standard relational table for this data?
As others have noted you are using slow-by-slow (row by row processing). Let's assume that PL/SQL, the bulk collect and row-by-row is actually necessary.
Then you should be constructing the parent and child records into collections and then inserting them in BULK using FORALL.
1. Create a collection for the new parent rows
2. Create a collection for the new child rows
3. For each set of LIMIT source row data
a. empty the parent and child collections
b. populate those collections with new parent/child data
c. bulk insert the parent collection into the parent table
d. bulk insert the child collection into the child table
And unless you really want to either load EVERYTHING or abandon everything you should use bulk exception handling so that the clean data gets processed and only the dirty data gets rejected. -
Function with for loop and parameter table/column names ... syntax help
I'm trying to create a function that returns the distinct values and counts from a user defined schema/table/column.
The code below defines an object type [stats_on_column_obj] and creates a single table of this type [stats_on_column_tab].
The function is supposed to take three input variables: p_schema_name, p_table_name, p_column_name and return a table (above).
I can hard code a SELECT statement into the () ... but once I try to convert it to parameters & exec immediate I am stuck. The red section is where the issue is (i think).
Oracle 10g.
CREATE TYPE stats_on_column_obj IS OBJECT(
COL_VAL VARCHAR2(500),
COL_VAL_CNT NUMBER (7)
CREATE TYPE stats_on_column_tab IS TABLE OF stats_on_column_obj;
CREATE OR REPLACE FUNCTION get_STATS_ON_COLUMN
p_schema_name IN varchar2,
p_table_name IN varchar2,
p_column_name IN varchar2
RETURN STATS_ON_COLUMN_tab
IS
l_STATS_ON_COLUMN_tab STATS_ON_COLUMN_tab := STATS_ON_COLUMN_tab ();
n INTEGER := 0;
str_select_tbl varchar2(5000);
BEGIN
str_select_tbl := 'SELECT '||p_column_name||' as col_val, count(*) as col_val_cnt FROM '||p_schema_name||'.'||p_table_name||' group by '||p_column_name;
FOR r IN (str_select_tbl)
LOOP
l_STATS_ON_COLUMN_tab.EXTEND;
n := n + 1;
l_STATS_ON_COLUMN_tab (n) := STATS_ON_COLUMN_obj (r.col_val, r.col_val_cnt);
END LOOP ;
RETURN l_STATS_ON_COLUMN_tab;
END;
[Error] PLS-00103 (124: 4): PLS-00103: Encountered the symbol "LOOP" when expecting one of the following: * & - + / at mod remainder rem .. <an exponent (**)> || multiset year DAY_
[Error] PLS-00103 (126: 9): PLS-00103: Encountered the symbol "=" when expecting one of the following: constant exception <an identifier> <a double-quoted delimited-identifier> table LONG_ double ref char time timestam
[Error] PLS-00103 (127: 29): PLS-00103: Encountered the symbol "(" when expecting one of the following: constant exception <an identifier> <a double-quoted delimited-identifier> table LONG_ double ref char time timestam
[Error] PLS-00103 (128: 4): PLS-00103: Encountered the symbol "END" when expecting one of the following: begin function package pragma procedure subtype type use <an identifier> <a double-quoted delimited-identifier> form
SELECT * FROM TABLE (get_STATS_ON_COLUMN('SCHEMAS_X','TABLE_X','COLUMN_X'));SCOTT@orcl > CREATE OR REPLACE
2 FUNCTION get_STATS_ON_COLUMN(
3 p_schema_name IN varchar2,
4 p_table_name IN varchar2,
5 p_column_name IN varchar2
6 )
7 RETURN STATS_ON_COLUMN_tab
8 IS
9 v_STATS_ON_COLUMN_tab STATS_ON_COLUMN_tab := STATS_ON_COLUMN_tab ();
10 v_n INTEGER := 0;
11 v_str_select_tbl VARCHAR2(5000);
12 BEGIN
13 v_str_select_tbl := 'SELECT stats_on_column_obj(' || p_column_name || ',count(*)) FROM ' ||
14 p_schema_name || '.' || p_table_name || ' group by ' || p_column_name;
15 EXECUTE IMMEDIATE v_str_select_tbl
16 BULK COLLECT
17 INTO v_STATS_ON_COLUMN_tab;
18 RETURN v_STATS_ON_COLUMN_tab;
19 END;
20 /
Function created.
SCOTT@orcl > select *
2 from table(
3 get_STATS_ON_COLUMN(
4 'SCOTT',
5 'EMP',
6 'JOB'
7 )
8 )
9 /
COL_VAL COL_VAL_CNT
CLERK 4
SALESMAN 4
PRESIDENT 1
MANAGER 3
ANALYST 2
SCOTT@orcl >
Or better change it to pipelined function.
SY. -
Generating function in for loop
I am generating a function sin[2*pi(24MHz + f)] - sin[24MHz]. The 'f' has to vary from -2MHz to 2MHz. I have to add the output of this loop with another 24MHz sine wave input. I have attached the code, please let me know whether what has been done is right or no.
Attachments:
AD9852 Set FTW1.vi 50 KBNo, you code makes no sense. You simply get an array of 10 identical values, because nothing changes as a function if iteration count.
PKBombay wrote:
I am generating a function sin[2*pi(24MHz + f)] - sin[24MHz]. The 'f' has to vary from -2MHz to 2MHz. I have to add the output of this loop with another 24MHz sine wave input. I have attached the code, please let me know whether what has been done is right or no.
I don't understand your formula, e.g. what is "sin[24MHz]"? Just a constant?
Is the solution 1D (y vs. f) or 2D (e.g. y vs. (f,t))?
Can you point to a web site that describes the math?
LabVIEW Champion . Do more with less code and in less time . -
Any difference between distinct and aggregate function in sql query cost???
Hi,
I have executed many sql stmts patterns- such as:
a) using a single table
b) using two tables, using simple joins or outer joins
but i have not noticed any difference in sql stmts in cost and in execution plan....
Anyway, my colleague insists on that using aggregate function is less costly compared to
distinct....(something i have not confirmed, that's why i beleive that they are exactly the same...)
For the above reffered 1st sql pattern.. we could for example use
select distinct deptno
from emp
select count(*), deptno
from emp
group by deptno select distinct owner, object_type from all_objects
select count(*), owner, object_type from all_objects
group by owner, object_typeHave you found any difference between the two ever...????
Note: I use Ora DB 10g v2.
Thank you,
Simdistinct and aggregate function are for different uses and may give same result but if u r using aggregate function to get distinct records, it will be expensive...
ex
select distinct deptno from scott.dept;
Statistics
0 recursive calls
0 db block gets
2 consistent gets
0 physical reads
0 redo size
584 bytes sent via SQL*Net to client
488 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
4 rows processed
select deptno from scott.emp group by deptno;
Statistics
307 recursive calls
0 db block gets
60 consistent gets
6 physical reads
0 redo size
576 bytes sent via SQL*Net to client
488 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
6 sorts (memory)
0 sorts (disk)
3 rows processed
Nimish Garg
Software Developer
*(Oracle & ASP.NET)*
Indiamart Intermesh Limited, Noida
To Get Free Oracle & ASP.NET Code Snippets
Follow: http://nimishgarg.blogspot.com -
Using aggregate function count
hi experts,
I want to select 2 fields from a table and put into structure (gw_konzs.) and with respect to that i want to use aggregate function count(*) for knowing how many rows has been selected ? and i dont want to use select & endselect
please help regarding this ...........
for example:
select konts ltext from ztab into corresponding fields of gw_konzs.
select count(*) from kna1 into gw_konzs
where konzs = gw_konzs-konzs.
append gw_konzs to gt_konzs
endselect.hi experts,
I want to select 2 fields from a table and put into structure and i want to select based on the where condition i dont want to use select & endselect
please help regarding this ...........
rewarded if useful
for example:
gw_detail & gw_konzs is structure
gt_detail & gt_konzsis internal table
select kunnr name1 from kna1 into corresponding fields of gw_detail where konzs = gw_konzs-konzs.
gw_detail-konzs = gw_konzs-konzs.
append gw_detail-konzs to gt_detail-konzs
endselect. -
Trying to create a Histogram type/object for aggregate functions
Hi,
I am trying to create an aggregate function that will return a histogram
type.
It doesn't have to be an object that is returned, I don't mind returning
a string but I would like to keep the associative array (or something
else indexed by varchar2) as a static variable between iterations.
I started out with the SecondMax example in
http://www.csis.gvsu.edu/GeneralInfo/Oracle/appdev.920/a96595/dci11agg.htm#1004821
But even seems that even a simpler aggregate function like one strCat
below (which works) has problems because I get multiple permutations for
every combination. The natural way to solve this would be to create an
associative array as a static variable as part of the Histogram (see
code below). However, apparently Oracle refuses to accept associate
arrays in this context (PLS-00355 use of pl/sql table not allowed in
this context).
If there is no easy way to do the histogram quickly can we at least get
something like strCat to work in a specific order with a "partition by
... order by clause"? It seems that even with "PARALLEL_ENABLE"
commented out strCat still calls merge for function calls like:
select hr,qtr, count(tzrwy) rwys,
noam.strCat(cnt) rwycnt,
noam.strCat(tzrwy) config,
sum(cnt) cnt, min(minscore) minscore, max(maxscore) maxscore from
ordrwys group by hr,qtr
Not only does this create duplicate entries in the query result like
"A,B,C" and "A,C,B" it seems that the order in rwycnt and config are not
always the same so a user can not match the results based on their
order.
The difference between my functions and functions like sum and the
secondMax demonstrated in the documentation is that secondMax does not
care about the order in which it gets its arguments and does not need to
maintain an ordered set in order to return the correct results. A good
example of a built in oracle function that does care about all its
arguments and probably has to maintain a similar data structure to the
one I want is the PERCTILE_DISC function. If you can find the code for
that function (or something like it) and forward a reference to me that
in itself would be very helpful.
Thanks,
K.Dingle
CREATE OR REPLACE type Histogram as object
-- TYPE Hist10 IS TABLE OF pls_integer INDEX BY varchar2(10),
-- retval hist10;
-- retval number,
retval noam.const.hist10,
static function ODCIAggregateInitialize (sctx IN OUT Histogram)
return number,
member function ODCIAggregateIterate (self IN OUT Histogram,
value IN varchar2) return number,
member function ODCIAggregateTerminate (self IN Histogram,
returnValue OUT varchar2,
flags IN number) return number,
member function ODCIAggregateMerge (self IN OUT Histogram,
ctx2 IN Histogram) return number
CREATE OR REPLACE type body Histogram is
static function ODCIAggregateInitialize(sctx IN OUT Histogram) return
number is
begin
sctx := const.Hist10();
return ODCIConst.Success;
end;
member function ODCIAggregateIterate(self IN OUT Histogram, value IN
varchar2)
return number is
begin
if self.retval.exist(value)
then self.retval(value):=self.retval(value)+1;
else self.retval(value):=1;
end if;
return ODCIConst.Success;
end;
member function ODCIAggregateTerminate(self IN Histogram,
returnValue OUT varchar2,
flags IN number)
return number is
begin
returnValue := self.retval;
return ODCIConst.Success;
end;
member function ODCIAggregateMerge(self IN OUT Histogram,
ctx2 IN Histogram) return number is
begin
i := ctx2.FIRST; -- get subscript of first element
WHILE i IS NOT NULL LOOP
if self.retval.exist(ctx2(i))
then self.retval(i):=self.retval(i)+ctx2.retval(i);
else self.retval(value):=ctx2.retval(i);
end if;
i := ctx2.NEXT(i); -- get subscript of next element
END LOOP;
return ODCIConst.Success;
end;
end;
CREATE OR REPLACE type stringCat as object
retval varchar2(16383), -- concat of all value to now varchar2, --
highest value seen so far
static function ODCIAggregateInitialize (sctx IN OUT stringCat)
return number,
member function ODCIAggregateIterate (self IN OUT stringCat,
value IN varchar2) return number,
member function ODCIAggregateTerminate (self IN stringCat,
returnValue OUT varchar2,
flags IN number) return number,
member function ODCIAggregateMerge (self IN OUT stringCat,
ctx2 IN stringCat) return number
CREATE OR REPLACE type body stringCat is
static function ODCIAggregateInitialize(sctx IN OUT stringCat) return
number is
begin
sctx := stringCat('');
return ODCIConst.Success;
end;
member function ODCIAggregateIterate(self IN OUT stringCat, value IN
varchar2)
return number is
begin
if self.retval is null
then self.retval:=value;
else self.retval:=self.retval || ',' || value;
end if;
return ODCIConst.Success;
end;
member function ODCIAggregateTerminate(self IN stringCat,
returnValue OUT varchar2,
flags IN number)
return number is
begin
returnValue := self.retval;
return ODCIConst.Success;
end;
member function ODCIAggregateMerge(self IN OUT stringCat,
ctx2 IN stringCat) return number is
begin
self.retval := self.retval || ctx2.retval;
return ODCIConst.Success;
end;
end;
CREATE OR REPLACE FUNCTION StrCat (input varchar2) RETURN varchar2
-- PARALLEL_ENABLE
AGGREGATE USING StringCat;GraphicsConfiguration is an abstract class. You would need to subclass it. From the line of code you posted, it seems like you are going about things the wrong way. What are you trying to accomplish? Shouldn't this question be posted in the Swing or AWT forum?
-
Javascript For loop not working within a function
Hi all,
I'm a beginner to LiveCycle and I cant seem to get a loop working within a function. The function is being called successfully because when I manually create the code it works but I am trying to clean things up.
So here is my working example:
function hideContent() {
MainFlowedSub.LevelsSub.Table1.presence = "hidden";
MainFlowedSub.LevelsSub.Table2.presence = "hidden";
... and so on....
MainFlowedSub.LevelsSub.Table8.Row1.presence = "hidden";
MainFlowedSub.LevelsSub.Table8.Row2.presence = "hidden";
... and so on....
However when I try and creat a loop instead of listing every sing table/row nothing happens. this is important to my project as there will be alot of different rows depending on radio button selections earlier in the form. Below is the current state of my code:
function hideContent() {
var i=0;
for (i=1;i<=5;i++)
MainFlowedSub.LevelsSub.Table[i].presence = "hidden";
var j=0;
for (j=1;j<=23;j++)
MainFlowedSub.LevelsSub.Table8.Row[j].presence = "hidden";
var k=0;
for (k=24;k<=88;k++)
MainFlowedSub.LevelsSub.Table8.Row[k].presence = "hidden";
this will then continue as there will be hundreds of rows.
Any help will be greatly appreciated and I am sure I am making a basic error so thanks in advance.
jthanks for your help paul. Again, really appreciated as I know very little about all this.
Unfortunately its still not working... One thing I am sure of is that I am doing something very basic wrong. So here is my code, I have applied your suggestion above which will cover all my data:
To give an understanding, I have 5 tables of content, each has i amount of rows. and I am running this script to clear/remove all items being displayed.
function hideContent() {
for (var i=1;i<=5;i++)
xfa.resolveNode("MainFlowedSub.LevelsSub.Table[" + i + "]").presence = "hidden";
for (var i=1;i<=71;i++)
xfa.resolveNode("MainFlowedSub.LevelsSub.Table8.Row[" + i + "]").presence = "hidden";
for (var i=1;i<=93;i++)
xfa.resolveNode("MainFlowedSub.LevelsSub.Table9.Row[" + i + "]").presence = "hidden";
for (var i=1;i<=99;i++)
xfa.resolveNode("MainFlowedSub.LevelsSub.Table10.Row[" + i + "]").presence = "hidden";
for (var i=1;i<=101;i++)
xfa.resolveNode("MainFlowedSub.LevelsSub.Table11.Row[" + i + "]").presence = "hidden";
for (var i=1;i<=87;i++)
xfa.resolveNode("MainFlowedSub.LevelsSub.Table12.Row[" + i + "]").presence = "hidden";
It has to be something to do with my For loops because if I manually insert each line it works perfectly.
Thanks again,
johnny -
Creating a function with a for loop and %type
Hello,
I am trying to create a function which contains a for loop as well as %type.
This function is on a student table and i am trying to create a function which will display the zip which is a varchar2(5).
I need to do this through this function.
However, I can't seem to get it running.
Can anyone help?
below is what i tried as well as other options and was not successful.
I also displayed my error with the show error command.
SQL> create or replace function zip_exist
2 return varchar2
3 is
4 v_zip student.zip%TYPE;
5 cursor c_zip is
6 select zip
7 from
8 student
9 where zip=zip;
10 begin
11 open c_zip;
12 v_zip IN c_zip
13 loop
14 v_zip:=c_zip%TYPE;
15 end loop;
16 close c_zip;
17 end;
18 /
Warning: Function created with compilation errors.
SQL> show error
Errors for FUNCTION ZIP_EXIST:
LINE/COL ERROR
12/7 PLS-00103: Encountered the symbol "IN" when expecting one of the
following:
:= . ( @ % ;
16/1 PLS-00103: Encountered the symbol "CLOSE"
SQL>
kabrajouser10873577 wrote:
Hello,
I am trying to create a function which contains a for loop as well as %type.
This function is on a student table and i am trying to create a function which will display the zip which is a varchar2(5).
I need to do this through this function.
However, I can't seem to get it running.
Can anyone help?
below is what i tried as well as other options and was not successful.
I also displayed my error with the show error command.
SQL> create or replace function zip_exist
2 return varchar2
3 is
4 v_zip student.zip%TYPE;
5 cursor c_zip is
6 select zip
7 from
8 student
9 where zip=zip;
10 begin
11 open c_zip;
12 v_zip IN c_zip
13 loop
14 v_zip:=c_zip%TYPE;
15 end loop;
16 close c_zip;
17 end;
18 /
Warning: Function created with compilation errors.
SQL> show error
Errors for FUNCTION ZIP_EXIST:
LINE/COL ERROR
12/7 PLS-00103: Encountered the symbol "IN" when expecting one of the
following:
:= . ( @ % ;
16/1 PLS-00103: Encountered the symbol "CLOSE"
SQL>
kabrajoTry This
Create a sample table
SQL> create table student(id number(10),zip varchar2(5));
Table created.Insert the record
SQL> insert into student values(1111,'A5454');
1 row created.
SQL> commit;
Commit complete.
SQL> select * from student;
ID ZIP
1111 A5454
SQL> create or replace function zip_exist(v_id number)
2 return varchar2
3 is
4 v_zip student.zip%TYPE;
5 BEGIN
6 select zip
7 INTO v_zip
8 FROM student
9 where id=v_id;
10 Return v_zip;
11 EXCEPTION WHEN NO_DATA_FOUND THEN
12 RETURN 'INVALD';
13 WHEN OTHERS THEN
14 return 'NA!';
15 end;
16 /
Function created.
SQL> set serveroutput on
SQL> select zip_exist(1111) from dual;
ZIP_EXIST(1111)
A5454
SQL> select zip_exist(2222) from dual;
ZIP_EXIST(2222)
INVALDHope this helps
Regards,
Achyut K -
How to insert elements into an array after each iteration of a for loop
I am new to labview and working on an application where I am supposed to store an element into an array (without overwriting) after each iteration in a for loop. I have tried using Build Array Function keeping the indicator outside the for loop and played with indexing but didn't work. Please suggest me an idea how to do it.
Thanks
Solved!
Go to Solution.Thank you for your suggestion.Here is my actual application attached . In the first image, a difference in time is evaluated and an enum const of insert into array is passed to the shift register where it takes to Insert element into array phase (Second image). I need to enter the time difference into an array after every loop iteration. Please have a look and could you let me know where I am mislead.
Attachments:
Image 1.JPG 88 KB
Image 2.JPG 71 KB -
Calling Function in a loop for CM
Hi,
I have the program to create Credit Memo with user selected records. It is working if the user selects any one customer and it will create CM for that customer. But now user wants to select different customers and based on each different vkorg vtweg spart kunnr it has to create different Credit Memo's. How should I put the function in the loop so that it creates different CM's based on each customer.
Please help me.
Thanks,
Neelu.
AT USER-COMMAND.
CASE sy-ucomm.
WHEN 'CMEMO'.
DESCRIBE TABLE gt_zprice LINES lv_cnt.
DO lv_cnt TIMES.
lv_index = sy-index + 1.
READ LINE lv_index FIELD VALUE chbox.
IF chbox = 'X'.
READ TABLE gt_zprice INTO gs_zprice1 INDEX sy-index.
IF sy-subrc EQ 0.
gs_zprice1-index = sy-index.
APPEND gs_zprice1 TO gt2_zprice.
CLEAR gs_zprice1.
ENDIF.
ENDIF.
CLEAR chbox.
ENDDO.
gt4_zprice[] = gt2_zprice[].
* SORT gt2_zprice BY vkorg vtweg spart kunnr.
* DELETE ADJACENT DUPLICATES FROM gt2_zprice
* COMPARING vkorg vtweg spart kunnr.
* DESCRIBE TABLE gt2_zprice LINES lv_lines.
* IF lv_lines = 1.
LOOP AT gt4_zprice INTO gs_zprice1.
AT NEW kunnr.
MOVE 'Y' TO lv_flg.
ENDAT.
IF lv_flg EQ 'Y'.
PERFORM headerdata.
PERFORM texts.
CLEAR lv_flg.
ENDIF.
PERFORM itemdata.
APPEND gs_zprice1 TO gt3_zprice.
CLEAR gs_zprice1.
ENDLOOP.
lv_itemno = 10.
PERFORM call_function.
PERFORM update_pricetable.
PERFORM errorcheckandcommit.
PERFORM displaydata.
REFRESH gt2_zprice.
CLEAR chbox.
CLEAR lv_lines.
REFRESH partner.
REFRESH item.
REFRESH itemx.
REFRESH lt_schedules_in.
REFRESH lt_schedules_inx.
REFRESH conditions1.
REFRESH order_text.
ELSE.
REFRESH gt2_zprice.
CLEAR chbox.
EXIT.
ENDIF.
ENDCASE.call the credimemo create routines at end of kunnr inside the loop.
LOOP AT gt4_zprice INTO gs_zprice1.
AT NEW kunnr.
MOVE 'Y' TO lv_flg.
ENDAT.
IF lv_flg EQ 'Y'.
PERFORM headerdata.
PERFORM texts.
CLEAR lv_flg.
ENDIF.
PERFORM itemdata.
APPEND gs_zprice1 TO gt3_zprice.
CLEAR gs_zprice1.
<b>at end of kunnr.
PERFORM call_function.
PERFORM update_pricetable.
PERFORM errorcheckandcommit.
PERFORM displaydata.
REFRESH gt2_zprice.
CLEAR chbox.
CLEAR lv_lines.
REFRESH partner.
REFRESH item.
REFRESH itemx.
REFRESH lt_schedules_in.
REFRESH lt_schedules_inx.
REFRESH conditions1.
REFRESH order_text.
endat.</b>
ENDLOOP.
lv_itemno = 10.
ELSE.
REFRESH gt2_zprice.
CLEAR chbox.
EXIT.
ENDIF.
ENDCASE. -
Insert Procedure For LOOP question
Hi all,
I have made a Procedure which basically massages data and loads into into another table and makes a time record aswell. I am practising my good datawarehousing practise (So load table into real DW_table)
I am using an Explicit Cursor For Loop....
What i was wondering is if there is some type of SQL%rowcount I can do in order to check that the record where "INSERTED" into dw_client and dw_time; before i create a auit record in another table. I know this is normally done using triggers, but I am testing this for a Datawarehouse and not sure triggers are the best answer. But please correct me if im wrong:
I basically wanted to put another insert in there, if the inserts actually ran!RPuttagunta wrote:
Why can you not use a merge statement in your code instead of writing a whole procedure for it?
merge into mehmet_schema.dw_client a
using
mehmet_schema.client.....
If I understand it right, you are checking if there are any records that exists in 'client' and doesn't exist in 'dw_client' table, then, you are inserting. Is that correct?Yes that is correct. Also I am inserting into the dw_time table using the sqeuence values, so i didnt think merge statement would do this!
aslo i wanted to use this procedure to clean up some of the data, as you can see in my Cursor, again why i havent used a merge
Edited by: oraCraft on 09-Nov-2010 09:53 -
I need to parameterise the query in the for loop, but VS2013 keeps telling me that @reference0 must be defined.
Any reason why this keeps happening?
var dbConnect = new DbConnect();
var cmd = new MySqlCommand();
dbConnect.OpenConnection();
var query =
"INSERT INTO booking (operator_id, plot_id, postcode, datetime, stops, " +
"mileage, price, passengers, name, note, phone, status, reference) " +
"VALUES (@operator_id, @plot_id, @postcode, @datetime, @stops, " +
"@mileage, @price, @passengers, @name, @note, @phone, @status, @reference);";
for (var i = 0; i < _waypointList.Count; i++)
query +=
@"INSERT INTO waypoint
(booking_id, sequence, address, lat, lng, reference)
VALUES
((select id FROM booking WHERE reference=@reference" + i + @"),
@sequence" + i + @",
@address" + i + @",
@lat" + i + @",
@lng" + i + @",
@reference" + i + ")";
cmd.Parameters.AddWithValue(("@reference" + i), _reference);
cmd.Parameters.AddWithValue(("@sequence" + i), i);
cmd.Parameters.AddWithValue(("@address" + i), _waypointList[i]);
cmd.Parameters.AddWithValue(("@lat" + i), _lat);
cmd.Parameters.AddWithValue(("@lng" + i), _lng);
Console.WriteLine(query);
cmd = new MySqlCommand(query, DbConnect.Connection);
cmd.Parameters.AddWithValue(("@operator_id"), _operatorId);
cmd.Parameters.AddWithValue(("@plot_id"), _plotId);
cmd.Parameters.AddWithValue(("@postcode"), _postcode);
cmd.Parameters.AddWithValue(("@datetime"), _datetime);
cmd.Parameters.AddWithValue(("@stops"), _stops);
cmd.Parameters.AddWithValue(("@mileage"), _mileage);
cmd.Parameters.AddWithValue(("@price"), _price);
cmd.Parameters.AddWithValue(("@passengers"), _passengers);
cmd.Parameters.AddWithValue(("@name"), _name);
cmd.Parameters.AddWithValue(("@note"), _note);
cmd.Parameters.AddWithValue(("@phone"), _phone);
cmd.Parameters.AddWithValue(("@status"), Status);
cmd.Parameters.AddWithValue(("@reference"), _reference);
cmd.ExecuteNonQuery();
dbConnect.CloseConnection();reason :>
for (var i = 0; i < _waypointList.Count; i++)
query +=
@"INSERT INTO waypoint
(booking_id, sequence, address, lat, lng, reference)
VALUES
((select id FROM booking WHERE reference=@reference" + i + @"),
@sequence" + i + @",
@address" + i + @",
@lat" + i + @",
@lng" + i + @",
@reference" + i + ")";
cmd.Parameters.AddWithValue(("@reference" + i), _reference);
cmd.Parameters.AddWithValue(("@sequence" + i), i);
cmd.Parameters.AddWithValue(("@address" + i), _waypointList[i]);
cmd.Parameters.AddWithValue(("@lat" + i), _lat);
cmd.Parameters.AddWithValue(("@lng" + i), _lng);
Mark as answer or vote as helpful if you find it useful | Ammar Zaied [MCP]
Maybe you are looking for
-
How can I display data gathered in a subVI in a graph of the main VI?
I have written a largish application (~50 VI's) which acquires, analyzes, display and saves data from an instrument with a built-in DAQPad. My problem is that my block diagram is rather messy by now. I'm using an event structure in my main VI which r
-
Can't access my IPhone 4S following the IOS 7 latest update
Hello everyone, I'm new to this forum and I really need your help. I own and IPhone 4S since October 2011 and I have always updated it with the latest updates. Yesterday evening was no different when I updated my phone with the latest IOS 7 version 7
-
Is apple doing any thing to solve the issue foe WIFI grayout
is apple doing any thing to solve the WIFI grayout ISSUE
-
I just received my new AirPort Extreme and would like to know how to get it to work with my Verizon Fios router, replacing the WiFi function of the router with the AE. I have the Airport Utility installed on my pathetic Windows 8 PC and on my iPad Ai
-
Hi, I create fillable fields on a form in which existing values are to be completed only when a checkbox is checked. My problem is this: Page1 [name] (manually compiled) [Last name] (manually compiled) [Address] (manually compiled) [etc...] (manually