Plsql code using cursors
Hi,
I am a new learner and i want to know how to write a code to get the data and insert into table.
My scenario is: I have 3 databases - for example db1,db2 and db3
I have one table called xx_fnd_lkp (column names: lkp1,lkp2,lkp3,lkp4,lkp5,lkp6,lkp7,lkp8,lkp9 and lkp10) in db1 and db2. for lkp1,lkp2,lkp3 has unique index.
Now i want to write the code to get all the recodrs from db1 and db2 (no duplicates) and insert into db3.
we have to insert only one record if db1 and db2 has same record.
please let me know how to write a procedure.
Thanks
shashi
user843979 wrote:
My scenario is: I have 3 databases - for example db1,db2 and db3
I have one table called xx_fnd_lkp (column names: lkp1,lkp2,lkp3,lkp4,lkp5,lkp6,lkp7,lkp8,lkp9 and lkp10) in db1 and db2. for lkp1,lkp2,lkp3 has unique index.
Now i want to write the code to get all the recodrs from db1 and db2 (no duplicates) and insert into db3.
create or replace procedure p as
begin
insert into xx_fnd_lkp
(lkp1,lkp2,lkp3,lkp4,lkp5,lkp6,lkp7,lkp8,lkp9 ,lkp10)
select lkp1,lkp2,lkp3,lkp4,lkp5,lkp6,lkp7,lkp8,lkp9 ,lkp10 from xx_fnd_lkp@db1
union
select lkp1,lkp2,lkp3,lkp4,lkp5,lkp6,lkp7,lkp8,lkp9 ,lkp10 from xx_fnd_lkp@db2;
end;@ = a database link
Manuals for reference
http://download.oracle.com/docs/cd/E11882_01/server.112/e10592/toc.htm
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10766/toc.htm
http://www.oracle.com/pls/db112/homepage
or for other versions
http://tahiti.oracle.com/
You wouldn't use a cursor unless you have a requirement to slow the procedure down as much as possible.
Edited by: 3360 on Jul 6, 2010 4:02 PM
Additional -
The procedure would be created in db3
This could still violate primary key on three columns, but you did not specify which row(s) you want the other non-PK column values from and what logic determines that.
Similar Messages
-
NLS issue in Java/PLSQL code [ using ROWID]
I have NLS related question regarding the following scenario in Java/PLSQL code ::-
OracleResultSet ors = (OracleResultSet) stmt.executeQuery("select rowId from t where t.col = 'XX'");
// The above query could return multiple rowIds.
String strVal1 = null;
String strVal2 = null;
if(ors.next())
strVal1 = ors.getROWID(1).stringValue();
if(ors.next())
strVal2 = ors.getROWID(1).stringValue();
ArrayList strList = new ArrayList();
strList.add(strVal1);
strList.add(strVal2);
Now I need to pass a list of rowId's from Java to PLSQL function f().
oracle.sql.ARRAY rowListArr = convertArrayListToRowPointerList(strList, conn) ;
OracleCallableStatement cstmt = (OracleCallableStatement)
cstmt.prepareCall("begin f(?); end;");
cstmt.setObject(1, rowListArr);
cstmt.execute();
where:-
static oracle.sql.ARRAY convertArrayListToRowPointerList(ArrayList arr, Connection conn)
throws SQLException {
oracle.sql.ArrayDescriptor stDesc = ArrayDescriptor.createDescriptor
("DBUSER.ROWPOINTERLIST", conn);
oracle.sql.Datum[] keyVals= new oracle.sql.Datum[arr.size()];
for(int i = 0; i < arr.size(); i++) {
keyVals[i] = new oracle.sql.CHAR((String) arr.get(i),
oracle.sql.CHAR.DEFAULT_CHARSET);
oracle.sql.ARRAY keyArr = new oracle.sql.ARRAY(stDesc, conn, keyVals);
return keyArr;
and
create or replace type DBUSER.ROWPOINTERLIST as table of varchar2(4000);
Will there be NLS issues in the above code, where I pass the rowId content
that I obtain from one query, as array of string bind variables to a subsequent PLSQL procedure? --- first approach
Or
do I need to pass the rowId list , as a array of oracle.sql.ROWID via bind variables? -- second approach
The problem I have in second approach is that in the DB we cannot define a type as a table of ROWID's. So currently I have RowPointerList as a table of varchar2's (note the length of list of rowId is not predetermined in my case, so I user table instead of varray).
However I was wondering if the first approach will have any NLS issues.
Will appreciate your comments.
ThanksROWIDs are represented as either hex-encoded values or base64 encoded values. Both encodings use pure ASCII, so there should be no NLS issues.
I am not very familiar with the oracle.sql.ARRAY type, but unless absolutely necessary, I would avoid the oracle.sql.CHAR datatype (assuming 10g drivers). Using java.lang.String is preferred.
-- Sergiusz -
Display a value from PLSQL code to screen
How to display a value from PLSQL code to screen without loading or refreshing the page?
im using ajax to call the javascript to run the PLSQL code. i desire to view some value in the screen when i run the PLSQL code
skud.anything that you print from the PLSQL code(using htp.p, htp.prn etc) with will available in Javascript as the server response. You can parse that string it in javascript and display it on screen or modify page items or create dynamic items/elements using those values.
A minimal example
Ondemand PLSQL process : TEST_PROCESS
begin
htp.prn('hello world');
end;Javascript Code
var ajaxRequest = new htmldb_Get(null,&APP_ID.,'APPLICATION_PROCESS=TEST_PROCESS',0);
ajaxResult = ajaxRequest.get();
alert(ajaxResult);Will display an alert message "hello world"
You can construct the string in JSON/XML format in PLSQL to pass complex data structures(or multiple values) or even HTML code, then do the required processing in Javascript, for example extract out item values from it and set items, convert the JSON array to a select list item in the page or put the HTML code with a div element in the page. -
To automate the SQL scripts using PLSQL Code
Hi All,
I have 20 database server (11.2.0.3) hosted on unix and Windows platforms.
Every day I have to kill inactive sessions from all the these 20 database servers. So I have made a below script::
connect sys/&&sys_password@&&tns_database_name as sysdba
SPOOL E:\DELETE_INACTIVE_SESSIONS.SQL
set PAGESIZE 1000
set LIN 5000
SET ECHO OFF;
SET FEEDBACK OFF;
SET HEADING OFF;
select 'alter system kill session '||'`'||SID||','||SERIAL#||'`'||' immediate;' from v$session where status='INACTIVE' and username in ('OSS_DICTIONARY','ADMINISTRATOR');
SPOOL OFF;
@@E:\DELETE_INACTIVE_SESSIONS.SQL
Is there any way so that this execution of script can be automated in PLSQL code for 20 servers so and that code could be put in batch file for execution(i.e. can be execute through batch file from my windows laptop).
ThanksShrma wrote:
Is there no way to handle the sql scripts in PLSQL code?
Well, remember that PL/SQL is executed on a specific server by a certain user so you are already connected when executing a PL/SQL code.
You could actually use a SQL Plus script to connect to different servers using connect and run your script.
i.e.:
SQL> connect sys/pwd_server1@db_server1
SQL> @killinactive.sql
SQL> connect sys/pwd_server2@db_server2
SQL> @killinactive.sql
But it does not make so much difference with my previous solution.
Please explain exactly what you would like to do.
Regards.
Al -
Publish a plsql code as webservice without using JDEVELOPER or APEX
Hi All,
I am looking into how can we publish a PLSQL code as web-service without using JDEV OR APEX.
When I google for this one I can see only by using JDEV or APEX we can publish Code as a web-service.
Is there any way in oracle, just by using simple PLSQL packages we can publish code as a webservice.
Appreciate your response.
Thanks,
MK.Apex does not publish PL/SQL code as web services. It is a web run-time and development framework. Something totally different.
To turn a PL/SQL function into a web service is simple. You use the orawsv servlet in XDB - without making a single code change to the function. It will not even know it is called as a web service.
To use orawsv, two basic steps. Configure and enable the servlet (raw HTTP/HTTPS connections will be handled by the Listener). This also entails enabling shared server in the database, if not already enabled. The 2nd step is to allow the function to be executed (via a HTTP call) as a web service, via granting specific roles.
orawsv handles the HTTP call. It provides the WSDL. It parses SOAP envelopes as input. It makes the call (as a standard PL/SQL call), to the function being used as a web service. It returns the results of the PL/SQL function call, as a SOAP envelope output.
See Support Notes:
How to Setup Native Oracle XML DB Web Services [Article ID 444191.1]
Sample Framework for testing Native Oracle XML DB Web Services [Article ID 803794.1]
How to Browse Native Oracle XML DB Web Services Example [Article ID 1324235.1] -
Hii...Experts
I ve written a plsql anonymous block code in database . That code is selecting 2 columns from source and want to implement that code in ODI interface in such a way that the values of two columns should be loaded into target.
How to do the such interface??
Please Help..
Thanks
Edited by: soumya.rn on Mar 23, 2012 3:54 AMIf yoru PLSQL code is in a "oracle package" object, you can call this object in an ODI interface
example :
your oracle package is called "my_PL_proc" and the parameter requires the source column "ID_PRODUCT"
in your ODI mapping, you can call it :
<%=odiRef.getObjectName("L", "my_PL_proc", "D") %>(source_table.ID_PRODUCT) -
Using Cursor attributes in Pro*C application (.pc file)
hi,
Does anyone know, what is hte equivalent of following PLSQL code in PRO*C??
declare
cursor c1 as select * from emp;
begin
if c1%isopen then
close c1;
else
open c1;
end;
I m able to get the cursor working succefully as such. But before my procedure opens it, i want to check whether it has been left open by the loop or whatever...
So what is the equivalent of "if c1%isopen....." in Pro*C??
I am able to get hte paramterized cursor workign as given in the book - Guide to ORacle Precompilers . But that does not mention anything about Cursor attributes usage in the Pro*C code.
Pls help...
thanks
regards
AbhivyaktiHi Leonid, Andrea
When you use "CONNECT AT :db_handle" instead of default connection "CONNECT", you have to give the connect handle to the command you want to execute.
ie:
EXEC SQL AT :db_handle PREPARE SQL_stat FROM "select ...";
EXEC SQL AT :db_handle DECLARE cur_stat CURSOR for SQL_stat;
EXEC SQL AT :db_handle OPEN cur_stat ;
EXEC SQL AT :db_handle FETCH cur_stat INTO :resrec;
Leonid, the error you had is probably because you connected at "DB_VE", and tried to select from default connect (that you're not connected to ==> ORA-01012)
Try EXEC SQL AT :DB_VE FETCH :c1 INTO :resrec;
or, if you connect to only 1 database, use "EXEC SQL CONNECT;" instead of (EXEC SQL CONNECT :pConnectString AT "DB_VE";) so that you use default connect name and you don't have to add "AT :DB_VE" to your SQL commands.
I know this reply comes long after your request, but I hope it may still help anybody. -
Hi
My oracle db version is 11g R1/AIX5.3
how following plsql code can be re-written for better performance
CREATE OR REPLACE PROCEDURE CSCOMMON.POST_SEQ_PROCESS
AS
-- Declare variables to hold sequenced infomration.
pragma autonomous_transaction;
V_RECORD_ID POST_SEQUENCING_PROCESS.RECORD_ID%TYPE;
V_RECEIVED POST_SEQUENCING_PROCESS.RECEIVED%TYPE;
V_PROCESS_NAME POST_SEQUENCING_PROCESS.PROCESS_NAME%TYPE;
V_PROCESS_ID POST_SEQUENCING_PROCESS.PROCESS_ID%TYPE;
V_PROCESS_SEQ POST_SEQUENCING_PROCESS.PROCESS_SEQ%TYPE;
V_RECEIVER POST_SEQUENCING_PROCESS.RECEIVER%TYPE;
V_RECEIVER_ID POST_SEQUENCING_PROCESS.RECEIVER_ID%TYPE;
V_RECEIVER_SEQ POST_SEQUENCING_PROCESS.RECEIVER_SEQ%TYPE;
V_SENDER POST_SEQUENCING_PROCESS.SENDER%TYPE;
V_SENDER_ID POST_SEQUENCING_PROCESS.SENDER_ID%TYPE;
V_MESSAGE_ID POST_SEQUENCING_PROCESS.MESSAGE_ID%TYPE;
V_INSTANCE_ID POST_SEQUENCING_PROCESS.INSTANCE_ID%TYPE;
V_STATUS POST_SEQUENCING_PROCESS.STATUS%TYPE;
V_STEP_ID POST_SEQUENCING_PROCESS.STEP_ID%TYPE;
V_INTERNAL_ID POST_SEQUENCING_PROCESS.INTERNAL_ID%TYPE;
V_LOCK_ID POST_SEQUENCING_PROCESS.LOCK_ID%TYPE;
V_ERROR_HANDLING POST_SEQUENCING_PROCESS.ERROR_HANDLING%TYPE;
V_STARTED POST_SEQUENCING_PROCESS.STARTED%TYPE;
V_WARNINGS POST_SEQUENCING_PROCESS.WARNINGS%TYPE;
V_DOCUMENTTYPE_NAME POST_SEQUENCING_PROCESS.DOCUMENTTYPE_NAME%TYPE;
V_DOCUMENTTYPE_ID POST_SEQUENCING_PROCESS.DOCUMENTTYPE_ID%TYPE;
V_DOCUMENTTYPE_SEQ POST_SEQUENCING_PROCESS.DOCUMENTTYPE_SEQ%TYPE;
v_current VARCHAR2 (600);
v_sql_error VARCHAR2 (600);
lv_count NUMBER;
CURSOR c_first500
IS
SELECT RECORD_ID,
RECEIVED,
PROCESS_NAME,
PROCESS_ID,
PROCESS_SEQ,
RECEIVER,
RECEIVER_ID,
RECEIVER_SEQ,
SENDER,
SENDER_ID,
MESSAGE_ID,
INSTANCE_ID,
STATUS,
STEP_ID,
INTERNAL_ID,
LOCK_ID,
ERROR_HANDLING,
STARTED,
WARNINGS,
DOCUMENTTYPE_NAME,
DOCUMENTTYPE_ID,
DOCUMENTTYPE_SEQ
FROM ( SELECT RECORD_ID,
RECEIVED,
PROCESS_NAME,
PROCESS_ID,
PROCESS_SEQ,
RECEIVER,
RECEIVER_ID,
RECEIVER_SEQ,
SENDER,
SENDER_ID,
MESSAGE_ID,
INSTANCE_ID,
STATUS,
STEP_ID,
INTERNAL_ID,
LOCK_ID,
ERROR_HANDLING,
STARTED,
WARNINGS,
DOCUMENTTYPE_NAME,
DOCUMENTTYPE_ID,
DOCUMENTTYPE_SEQ
FROM CSCOMMON.SEQUENCING_PROCESS
ORDER BY RECEIVED)
WHERE ROWNUM < 101;
P_RAND NUMBER;
V_LID NUMBER;
BEGIN
v_current := 'BEFORE CURSOR OPENING';
SELECT COUNT (*) INTO lv_count FROM POST_SEQUENCING_PROCESS;
OPEN c_first500;
LOOP
SELECT CSCOMMON.SEQ_LID_SEQUENCING_PROCESS_NU.NEXTVAL
INTO V_LID
FROM DUAL;
UPDATE CSCOMMON.SEQUENCING_PROCESS A
SET A.LOCK_ID = V_LID ,
A.STATUS = 1,
A.STARTED = SYSDATE,
A.WARNINGS = 0
WHERE NOT EXISTS
(SELECT 1
FROM CSCOMMON.SEQUENCING_PROCESS B
WHERE ( (A.RECEIVER_ID = B.RECEIVER_ID
AND A.RECEIVER_SEQ = 1)
OR (A.PROCESS_ID = B.PROCESS_ID
AND A.PROCESS_SEQ = 1)
OR (A.DOCUMENTTYPE_ID = B.DOCUMENTTYPE_ID
AND A.DOCUMENTTYPE_SEQ = 1))
AND (A.ERROR_HANDLING = 0 OR B.STATUS != 4)
AND B.RECORD_ID < A.RECORD_ID)
AND A.STATUS = 2
AND 1024 =
(SELECT WM1.STATUS
FROM WMLOG610.WMPROCESS WM1,
( SELECT MAX (AUDITTIMESTAMP) AUDITTIMESTAMP,
INSTANCEID
FROM WMLOG610.WMPROCESS WM2
WHERE INSTANCEID IN
(SELECT INSTANCE_ID
FROM CSCOMMON.SEQUENCING_PROCESS where rownum<101)
GROUP BY INSTANCEID
ORDER BY instanceid) WM2
WHERE A.INSTANCE_ID = WM1.INSTANCEID
AND WM1.INSTANCEID = WM2.INSTANCEID
AND WM1.AUDITTIMESTAMP = WM2.AUDITTIMESTAMP
AND ROWNUM = 1)
AND A.LOCK_ID IS NULL
AND A.DOCUMENTTYPE_NAME != 'FxHaulage';
commit;
FETCH c_first500
INTO V_RECORD_ID,
V_RECEIVED,
V_PROCESS_NAME,
V_PROCESS_ID,
V_PROCESS_SEQ,
V_RECEIVER,
V_RECEIVER_ID,
V_RECEIVER_SEQ,
V_SENDER,
V_SENDER_ID,
V_MESSAGE_ID,
V_INSTANCE_ID,
V_STATUS,
V_STEP_ID,
V_INTERNAL_ID,
V_LOCK_ID,
V_ERROR_HANDLING,
V_STARTED,
V_WARNINGS,
V_DOCUMENTTYPE_NAME,
V_DOCUMENTTYPE_ID,
V_DOCUMENTTYPE_SEQ;
EXIT WHEN c_first500%NOTFOUND;
BEGIN
v_current := 'INSERT INTO POST_SEQUENCING_PROCESS';
IF (lv_count = 0)
THEN
INSERT INTO POST_SEQUENCING_PROCESS (RECORD_ID,
RECEIVED,
PROCESS_NAME,
PROCESS_ID,
PROCESS_SEQ,
RECEIVER,
RECEIVER_ID,
RECEIVER_SEQ,
SENDER,
SENDER_ID,
MESSAGE_ID,
INSTANCE_ID,
STATUS,
STEP_ID,
INTERNAL_ID,
LOCK_ID,
ERROR_HANDLING,
STARTED,
WARNINGS,
DOCUMENTTYPE_NAME,
DOCUMENTTYPE_ID,
DOCUMENTTYPE_SEQ)
SELECT *
FROM cscommon.sequencing_process A
WHERE lock_id IS NOT NULL
AND A.DOCUMENTTYPE_NAME != 'FxHaulage' order by lock_id;
commit;
INSERT INTO CSCOMMON.PRE_SEQUENCING_PROCESS
(SELECT * FROM CSCOMMON.POST_SEQUENCING_PROCESS);
commit;
DELETE FROM CSCOMMON.POST_SEQUENCING_PROCESS;
COMMIT;
v_current := 'DELETE FROM SEQUENCING_PROCESS';
DELETE FROM CSCOMMON.SEQUENCING_PROCESS
WHERE LOCK_ID IS NOT NULL
AND DOCUMENTTYPE_NAME != 'FxHaulage';
COMMIT;
ELSE
RETURN;
END IF;
END;
END LOOP;
CLOSE c_first500;
COMMIT;
EXCEPTION
WHEN OTHERS
THEN
v_sql_error := SQLERRM || ' - ' || v_current;
ROLLBACK;
END;
/May be by using forall /bulk collections
Thanks
RajYou need to understand transactional consistency. Not only are your commits
slowing things down, they are not good for maintaining transactional consistency.
Ask yourself what would happen if there was a problem in your procedure after
the first commit? How would you recover from that with some records
updated but the rest of your procedure not having been run?
In general you should only have one commit at the topmost level. By that I mean if
there is a program that kicks of other ones and is the 'master' controller, that
should be the one that decides to commit or rollback the whole transaction.
Also you need to understand exception handling. Your exception processing is dangeroulsly wrong.
Remove it.
Finally, try and do this processing without using cursor loops: pure (set-based) SQL is much faster than
slow cursor based PL/SQL and SQL together. -
Sample plsql code needed.
I am a beginner in plsql programming . I need to dump all data from EMP table to EMP1 by using cursor.
Can anybody help?I am a beginner in plsql programming.I would first learn all there is to learn about SQL, nowadays...
Cursor based row-by-row processed = slow-by-slow.
http://tkyte.blogspot.com/2006/10/slow-by-slow.html
Doing it set-based, should be the way to go, it takes only one line of code, one single SQL statement:
SQL> create table emp1 as select * from emp;Cursor examples can be found in the Oracle documentation @ http://tahiti.oracle.com
For example, have a look in the PL/SQL User's Guide and Reference @ http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/toc.htm
Or here: http://download.oracle.com/docs/cd/B10500_01/appdev.920/a96624/a_samps.htm
Edited by: hoek on May 8, 2010 6:08 PM -
Slow performance when using cursor with bind variable
i'm facing the problem mentioned in the subject.
whenever i use the bind variable it would take more than 5mins to fetch 157 records, but if i hardcode the value ( not using variable ) it would take only 10sec to fetch 157 records.
can anyone give me some guide to solve this problem? thank you..
Code :
DECLARE
cursor cur1(l_startdate IN varchar2,l_enddate IN varchar2) IS
select * from shipment ship where ship.insertion_date >= to_date(l_startdate,'DD-MM-YYYY HH24:MI:SS') and ship.insertion_date < to_date(l_enddate ,'DD-MM-YYYY HH24:MI:SS')
TYPE shipment_aat IS TABLE OF cur1%ROWTYPE INDEX BY PLS_INTEGER;
l_shpt shipment_aat;
limit_in INTEGER := 100;
BEGIN
v_startdate := '10-06-2008 14:00:00';
v_enddate := '10-06-2008 17:00:00';
OPEN C_shpt(v_startdate,v_enddate);
LOOP --start shipment loop
FETCH C_shpt BULK COLLECT INTO l_shpt LIMIT limit_in;
FOR indx IN 1 .. l_shpt.COUNT
LOOP
DBMS_OUTPUT.PUT_LINE('l_shpt value ' || l_shpt(indx).ship_number || '/' || l_shpt(indx).insertion_date);
END LOOP;
EXIT WHEN l_shpt.COUNT < limit_in;
END LOOP; -- end of shipment loop
CLOSE cur1;
END;When your query takes too long ...
-
[b]Tutorial:[/b] Simplify Developing OLE Automation Code Using VBA
INTRODUCTION
Automating Office applications from Oracle Forms can be a tedious, frustrating, and time-consuming process. Because the OLE2 and CLIENT_OLE2 built-ins do not validate the automation commands that they relay, code that compiles without errors often dies at runtime with a not-so-helpful error code. This tutorial will demonstrate how to simplify the development of automation code using a tool that ships with all Microsoft Office editions -- the Visual Basic for Applications (VBA) IDE.
The VBA IDE, a core Office component, is a full-fledged development environment featuring code completion, basic syntax highlighting, context-driven help and a runtime debugger. Its Object Browser provides a convenient means of browsing the Word object model, as well as searching by keyword.
For those who may not interested in following this tutorial in detail, I would like to stress the usefulness of the Object Browser as a tool for inspecting the functions supported by OLE server applications and, perhaps more importantly, valid values for function arguments. Whether/not anyone buys the assertion that starting with VBA prototypes is far more productive than pounding out OLE2 code from the very start, they will find the Object Browser invaluable as a reference -- I rely on it exclusively for this sort of documentation.
A BRIEF INTRODUCTION TO THE VBA IDE & THE OBJECT BROWSER UTILITY
Try this:
1. Open Word
2. Launch the VBA IDE by pressing <Alt><F11>
3. Open the Object Browser by pressing <F2>
The Object Browser allows you to visually navigate Word's class hierarchy. Its user interface is a bit crowded, so controls are unlabeled. Hovering the mouse cursor above a control will display a tooltip explaining that control's purpose. The browser's scope can be narrowed by using the Project/Library combo. Typing a keyword or substring in the Search Text combo and clicking on the Search button will cause all classes/members whose name contains the specified search text to be listed in the Search Results pane. Selecting an item from this list will update the two panes below it, showing the selected class, and its members. Beneath the Classes and Members panes is an untitled pane, gray in color, which displays details for the selected class/member, including hyperlinks to relevant information such as arguments, their types and allowable values. If Visual Basic Help is installed, pressing <F1> will display help on a selected class/member. (This feature can be installed from your Office install CD, if necessary.)
NOTE: While it is possible to cut-and-paste the code examples that follow, I highly recommend that they be typed in by hand. Doing so will provide a better understanding of how the IDE's code completion behaves. Use code completion most efficiently by not using the mouse or <Enter> key when selecting from completion lists. Instead, just type enough letters to select the desired list element, then continue along as if you had typed the entire element, typing the next operator in your statement. It really is slick!
HELLO WORLD - VBA-STYLE
1. Open Word
2. Launch the VBA IDE by pressing <Alt><F11>
3. Select Module from the Insert menu.
4. In the blank area that appears, enter the following code:
Public Sub HelloWorld()
Documents.Add
Selection.TypeText ("Hello, world!")
End Sub5. Press <F5> to run the code.
If you switch back to Word by pressing <Alt><F11>, there should appear a newly-created document containing the text Hello, world!.
A MORE AMBITIOUS EXAMPLE
In this example, we will launch Word, type some text, and alter its formatting. For the purposes of this tutorial, consider it the process we wish to automate from within Forms.
1. If Word is running, close it.
2. Open any Office application except Word, such as Excel, Outlook or PowerPoint
3. Launch the VBA IDE by pressing <Alt><F11>.
4. Select References from the Tools menu -- a dialog should pop up.
5. From within this dialog, locate and select Microsoft Word <version> Object Library, then click OK.
6. Select Module from the Insert menu.
7. In the blank area that appears, enter the following code:
Public Sub LaunchWord()
Dim app As Word.Application
Set app = CreateObject("Word.Application")
app.Visible = True '!!! IMPORTANT !!!
app.Documents.Add
With app.Selection
.TypeText "This is paragraph 1."
.TypeParagraph
.TypeText "This is paragraph 2."
.TypeParagraph
.TypeText "This is paragraph 3."
End With
With ActiveDocument
.Paragraphs(1).Range.Words(3).Bold = True
.Paragraphs(2).Range.Words(3).Italic = True
.Paragraphs(3).Range.Words(3).Underline = True
End With
End Sub8. Press <F5> to run the code.
A new Word session should have been launched. Switch to it, to view the results of our handiwork!
TAILORING VBA CODE INTENDED FOR OLE2 CONVERSION
Now, things get a bit uglier. The code listed above gives a good idea of how concise VBA code can be, but With blocks and chained object references do not translate readily into OLE2 code. Here's the same process, rewritten in a more OLE2-friendly style. Note the numerous intermediate object references that have been declared.
Public Sub LaunchWord()
Dim app As Word.Application
Dim doc As Word.Document
Dim docs As Word.Documents
Dim pars As Word.Paragraphs
Dim par As Word.Paragraph
Dim wrds As Word.Words
Dim sel As Word.Selection
Dim rng As Word.Range
Set app = CreateObject("Word.Application")
app.Visible = True '!!! IMPORTANT !!!
Set doc = app.Documents.Add
Set sel = app.Selection
sel.TypeText "This is paragraph 1."
sel.TypeParagraph
sel.TypeText "This is paragraph 2."
sel.TypeParagraph
sel.TypeText "This is paragraph 3."
Set pars = doc.Paragraphs
'select third word of first paragraph and make it bold
Set par = pars.Item(1)
Set rng = par.Range
Set wrds = rng.Words
Set rng = wrds.Item(3)
rng.Bold = True
'select third word of second paragraph and italicize it
Set par = pars.Item(2)
Set rng = par.Range
Set wrds = rng.Words
Set rng = wrds.Item(3)
rng.Italic = True
'select third word of second paragraph and underline it
Set par = pars.Item(3)
Set rng = par.Range
Set wrds = rng.Words
Set rng = wrds.Item(3)
rng.Underline = True
End Sub
TRANSFORMATION: CONVERTING VBA CODE INTO PL/SQL
Here is the PL/SQL counterpart to our previous VBA routine. Compare printouts of the two and note their similarities. Notice the need for argument lists -- this causes the code to fluff up quite a bit, and really interferes with readability.
PROCEDURE LAUNCH_WORD IS
v_app OLE2.OBJ_TYPE; -- Application
v_doc OLE2.OBJ_TYPE; -- Document
v_docs OLE2.OBJ_TYPE; -- Documents collection
v_pars OLE2.OBJ_TYPE; -- Paragraphs collection
v_par OLE2.OBJ_TYPE; -- Paragraph
v_wrds OLE2.OBJ_TYPE; -- Words collection
v_sel OLE2.OBJ_TYPE; -- Selection
v_rng OLE2.OBJ_TYPE; -- Range
v_args OLE2.LIST_TYPE; -- OLE2 argument list
BEGIN
/* launch Word and MAKE IT VISIBLE!!! */
v_app := OLE2.CREATE_OBJ('Word.Application');
OLE2.SET_PROPERTY(v_app, 'Visible', TRUE);
/* initialize key object references */
v_docs := OLE2.GET_OBJ_PROPERTY(v_app, 'Documents');
v_doc := OLE2.INVOKE_OBJ(v_docs, 'Add');
v_sel := OLE2.GET_OBJ_PROPERTY(v_app, 'Selection');
/* type first paragraph */
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, 'This is paragraph 1.');
OLE2.INVOKE(v_sel, 'TypeText', v_args);
OLE2.DESTROY_ARGLIST(v_args);
OLE2.INVOKE(v_sel, 'TypeParagraph');
/* type second paragraph */
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, 'This is paragraph 2.');
OLE2.INVOKE(v_sel, 'TypeText', v_args);
OLE2.DESTROY_ARGLIST(v_args);
OLE2.INVOKE(v_sel, 'TypeParagraph');
/* type third paragraph */
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, 'This is paragraph 3.');
OLE2.INVOKE(v_sel, 'TypeText', v_args);
OLE2.DESTROY_ARGLIST(v_args);
/* set reference to Paragraphs collection */
v_pars := OLE2.GET_OBJ_PROPERTY(v_doc, 'Paragraphs');
/* select third word of first paragraph and make it bold */
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, 1);
v_par := OLE2.INVOKE_OBJ(v_pars, 'Item', v_args);
OLE2.DESTROY_ARGLIST(v_args);
v_rng := OLE2.GET_OBJ_PROPERTY(v_par, 'Range');
v_wrds := OLE2.GET_OBJ_PROPERTY(v_rng, 'Words');
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, 3);
v_rng := OLE2.INVOKE_OBJ(v_wrds, 'Item', v_args);
OLE2.SET_PROPERTY(v_rng, 'Bold', TRUE);
/* select third word of second paragraph and italicize it */
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, 2);
v_par := OLE2.INVOKE_OBJ(v_pars, 'Item', v_args);
OLE2.DESTROY_ARGLIST(v_args);
v_rng := OLE2.GET_OBJ_PROPERTY(v_par, 'Range');
v_wrds := OLE2.GET_OBJ_PROPERTY(v_rng, 'Words');
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, 3);
v_rng := OLE2.INVOKE_OBJ(v_wrds, 'Item', v_args);
OLE2.SET_PROPERTY(v_rng, 'Italic', TRUE);
/* select third word of second paragraph and underline it */
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, 3);
v_par := OLE2.INVOKE_OBJ(v_pars, 'Item', v_args);
OLE2.DESTROY_ARGLIST(v_args);
v_rng := OLE2.GET_OBJ_PROPERTY(v_par, 'Range');
v_wrds := OLE2.GET_OBJ_PROPERTY(v_rng, 'Words');
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, 3);
v_rng := OLE2.INVOKE_OBJ(v_wrds, 'Item', v_args);
OLE2.SET_PROPERTY(v_rng, 'Underline', TRUE);
END;
REFACTORING FOR REUSABILITY AND READABILITY
While the previous procedure runs without errors, it suffers from poor readability which, in turn, makes it difficult to maintain. Here, we address those issues by moving repetetive low-level operations into separate procedures.
PROCEDURE LAUNCH_WORD IS
v_app OLE2.OBJ_TYPE; -- Application
v_doc OLE2.OBJ_TYPE; -- Document
v_docs OLE2.OBJ_TYPE; -- Documents collection
v_sel OLE2.OBJ_TYPE; -- Selection
v_args OLE2.LIST_TYPE; -- OLE2 argument list
BEGIN
/* launch Word and MAKE IT VISIBLE!!! */
v_app := OLE2.CREATE_OBJ('Word.Application');
OLE2.SET_PROPERTY(v_app, 'Visible', TRUE);
/* create a new Word document */
v_docs := OLE2.GET_OBJ_PROPERTY(v_app, 'Documents');
v_doc := OLE2.INVOKE_OBJ(v_docs, 'Add');
v_sel := OLE2.GET_OBJ_PROPERTY(v_app, 'Selection');
/* add a few paragraphs */
PRINT_PARAGRAPH(v_sel, 'This is paragraph 1.');
PRINT_PARAGRAPH(v_sel, 'This is paragraph 2.');
PRINT_PARAGRAPH(v_sel, 'This is paragraph 3.');
/* apply formatting */
APPLY_FORMATTING(v_doc, 1, 3, 'Bold', TRUE);
APPLY_FORMATTING(v_doc, 2, 3, 'Italic', TRUE);
APPLY_FORMATTING(v_doc, 3, 3, 'Underline', TRUE);
END;
PROCEDURE APPLY_FORMATTING(
v_doc OLE2.OBJ_TYPE,
v_paragraph_num NUMBER,
v_word_num NUMBER,
v_attribute VARCHAR2,
v_value BOOLEAN) IS
v_pars OLE2.OBJ_TYPE; -- Paragraphs collection
v_par OLE2.OBJ_TYPE; -- Paragraph
v_wrds OLE2.OBJ_TYPE; -- Words collection
v_rng OLE2.OBJ_TYPE; -- Range
v_args OLE2.LIST_TYPE; -- OLE2 argument list
BEGIN
/* set reference to Paragraphs collection */
v_pars := OLE2.GET_OBJ_PROPERTY(v_doc, 'Paragraphs');
/* get specified paragraph */
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, v_paragraph_num);
v_par := OLE2.INVOKE_OBJ(v_pars, 'Item', v_args);
OLE2.DESTROY_ARGLIST(v_args);
/* get words for specified paragraph */
v_rng := OLE2.GET_OBJ_PROPERTY(v_par, 'Range');
v_wrds := OLE2.GET_OBJ_PROPERTY(v_rng, 'Words');
/* apply formatting to word found at specified index */
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, v_word_num);
v_rng := OLE2.INVOKE_OBJ(v_wrds, 'Item', v_args);
OLE2.SET_PROPERTY(v_rng, v_attribute, v_value);
END;
PROCEDURE PRINT_PARAGRAPH(v_sel OLE2.OBJ_TYPE, v_text VARCHAR2) IS
v_args OLE2.LIST_TYPE;
BEGIN
v_args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(v_args, v_text);
OLE2.INVOKE(v_sel, 'TypeText', v_args);
OLE2.DESTROY_ARGLIST(v_args);
OLE2.INVOKE(v_sel, 'TypeParagraph');
END;
CONCLUSION
It is my hope that this tutorial, despite it's introductory nature, has demonstrated the value of the VBA IDE, the ease with which automation processes can be prototyped using VBA, the noticeable similarity between VBA automation routines and their Forms PL/SQL counterparts, and the advantages of testing automation processes within the VBA IDE. Please feel free to follow up with any specific questions or concerns you may have.
Thanks,
Eric Adamson
Lansing, Michigan
FINAL NOTE: These examples use the OLE2 built-in, and will operate correctly when called from forms running in the Form Builder OC4J. Deploying them to an Oracle Application Server will launch Word on the server itself (if available), which is usually not the developer's intent! Automating Word client-side via web forms requires adding WebUtil support. Adapting the code for WebUtil is trivial -- just replace all instances of OLE2 with CLIENT_OLE2. Adapting forms for WebUtil and configuring OLE support into your Oracle Application Server, however, are beyond the scope of this tutorial.
REVISION HISTORY
This promises to be something of a 'living document'. I've snuck changes through without comment in the past, but in the future, I'll try to document significant changes here.
2006-08-21
* Prefaced boring subject line with text: 'Tutorial:' to clarify purpose
* Added emphasis on value of Object Browser as a referenceThanks James, for your kind words. I do hope this information will help folks out. I honestly believe that tinkering around in the VBA IDE will prove highly gratifying for automation developers. It can be assured that learning to make Word jump through hoops is much more straight-forward in this environment. I'm not one for mottos, but if I were pressed for a cheesy motto, I would say: First, make it work. Then, make it work in Oracle!
Once the idea has sunk in, that Visual Basic routines for automating Word are exact analogs to their OLE2 counterparts, we can remove keywords like Oracle and PL/SQL from our Google searches on Word automation which, at least in this context, are the proverbial kiss of death. Suddenly we find ourselves liberated by the possibility of steal-, ahem... borrowing ideas from the Visual Basic* community!
As for links, my link of choice is invariably http://groups.google.com -- if you don't already use it at least ten times a day, you must try it. This is the venerable USENET archive, including the holdings of now-extinct DejaNews. Another possible site of interest is http://word.mvps.org/FAQs/MacrosVBA, which may serve as a good starting point for those who wish to learn how to do fancy tricks with Word using VBA.
If these links don't prove immediately helpful, please feel free to give specifics on the sort of operations you are interested in automating, and I'll see if I can post an example that addresses it.
Regards,
Eric Adamson
Lansing, Michigan
PS: I do hope, as people read my posts, with every other acronym being VBA, that they are not mistakenly hearing a call to learn Visual Basic. I say this, not because I believe learning VB would be a Bad Thing, but because I assume that few of us feel we have the time to learn a new programming language. Despite having come to the Oracle camp already knowing VB/VBA, and having acquired a fair bit of experience with automating Office applications as an Access developer, I remain confident that what I am suggesting people attempt does not rise to the level of learning a language. What I am suggesting is that they learn enough of the language to get by.
*VB vs. VBA
Just a quick word on this, as readers may wonder why I seem to use these terms interchangeably. Visual Basic (VB) can refer to either a development platform or a programming language. Visual Basic for Applications (VBA) is a language -- more precisely, it is a subset of the Visual Basic language. One purchases VB, usually quite intentionally. VBA is included with Microsoft Office, as is VBA's development environment, the VBA IDE. The key distinction between VB and VBA is that VBA cannot be used to create self-contained executables. Rather, VBA relies on VBA-enabled applications, such as Microsoft Office applications, to serve as a container for VBA code, and to provide a runtime environment for that code. For the purposes of discussing OLE Automation, VB and VBA are quite interchangeable. -
Loading data from one table to another using cursor
Hi,
I have given the below command to load the data from 1 table to another using cursor.
declare
cursor mycursor IS
SELECT extract_name,from_date,to_date,BETA from temp_table where EXTRACT_NAME='GIFTCARD_DETAILS';
Begin
for mycursor_1 IN mycursor loop
insert into tmp_tab columns(col1,col2,col3,col5) values(mycursor_1.EXTRACT_NAME,mycursor_1.from_date,mycursor_1.to_date,mycursor_1.BETA);
End loop;
commit;
end;
It is working fine.
But I want to hard code some of the columns ( like flags ) which are not there in 1st table and load them into 2nd table.
In db2 we will give commands like
varSqlStatus=`db2 "declare mycurs cursor for select extract_name,from_date,to_date,BETA,'N','Y' from temp_table"`
varSqlStatus=`db2 "load from mycurs of cursor modified by identityignore insert into tmp_tab(col1,col2,col3,col5,col6,col7) nonrecoverable"`
But I want it in oracle 10g, Can any one help me in this.Have you tried either of the two options :
1. Modify the CURSOR itself :
cursor mycursor IS
SELECT extract_name,from_date,to_date,BETA,'N','Y' from temp_table where EXTRACT_NAME='GIFTCARD_DETAILS';2. Modify the INSERT statement itself :
insert into tmp_tab columns(col1,col2,col3,col5,col6,col7) values(mycursor_1.EXTRACT_NAME,mycursor_1.from_date,mycursor_1.to_date,mycursor_1.BETA,'N','Y'); -
How to write a file in unix server through oracle plsql code
Hi All,
My requirement is to create and write a file (any file for eg txt file) in unix box with in a specified directory through oracle plsql code.
Oracle sits in windows server.
using utl_file package we can create directory where oracle resides and write it there in oracle server in our case windows..
But here we need to create,write a file but in unix server which is different server than where the oracle server resides..
we are using Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
PL/SQL Release 11.2.0.2.0 - Production
Can any one one please help me out in this issue...
Thanks in Advance.
PrakashMr Prakash,
Why are you asking this question multiple times in every forum you can spell?
Valid responses have been presented to you already two times.
Can you explain why you can't follow them up, but continue to abuse this forum by repeating doc questions?
Sybrand Bakker
Senior Oracle DBA -
How to manipulate data in multiple rows without using cursor??
Hi all,
I have a form in which there is a push button & 4 text fields.
Push button : Process
Text fields: Year, Month, Financial_To_Year, Financial_From_Date.
In database , there are tables like, CUSTOMER_MASTER, FD_ACCOUNT_MASTER, FD_ACCOUNT_DTL, CUSTOMER_YEARLY_INTEREST, etc.
In table FD_ACCOUNT_MASTER, there are columns, like CUST_CODE, FD_ACCT_NO, FD_AMOUNT, ACCT_OPEN_DT, ACCT_CLOSE_DATE, ACCT_TYPE, INTEREST_RATE, etc.
There are thousands of records in the table.
For Push button : Process , TRIGGER: When button pressed,
I have to do all the process of FD for all the FD_ACCOUNTS at once. Process means i have to calculate Interest for all the accounts, calculate interest monthly, quarterly, yearly and make the FD_Accounts disable after the date of ACCT_CLOSE_DATE is reached, make the accounts renewed , etc all the process.
But to do this process for multiple rows at once, we use cursor, but i don't want to use cursor as i feel its too tedious to do.
Is there any other way , where i do process of multiple records at once without using cursor??
Help me, Thank You.
Oracle Forms Builder 6i.
Oracle9i Enterprise Edition Release 9.2.0.1.0 - ProductionAn Update statement certainly can update sets of data instead single row updates:
UPDATE Statement
if you can't do it in a single statement you can use bulk processing as well:
PLSQL 101
cheers -
Displaying Images in a Report or in PLSQL Code
Hi all,
I have a products catelog in an items table (item_id, item_name, item_image (blob)). I want to display it in a table form but Reports in Portal30 do not allow images.
I can write simple PLSQL code to display table contents in tabular form (using htp, htp packages) but I could not find any procedure/function to display image stored in a db table to an HTML table.
I shall be grateful for any help or hint regarding this. You can mail me directly if you like.Armaghan
This question is best asked in the Oracle9iAS Portal Applications Forum.
Maybe you are looking for
-
It had worked fine for me until Firefox 22.0, I believe.
-
Can't update to the new OSX ML
That's the message that pops up: "There was an eror eith the app store, please try again later". It says that for already 2 weeks.
-
Performance problem during commit
hi, i register 5000 objects in a UnitOfWork. only a small number of objects changed. when commit the UnitOfWork i'm waiting over 10 seconds before the commit end. what can i do to increase the commit performance thanks
-
HT203164 what is gracenotes and how do i get rid of it it seems to stop me doenloading
when trying to download a c/d gracenotes comes on my top bar this seems to slow down my downloads what purpose does it serve and how do i get rid of it
-
My earlier post was answered by Frank Kulash, thanks Frank. However i have few questions SELECT owner_id , owner_name AS old_owner_name , REGEXP_SUBSTR ( owner_name , '^\(([^)]+)' , 1 , 1