Listing

AskTom Home
ViewForPrinting
Home
Recent Archives Advanced Search FAQ by Category Most Popular Hot Articles Your Questions [ Listing ]
Subject | Article | Last Updated (East coast time)
How can I copy a file that is located on an NT box to another NT box | article only | May 02, 2000 01:25 pm
Is there anyway to kill the users who are idle | article only | May 02, 2000 01:31 pm
How to commit in a trigger | article only | May 02, 2000 01:32 pm
How to get all granted privileges for any specific user | article only | May 02, 2000 01:39 pm
Random Numbers | article only | May 02, 2000 01:40 pm
How do I calculate the time taken by an sql statement | article only | May 02, 2000 02:26 pm
Auditing the number of rows deleted with a trigger. | article only | May 02, 2000 02:27 pm
Uploading a file with OAS | article only | May 02, 2000 02:27 pm
Wedb -- display a default date for a date field | article only | May 02, 2000 02:30 pm
Can I Assign return value of Stored Function to DEFINE in SQL Script. | article only | May 02, 2000 02:31 pm
what is maximum row size in Oracle table | article only | May 02, 2000 02:36 pm
Installer Y2k issue | article only | May 02, 2000 02:36 pm
Why doesn't revoke connect drop the user | article only | May 02, 2000 02:41 pm
Subquery in inserts? | article only | May 02, 2000 02:43 pm
Initialize varray easily. | article only | May 02, 2000 02:48 pm
Is it possible to run programs such as SAS and Microsoft Excel from Oracle Forms? | article only | May 02, 2000 02:52 pm
Trigger processing question | article only | May 02, 2000 02:53 pm
Start spooling from sqlplus login/glogin file | article only | May 02, 2000 02:53 pm
tracing failures of jobs run via dbms_job | article only | May 02, 2000 02:56 pm
Deleting from a joined view | article only | May 02, 2000 02:59 pm
how to resize redo log files. | article only | May 02, 2000 03:00 pm
Howto Standby Database in 7.3 | article only | May 02, 2000 04:00 pm
how to do "Where column = bind_variable" and bind_variable might be NULL | article only | May 04, 2000 10:43 am
Is there a way to store Seagate Crystal Reports in Oracle | article only | May 04, 2000 11:09 am
Can I rename a column? | article only | May 04, 2000 11:11 am
Where are utloidxs.sql and utldidxs.sql? | article only | May 04, 2000 11:20 am
Will installing 8.1.5 context cartrage work in 8.0.4 database? | article only | May 04, 2000 01:26 pm
Using bind variables in DDL | article only | May 04, 2000 01:34 pm
Question about parameterized view | article only | May 04, 2000 01:42 pm
Can resize both expand and shrink a file? | article only | May 04, 2000 01:43 pm
Getting the difference between dates in seconds. | article only | May 04, 2000 01:44 pm
complex decode | article only | May 04, 2000 01:45 pm
Generic "file open" dialog in forms | article only | May 04, 2000 01:56 pm
blocks column in dba_tables | article only | May 04, 2000 02:12 pm
How long has a query/statement been running | article only | May 04, 2000 02:14 pm
Update Cascade | article only | May 04, 2000 02:14 pm
Can I install ORACLE 8.0.5 on Windows 2000? | article only | May 04, 2000 02:21 pm
RE: Ask Tom Submission | article only | May 04, 2000 02:37 pm
finding the size in bytes of an index | article only | May 04, 2000 02:41 pm
what is a meaning of 'WEB ENABLED APPLICATION' | article only | May 04, 2000 02:51 pm
can i hardcode username/password into a form | article only | May 04, 2000 02:51 pm
controlling commit/rollback in a disibuted transaction | article only | May 04, 2000 03:02 pm
Can I do mutlithreaded programming in PLSQL | article only | May 04, 2000 03:04 pm
utl_file question | article only | May 05, 2000 09:30 am
composite primary key | article only | May 05, 2000 09:32 am
Update cascade | article only | May 05, 2000 09:38 am
Max identifier width. | article only | May 05, 2000 09:39 am
generating create index statements from data dictionary when using function based indexes. | article only | May 05, 2000 09:40 am
"base 26" | article only | May 05, 2000 09:41 am
Detect Duplicate records in a Pl/sql table | article only | May 05, 2000 10:34 am
select multiple items in forms 4.5 LOVS | article only | May 05, 2000 10:37 am
using the SYSTEM account | article only | May 05, 2000 10:38 am
blank pages from OAS PLSQL cartridge. | article only | May 05, 2000 10:43 am
Product_user_profile question | article only | May 05, 2000 10:44 am
deleting duplicate rows | article only | May 05, 2000 10:46 am
changing the default date format. | article only | May 05, 2000 10:47 am
Hit counter in plsql cartridge | article only | May 05, 2000 12:39 pm
foreign keys and indexes | article only | May 05, 2000 12:41 pm
shoud I use char or varchar2 | article only | May 05, 2000 12:41 pm
In Oracle Designer 2000 how can I attach the menu of my choice | article only | May 05, 2000 12:44 pm
RE: Ask Tom Submission | article only | May 05, 2000 12:45 pm
free space in database | article only | May 05, 2000 12:47 pm
String concatenation | article only | May 05, 2000 12:48 pm
how long as someone been idle | article only | May 05, 2000 12:50 pm
starting database from comand line in NT | article only | May 05, 2000 01:28 pm
Can I get the dependency and hierarchy of calling procedures | article only | May 05, 2000 01:31 pm
how to attach a help file typed in MS word to any key/button in forms | article only | May 05, 2000 01:36 pm
How can I trap the oracle errors from csh | article only | May 05, 2000 01:37 pm
disable redo | article only | May 05, 2000 01:37 pm
running sql.bsq two times. | article only | May 05, 2000 01:38 pm
grouping by WEEK | article only | May 05, 2000 03:20 pm
using dbms_lob.read and write | article only | May 05, 2000 03:33 pm
sqlldr and loading date/time | article only | May 05, 2000 03:38 pm
copy passwords from one instance to another | article only | May 05, 2000 03:39 pm
how to determine what columns are modified in a trigger. | article only | May 05, 2000 03:40 pm
passing a plsql table over a database link | article only | May 05, 2000 03:41 pm
using & in sqlplus | article only | May 05, 2000 03:48 pm
begintrans/commitrans and autocommit | article only | May 05, 2000 03:49 pm
OAS / Oracle8i questions | article only | May 05, 2000 03:50 pm
extracting DDL from a dmp file | article only | May 05, 2000 03:53 pm
dynamically execute a procedure | article only | May 05, 2000 03:57 pm
extracting to ascii delimited files | article only | May 05, 2000 04:00 pm
calling a procedure with an output type of PLSQL table | article only | May 05, 2000 04:01 pm
connecting as another user without their password | article only | May 05, 2000 04:03 pm
about mutating tables. | article only | May 05, 2000 04:04 pm
adding time to a date | article only | May 05, 2000 04:13 pm
row(s) 1 - 86 of 86
May 02, 2000 Florence -- Thanks for the question regarding "How can I copy a file that is located on an NT box to another NT box ", version
You Asked
How can I copy a file that is located on an NT box to
another NT box by calling a package/function located in an
Oracle8 database on Unix?
and we said...
I can only see doing this if you are running something like Samba on UNIX (or
unix services for NT) and have mounted the 2 NT boxes to the unix machine so
their file systems look like unix file systems.

Then, you could

o use something like UTL_FILE to read from one and write to the other.
o Or an external procedure written in C to do a binary copy.
o Or a java stored procedure to do the same.
May 02, 2000 Gopesh -- Thanks for the question regarding "Is there anyway to kill the users who are idle ", version
You Asked
Dear TOM,
Hi

Is there anyway to kill the users who are idle for more than six
hrs.

Regards
Gopesh
and we said...
You can use profiles (see concepts and admin guide) or you can
use dbms_jobs to look for and kill sessions on a recurring
basis.  Profiles have the downside that they will send a kill to
the client and wait for the client to acknowledge -- so the
sessions will tend to stay in the database until the client does
something in the database -- discovers it was killed and then
goes away.

To use dbms_jobs and plsql for example, if you use the
last_call_et column in v$session for INACTIVE sessions, you can
find all users inactive for 6 hours of more:

  1  select 'alter system kill session ''' || sid || ',' ||
serial# || '''; /* ' || username || ' */'
  2  from v$session where username is not null
  3  and status = 'INACTIVE'
  4* and last_call_et/60/60 >= 6
ops$tkyte@8i> /

'ALTERSYSTEMKILLSESSION'''||SID||','||SERIAL#||''';/*'||USERNAME|
|'*/'
-----------------------------------------------------------------
-----------------------------------
alter system kill session '7,11639'; /* REVIEW */
alter system kill session '59,5939'; /* ATCDEMO */

If you use dbms_sql to dynamically execute SQL (make sure to
grant ALTER SYSTEM to the owner of the procedure, see
http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
for
the reason why), you could write a procedure that is run every N
minutes using dbms_jobs to kill these idle sessions.
May 02, 2000 Sabin -- Thanks for the question regarding "How to commit in a trigger", version
You Asked
I want to find out a way to commit the statements
passed in a trigger. i.e. Imagine through a trigger, i maybe
passing some update statements. These statements cannot be
committed by a trigger. Still, how do i commit them through a
trigger
and we said...

This can be done only in Oracle8i, release 8.1 and up.

The feature is called an autonomous transaction.  See
http://osi.oracle.com/~tkyte/autonomous/index.html
for
more info on that feature.

Prior to that, all statements executed by the trigger are under
the transactional control of the initiating event.  They cannot
be committed or rolled back independently of the parent
transaction.
May 02, 2000 san -- Thanks for the question regarding "How to get all granted privileges for any specific user", version
You Asked
Tom:
I am using Oracle 8i on NT as well on UNIX. Could you please
tell
me how I can get information about all granted privileges
(objects and system both) for any specific users?

Regards,
San
and we said...
These 2 views give you that information:

ops$tkyte@8i> desc dba_tab_privs
 Name                                                  Null?
Type
 ----------------------------------------------------- --------
------------------------------------
 GRANTEE                                               NOT NULL
VARCHAR2(30)
 OWNER                                                 NOT NULL
VARCHAR2(30)
 TABLE_NAME                                            NOT NULL
VARCHAR2(30)
 GRANTOR                                               NOT NULL
VARCHAR2(30)
 PRIVILEGE                                             NOT NULL
VARCHAR2(40)
 GRANTABLE
VARCHAR2(3)

ops$tkyte@8i> desc dba_sys_privs
 Name                                                  Null?
Type
 ----------------------------------------------------- --------
------------------------------------
 GRANTEE                                               NOT NULL
VARCHAR2(30)
 PRIVILEGE                                             NOT NULL
VARCHAR2(40)
 ADMIN_OPTION
VARCHAR2(3)

ops$tkyte@8i>

tab privs give you object privs.
sys privs give you system privs.

where GRANTEE = <username> gives you the info for a specific
user.
May 02, 2000 Doug -- Thanks for the question regarding "Random Numbers", version
You Asked
I recall you once posted a pl/sql package that
generated a psuedorandom number series that persisted across
reboots and instance restarts.

Does this package still exist or has it been incorporated into
one of the 8.1.5 included packages ?
and we said...
There is no package that "generated a psuedorandom number series
that persisted across reboots and instance restarts" -- nothing
but data in a table survives a restart.

There are random number generators, see
http://osi.oracle.com/~tkyte/Misc/Random.html
for more info.
May 02, 2000 Shaji -- Thanks for the question regarding "How do I calculate the time taken by an sql statement ", version
You Asked
How do I calculate the time taken by an sql statement
to execute and is it possible to calculate the time taken by a
pl/sql block also?
and we said...
There are many ways to do this.

Perhaps the easiest, if you are just trying to get some timings,
is to use SQLPlus and "set timing on".  For example:

ops$tkyte@8i> set timing on
ops$tkyte@8i> select count(*) from all_objects;

  COUNT(*)
----------
     20438

Elapsed: 00:00:06.25

shows it took 6.25 seconds to execute that.  That works for SQL
and PLSQL.

A more detailed look at thing may be achieved with SQL_TRACE,
TIMED_STATISTICS and TKPROF.

see
http://technet.oracle.com/doc/server.815/a67775/ch14_str.htm#1018
for details on that.
May 02, 2000 Ramana -- Thanks for the question regarding "Auditing the number of rows deleted with a trigger.", version
You Asked
Hi,

I have a specific requirement for one of the members in our
development team.  The situation is whenever a "delete"
statement
is issued there should be a log that should store the info
sysdate and the number of rows deleted.  We are trying to do
this
while using a statement trigger..  But, unable to identify a way

to know the number of rows deleted in the trigger.

Any ideas?

Thanks in advance,
Ramana Damarla
and we said...
The statement triggers cannot do this as they do not know how
many rows have been deleted.  You can do something like:

create or replace package my_state_pkg
as
    emp_del_count number;
end;
/

create or replace trigger BEFORE delete on EMP
begin
  my_state_pkg.emp_del_count := 0;
end;

create or replace trigger AFTER DELETE on emp for each row
begin
  my_state_pkg.emp_del_count := my_state_pkg.emp_del_count+1;
end;

create or replace trigger AFTER delete on emp
begin
   insert into log table values ( sysdate, 'emp',
my_state_pkg.emp_del_count );
end;
May 02, 2000 Matias -- Thanks for the question regarding "Uploading a file with OAS", version
You Asked
How can I upload a file using HTTP, and save it in the
disk of OWS?
Exist any pl/sql script for this? Or only perl do it?
Can you give me any code?

Thank you and sorry for my bad english
I'm use OWS 3.0 and Win NT 4.0
and we said...
With OAS 3.x, your choices are limited.  In OAS4.x, they added
the ability for the native plsql cartridge to upload into the
DATABASE (not the file system, only the DATABASE).  In OAS3.x,
there is some free C code you can download that works just like
the plsql cartridge but lets you upload into the file system or
database.  See
http://osi.oracle.com/~tkyte/owarepl/doc/index.html
for more info.

You can write your own C code as well.
May 02, 2000 shiva -- Thanks for the question regarding "Wedb -- display a default date for a date field", version
You Asked
I am using Oracle Webdb 2.0

1.I want to display a default/current
date for date field,please give all the
statement.

2.How to rename and drop an existing site name?
and we said...
In the default value field, use the following

#sysdate  -- to show the current date
#to_char( sysdate, 'Month DD, YYYY' )  -- to format the date

There is no way to rename a site
There is no automated way to drop a site but the attached note
goes through the steps.

========================================
PURPOSE

This documentation contains the procedure necessary to delete a
WebDB site.
There is currently no Drop Site link on the Site Administration
page and
sites must be deleted manually via SQL*Plus.

SCOPE & APPLICATION

The information in this document targets WebDB users, site
administrators,
and support analysts.

In order to delete a WebDB site that was earlier created through
WebDB,
you must use SQL*Plus to connect to target WebDB database and to
manually delete the relevant schema objects and data items.

Three database schemas per site are created upon completion of
the site
installation procedure.

If the schema name chosen for the new WebDB site were MYSITE,
then the
relevant schemas would be:

    MYSITE
    MYSITE_PUBLIC
    MYSITE_ADMIN

These schemas and the data associated with them must be deleted
in
order to remove the site.

To drop websites created with WebDB's SiteBuilder, do the
following in SQL*Plus:

    1.  Log into SQL*Plus as user sys, with the appropriate
password
        (default password is change_on_install).

        For example: sqlplus sys/change_on_install

    2.  select username from all_users;

    3.  Look for the names of the sites you want to drop in the
list of users.
        For each <sitename>, you have the following users:
            <sitename>
            <sitename>_public
            <sitename>_admin

    4.  drop user <sitename> cascade; (This might take some
time, about 10
        minutes.)

    5.  drop user <sitename>_public cascade;

    6.  drop user <sitename>_admin cascade;

Repeat steps 3-6 for all the sites that you want to delete.

This drops your site, but leaves the link on the WebDB browser.
To drop the
link from the browser, you must run the following steps:

    1.  Log into SQL*Plus as the "webdb" user.

    2.  delete from wwv_modules$ where schema =
upper('<sitename>');
        (do this for each site you have dropped above)

    3.  commit;

This now drops the Site link from the WebDB browser.

This procedure removes the site from the database and also
removes the
site link from the WebDB browser.
Review & Followup
Rating: 4
Answer to my longtime question November 20, 2001
Reviewer: Kavitha from UK
Hi,

I kept wondering about default values. I tried $$DATE$$ and SYSDATE and all the
whole lot of things we use in Developer/2000 but nothing worked.

Now I know that # in front of them works. Thanks a lot for this!

May 02, 2000 Mukesk -- Thanks for the question regarding "Can I Assign return value of Stored Function to DEFINE in SQL Script.", version
You Asked
Can I Assign return value of Stored
Function to DEFINE in SQL Script.

For e:g
ret := my_fun(dummy)
DEFINE YYY = ret ?? Is it possible ?
Now in SQl Script I have to use this RET value  as the Value of
DEFINE .
and we said...
there are 2 ways to do this, both require you do something like:

ops$tkyte@8i> column x new_val my_x

that says "when I run a query that selects a column named X put
the value of the last row fetched into a define variable called
MY_X".

Now, if I have a function I can "select" (eg: it does not write
to the database state -- no inserts/updates/deletes) I can
simply:

ops$tkyte@8i> create or replace function foo( a in number )
return number
  2  as
  3  begin
  4          return a*2;
  5  end;
  6  /
Function created.

ops$tkyte@8i> select foo(10) X from dual;

         X
----------
        20

ops$tkyte@8i>
ops$tkyte@8i> select &my_x from dual;
old   1: select &my_x from dual
new   1: select         20 from dual

        20
----------
        20

select that function from dual to run it and get the value into
the define variable.  If I cannot select foo() from dual -- I
can still do this using a bind variable:

ops$tkyte@8i> variable bind_var number
ops$tkyte@8i> exec :bind_var := foo( 22 )

PL/SQL procedure successfully completed.

ops$tkyte@8i> select :bind_var X from dual;

         X
----------
        44

ops$tkyte@8i>
ops$tkyte@8i> select &my_x from dual;
old   1: select &my_x from dual
new   1: select         44 from dual

        44
----------
        44

So I can always select BIND_VARIABLE "X" from dual;  and that'll
do it for me.
May 02, 2000 Venku Reddy -- Thanks for the question regarding "what is maximum row size in Oracle table", version
You Asked
what is maximum row size in Oracle table?
and we said...
4,000 gigabytes.

(4 gigabytes/LOB, 1,000 lobs/table).

Just take the maximum VARCHAR2 size (4000) and/or CHAR size
(2000) and add them up.

4000x1000 = 4,000,000 bytes of structured data.

Thats in Oracle8.0 and up.

In 7.x its

254 columns/table
varchar2 = max 2000 bytes

so about 508,000 bytes structured.

1 long per table at 2 gigabytes.
May 02, 2000 Matt -- Thanks for the question regarding "Installer Y2k issue", version
You Asked
I encountered problems while trying to uninstall Oracle
software using the Install program.  I was told that the
problems
were due to a Y2K bug that Oracle has a patch for.  So far, I
haven't found the patch.  Can you help me locate it?
and we said...

From
http://metalink.oracle.com/
Win32 Oracle Installer Y2K Fix
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Versions Affected
~~~~~~~~~~~~~~~~~
  Product & Oracle versions affected
  Oracle Installer for Win32 v3.3.1.1.0 and lower

 This Oracle Installer version has been certified to work with
Oracle
 Server and Oracle Clients 7.3.4, 8.0.4, and 8.0.5.

Platforms Affected
~~~~~~~~~~~~~~~~~~
  Exclusive to Win32 (Windows NT / Windows 95 / Windows 98)

Description
~~~~~~~~~~~
  The RGS product registration file contained a 2-digit
  timestamp.

Likelihood of Occurrence
~~~~~~~~~~~~~~~~~~~~~~~~
  100% certainty after Dec 31st, 1999.

Possible Symptoms
~~~~~~~~~~~~~~~~~
  Protection Exception (GPF)
  Access Violation

Workaround
~~~~~~~~~~
  Set the system clock back to 1999, perform the install,
  and reset the system clock back to 2000.

Patches
~~~~~~~

  Download the

  Y2K Compliant Oracle Installer for Win32 (ver.3.3.1.1.0C) from
MetaLink.

  Login to MetaLink at
http://www.oracle.com/support/elec_sup/
  In MetaLink V1 select the Downlaod button to access patches.
  In MetaLink V2 select the Patches button.

    1.  Select Oracle Installer for the Product and Windows NT
for the
Platform.
    2.  Click Go.
    3.  Download the readme and patch.

References
~~~~~~~~~~
  BUG 826393 / BUG 826397

This alert was updated 30-Nov-1999 with a new patch set id.

This alert is a Year 2000 Readiness Disclosure, and is provided
pursuant to the Year 2000 Information and Readiness Disclosure
Act.
_________________________________________________________________
___________
__
                                   Oracle WorldWide Customer
Support
May 02, 2000 Zhuo -- Thanks for the question regarding "Why doesn't revoke connect drop the user", version
You Asked
   Thank you for your help.I have a question today.
After I revoke a database user,eg"revoke connect from zhuo",I
use
"select * from all_users" ,and I find that the user which I just

revoke exists.
Can you tell me why it is?
and we said...
you've simply reduce the set of priveleges that user has.   You
did not drop the user.  Connect is a role -- you do not *need*
connect to be a database user or even to log in.  I can:

create user a identified by a;
grant create session to a;

Now, a can log in - they do not need connect.

To get rid of the user, use the DROP USER <username> command.
May 02, 2000 Boris -- Thanks for the question regarding "Subquery in inserts?", version
You Asked
is it possible to use a sub_query into an INSERT statement.

eg : INSERT into my_table
(col1,col2)
values
('a',as(select c from my_other_table));

What is the correct syntax ?
Thank you.
and we said...

Yes, it would be:

insert into my_table
(col1,col2)
select 'a', c from my_other_table
/
May 02, 2000 Krishna -- Thanks for the question regarding "Initialize varray easily.", version
You Asked
Dear Tom,
Is there a way to initialize the entire
varray without initializing the  individual elements in that
array
Eg
Tyep temp_str IS VARRAY(200) of varchar2(1000);
html_str temp_str temp_str := (null,null,null,......up to 200
times);
My question is can we in any way initialize this array insuch a
way that
each element is initialiazed to null without typing "null" for
200 times.
Thanks
Krishna P Roy
and we said...
declare
   html_str  temp_str := temp_str();
begin
   for i in 1 .. 200 loop
      html_str.extend;
      html_str(i) := null;
   end loop;
end;

Or, you could have a little function:

ops$tkyte@8i> create or replace function empty_str return
temp_str
  2  as
  3     empty  temp_str := temp_str();
  4  begin
  5     for i in 1 .. 200 loop
  6        empty.extend;
  7        empty(i) := null;
  8     end loop;
  9          return empty;
 10  end;
 11  /

Function created.

ops$tkyte@8i> show erro
No errors.
ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> declare
  2     html_str  temp_str := empty_str;
  3  begin
  4          null;
  5  end;
  6  /

PL/SQL procedure successfully completed.

if you need to do this often.
May 02, 2000 Cory -- Thanks for the question regarding "Is it possible to run programs such as SAS and Microsoft Excel from Oracle Forms?", version
You Asked
Tom,
Is it possible to run programs such as SAS and Microsoft Excel
from Oracle Forms?
If so, is it also possible to pass parameters to them?
Thanks,
Cory Sanford
and we said...
Sure, the easiest way is just via the "HOST()" command.  You
build a command line like you would in the Start/Run option and
it'll run it.

OLE is a more sophisticated way to do it and offers more contol
(see attached).  I don't know about SAS, but Excel certainly is
OLE enabled.

You can use DDE as well in Windows.  The forms doc go into that
(sort of 'old fashioned' tho)
May 02, 2000 Bhavesh -- Thanks for the question regarding "Trigger processing question", version
You Asked
HI:

I have a AFTER INSERT trigger question.
I have table called INPUT which has two columns, ID --> Number
and RADIUS --> Number data type coulumns.

Now, I have a procedure called CALCULATE_AREA which calculates
area of a circle by taking ID as the parameter. Now, I want to
automate the area calculation.
I tried to create a trigger (the code is pasted) which fire when

I insert a row in the INPUT table. THe trigger calls the
CALCULATE_AREA procedure. The problem is, table is mutating!
Because I query the same table INPUT, which is being inserted.
And I do need a AFTER INSERT trigger, because only after
insertion, the procedure gets the input.

Here is the code of trigger
Thanks a lot,
Regards,
Bhavesh
and we said...
[snip]

A row level trigger *cannot* read the table that fired the
triggering event.  You have 2 choices.  They are in my prefered
order of implementation (in the order i believe you should do
them).

o you have access to the entire row in the :new record.  Instead
of passing the ID to the calculate routine and having it read
the values out -- pass the values themselves.

o see
http://osi.oracle.com/~tkyte/Mutate/index.html
for a method of avoiding the mutating table error
when you cannot do it any other way (but since you can do it
another way -- i suggest that)
May 02, 2000 Mazhar -- Thanks for the question regarding "Start spooling from sqlplus login/glogin file", version
You Asked
When I open a sqlplus or svrmgr session

how can I ensure (using login.sql

or glogin.sql) a spool file is generated

with current date&time as the name of the

file and is saved when I exit the

session.

eg. 31mar2k0805.lst
and we said...
well... ENSURE is a very strong word.  Using sqlplus, you could
put into the login.sql or glogin.sql the following:

column spool_name new_value S
set termout off
select to_char( sysdate, 'ddmonyyyyhh24mi' ) spool_name from
dual;
set termout on
spool &S

that'll start spooling and sqlplus will end spooling when you
exit. HOWEVER, if at anytime the end user does a spool off, or
starts spooling to another file -- your initial spool is cut
off.

So -- you can auto start spooling but if someone issues any
spool commands themselves, yours will stop being in effect and
there is no way to stop it.
Review & Followup
Rating: 4
Start spooling from sqlplus login/glogin file March 14, 2002
Reviewer: Mir Mazhar Hussain from USA
The script was exactly what I needed. Thanks.

Rating: 4
June 25, 2002
Reviewer: Sagi from India
You are really great.

Thanx tom.

May 02, 2000 PRATHAP -- Thanks for the question regarding "tracing failures of jobs run via dbms_job", version
You Asked
Dear Sir,
I would like to know how to
maintain the history of job scheduling
executed through DBMS_JOBS(ORACLE 8)
in order to trace any failures,
since, the system
tables - DBA_JOB, DBA_JOBS_RUNNING
are over written during execution.

Thanking you

Prathap Kumar
Calcutta
and we said...
Every time a job runs and is unsuccessful (eg: raises an
unhandled error), two things are done

o A message is written to the alert log. the error will look
something like:

Fri Mar 17 16:31:35 2000
Errors in file
/export/home/oracle8i/admin/ora8i/bdump/ora8i_snp0_481.trc:
ORA-12012: error on auto execute of job 206252
ORA-01460: unimplemented or unreasonable conversion requested
ORA-06512: at "SYS.DBMS_SNAPSHOT", line 587
ORA-06512: at "SYS.DBMS_SNAPSHOT", line 644
ORA-06512: at "SYS.DBMS_IREFRESH", line 561
ORA-06512: at "SYS.DBMS_REFRESH", line 207
ORA-06512: at line 1

o A trace file is generated, the second line of the error above
tells us what file this is.  We can review this file for more
details of the error.
May 02, 2000 Manoj -- Thanks for the question regarding "Deleting from a joined view", version
You Asked
Dear tom,

We have a table having the following structure
sw_emp_no char(10) not null

Now this table is owned by user ADMIN. Now,we have created a
view
on the table in a different schema .When we want to delete
records from this table from the other schema, we am prompted
with the following error by Oracle
The whole problem is as follows.

This is the view defining query:
create or replace view SWA_EMP_PROC as select a.* from
ADMIN.SWA_EMP_PROC
a,mst_emp_master b where a.SW_EMP_NO = b.ms_emp_no

On deletion from the view we are prompted with the error:

ORA-01752: cannot delete from view without exactly one
key-preserved table

A similar definition of the same view doesn't however give an
error on deletion from swa_emp_proc view.

CREATE OR REPLACE VIEW SWA_EMP_PROC AS SELECT * FROM
ADMIN.SWA_EMP_PROC
WHERE SW_EMP_NO IN (SELECT MS_EMP_NO FROM MST_EMP_MASTER)
and we said...
Similar --- but very different.  Consider this annotated
example.  The solution, if your model supports it, is to put a
UNIQUE constraint on mst_emp_master(ms_emp_no).

ops$tkyte@8i> create table swa_emp_proc( sw_emp_no char(10) not
null );
Table created.

ops$tkyte@8i> create table mst_emp_master( ms_emp_no char(10)
not null );
Table created.

ops$tkyte@8i> insert into swa_emp_proc values ( 1 );
ops$tkyte@8i> insert into mst_emp_master values ( 1 );
ops$tkyte@8i> insert into mst_emp_master values ( 1 );
ops$tkyte@8i> commit;
Commit complete.

Here are your views:

ops$tkyte@8i> create or replace view SWA_EMP_PROC_JOIN as select
a.* from SWA_EMP_PROC
  2  a,mst_emp_master b where a.SW_EMP_NO = b.ms_emp_no
  3  /
View created.

ops$tkyte@8i> CREATE OR REPLACE VIEW SWA_EMP_PROC_IN AS SELECT *
FROM SWA_EMP_PROC
  2  WHERE SW_EMP_NO IN (SELECT MS_EMP_NO FROM MST_EMP_MASTER)
  3  /
View created.

ops$tkyte@8i> REM this shows they can be different in the data
they return:

ops$tkyte@8i> select * from SWA_EMP_PROC_JOIN;

SW_EMP_NO
----------
1
1

ops$tkyte@8i> select * from SWA_EMP_PROC_IN;

SW_EMP_NO
----------
1

ops$tkyte@8i> REM this shows you cannot delete from the JOIN
view since the
ops$tkyte@8i> REM rows in swa_emp_proc are 'multiplied' -- you
get a row back
ops$tkyte@8i> REM for each row in mst_emp_master
ops$tkyte@8i> REM It is ambigous how the delete should proceed
on this.
ops$tkyte@8i> REM consider "delete form swa_emp_proc_join WHERE
ROWNUM = 1"
ops$tkyte@8i> REM that would in effect delete 2 rows -- but it
cannot -- its not defined
ops$tkyte@8i> REM so we don't permit it to happen:

ops$tkyte@8i> delete from SWA_EMP_PROC_JOIN;
delete from SWA_EMP_PROC_JOIN
            *
ERROR at line 1:
ORA-01752: cannot delete from view without exactly one
key-preserved table

but we can delete from the IN since the rows in A are not
'multiplied'

ops$tkyte@8i> delete from SWA_EMP_PROC_IN;
1 row deleted.

ops$tkyte@8i> rollback;
Rollback complete.

Lets get rid of the one row that messes this up:

ops$tkyte@8i> delete from mst_emp_master where rownum = 1;
1 row deleted.

and add a unique constraint:

ops$tkyte@8i> alter table mst_emp_master add constraint
ms_emp_no_unique unique(ms_emp_no);
Table altered.

ops$tkyte@8i> REM Now, we have the constraint that makes it so
that the rows in
ops$tkyte@8i> REM swa_emp_proc are *not* multiplied by rows in
mst_emp_master.
ops$tkyte@8i> REM now we have a key preserved join and can
delete from it
ops$tkyte@8i>
ops$tkyte@8i> delete from SWA_EMP_PROC_JOIN;

1 row deleted.

Hope this clears up the confusion.
May 02, 2000 Kailasapathy -- Thanks for the question regarding "how to resize redo log files.", version
You Asked
I'm running Oracle 7.3.4 in archivelog mode, my relog
files size is 1 MB and found it's generating lot of archive log
files.
I want to increase the size of redo logs without shutting down
the database, is there any
method to increase the size of redolog files dynamically.
and we said...
You'll just add new LARGER redo log files and then drop the
existing small ones.  There is no way to resize a log file
(whether the database is up or down).  Just add new ones, issue
"alter system switch logfile" to advance the logs to these new
ones and then drop the old small ones.
Review & Followup
Rating: 4
Make sure the database has checkpointed June 13, 2001
Reviewer: Peter Hitchmough from Macclesfield UK
The response is right and worked for me, but a little more may be required when
dropping the latest logfile...

Watch out that you don't get ORA-1624 "log %s needed for crash recovery of
thread %s".

Cause:  A log cannot be dropped or cleared until the thread's checkpoint has
advanced out of the log.
Action: If the database is not open then open it. Crash recovery will advance
the checkpoint. If the database is open force a global checkpoint. If the log is
corrupted so that the database cannot be opened, it may be necessary to do
incomplete recovery until cancel at this log.

May 02, 2000 KK -- Thanks for the question regarding "Howto Standby Database in 7.3", version
You Asked
I'm now responsible for building a
new backup and recovery procedure for
my company billing database.  I would
like to set up a standby database.
The production DB and the standby DB are
both Oracle V7.3.4.

Can you suggest any other alternatives
to me?
and we said...
A standby database is a great FAILOVER solution.  It is not a
backup/recovery solution however.  The standby database is used
when you want to failover to another machine in seconds/minutes
in the event the production machine is blown up or something.
Backups/recovery are used when you want to be able to recover
all or part of a database and can afford to have the affected
data be unavailable during the recovery.

I've attached a note describing how to setup standby databases
for 7.3.

Article-ID:         <Note:33236.1>
Alias:              OLS:9750280.61
Circulation:        PUBLISHED (EXTERNAL)
Folder:             server.Rdbms.Recovery
Topic:              ** Standby Databases
Title:              HOT STANDBY DB INFO IN 7.3
Document-Type:      FAQ
Impact:             MEDIUM
Skill-Level:        NOVICE
Server-Version:     07.03 to 07.03
Updated-Date:       11-DEC-1999 07:08:55
References:
Shared-Refs:
Authors:            COMET
Attachments:        NONE
Content-Type:       TEXT/PLAIN
Keywords:           RDBMS; RECOVERY; STANDBY;
Products:           5;
Platforms:          GENERIC;

Document ID:        9750280.61
Title:              Hot Standby DB info in 7.3
Creation Date:      21-DEC-95
Last Revision Date: 21-DEC-95
Revision Number:    0
Product:            RDBMS
Product Version:    7.3
Platform:           N/A
Information Type:   Advisory
Impact:             Medium
Abstract:           The objective of the Standby Database
feature is to support
                    the capability of maintaining a duplicate,,
or standby,
                    database of a primary,or on-line, database
for recovering
                    from disasters at the production site.
Keywords:           RDBMS;STANDBY;RECOVERY

-----------------------------------------------------------------
--------------

                Standby Database Feature of ORACLE7 Version 7.3

Introduction
The objective of the Standby Database feature is to support the
capability of
maintaining a duplicate, or standby, database of a primary, or
on-line,
database for recovering from disasters at the production site.
Standby
Database consists of an external interface and checks within the
Oracle7
kernel code to detect and correct data corruption situations.
This paper
describes the design concepts and external interfaces of the
Standby Database
feature.

The Standby Database feature is intended to address the general
requirement
areas of data availability and product usability. Data
availability is
increased by providing production application accessibility to
the data
through a switch over to the standby database sooner than if the
usual
recovery procedures had been applied to the primary database.
Usability is
increased in that through this feature Oracle Corporation
provides a
methodology to endorse and support disaster recovery.

Design Concepts
The Standby Database feature allows a customer to maintain a
duplicate copy of
a database at a remote site by using the archived log
information. The
database being copied from is referred to as the primary
database, and the
database being copied to, or the duplicate copy, is referred to
as the standby
database.

The primary database is any ORACLE7 release 7.3, or higher,
database
functioning as accustomed, without restriction. The standby
database is
duplicated on physical hardware (disk and cpu) separate from the
primarydatabase and is not used for any application other than
as a disaster
recovery system. The standby database is kept constantly in
recovery mode.

As the primary database archives its redo logs, these log files
can be
transferred to the remote site and applied to the standby
database. The
standby database is always behind in time and transactional
history from the
primary database.

In the event of a catastrophic failure of the primary
database,the standby
database can be taken out of recovery mode and activated for
on-line use. From
the point of activating, or opening the standby database, the
standby database
is now the primary database from the points of view of the
customer's business
and Oracle software.

The standby database is not intended for any other use other
than as a
disaster recovery database for the primary database. The standby
database can
not be queried or opened for any other purpose other than to
activate in the
event of catastrophic error of the primary database. Once the
standby database
is activated it can not be returned to standby recovery mode
without
recreating it again as a standby database, and the primary
database will not
have any transactional history beyond the point in time when the
disaster
occurred.

External Interface
The following activities must be done by the database
administrator to use
this feature; creation of the standby database, maintenance of
the standby
database, and activation of the standby database. The primary
goal of these
administrative procedures is to keep the control file, log files
and data
files consistent with eachother as well as consistent between
the primary and
standby databases.

Creating the Standby Database
To create the standby database,the database administrator must
take a back-up
copy of the data files of the primary database, create a back-up
control file
for the standby database, and archive the on-line redo logs of
the primary
database. The backed-up data files, control file and archived
log files can
then be transferred to a remote site where the standby database
will be
maintained.

To create a standby database, perform the following procedures:
1. Back-up the data files from your primary database. The
back-ups can be done
either on-line or off-line.
2. Create the control file for your standby database by issuing
the ALTER
DATABASE CREATE STANDBY CONTROLFILE AS 'filename' command. This
command
creates a modified back-up copy of the primary database's
control file.
3. Archive the current on-line redo logs of the primary database
by issuing
the ALTER SYSTEM ARCHIVE LOG CURRENT command. This command
forces a log switch
on all threads and archives all of the redo at an scn after the
data files
have been backed-up.
4. Transfer the standby database control file, archived log
files and
backed-up data files to the remote (standby) site.

Maintaining the Standby Database
To maintain the standby database, the stand by database mus be
mounted and put
in to standby recovery mode. As redo logs are archived at the
primary site,
these logs must be transferred to the remote site and applied to
the standby
database.

To maintain your standby database in recovery mode, perform the
following
procedures:
1. Mount (but do not open) the standby database by issuing the
ALTER DATABASE
MOUNT STANDBY DATABASE [EXCLUSIVE/PARALLEL] command.
2. Transfer the archived redo logs from the primary database to
the remote
(standby) site.
3. Put the standby database in to recovery mode by issuing the
RECOVER [FROM
'location'] STANDBY DATABASE command.

As the archived logs are generated at the primary site, you must
continually
transfer and apply them to the standby database. Also, you can
only apply logs
to the standby database that have been archived on the primary
database.
Refreshing the Standby Database Control File

Certain administrative operations on the primary database make
modifications
to the primary database's control file which need to be
propagated to the
standby database's control file. In this case it is necessary to
refresh the
standby database's control file from the primary database's
modified control
file.

To refresh your standby database's control file, perform the
following
procedures:
1. Issue the CANCEL command on the standby database to halt the
recovery
process.
2. Issue the ALTER DATABASE CREATE STANDBY CONTROL FILE AS
'filename' command
on the primary to database to create a refreshed copy of the
control file.
3. Issue the ALTER SYSTEM ARCHIVE LOG CURRENT command on the
primary database
to archive the current on-line logs of your primary database.
4. Transfer the standby control file and the archived logfiles
to the standby
database.
5. Restart the recovery process on the standby database.

If you use the CREATE CONTROLFILE command on the primary
database to change
the maximum number of data files, instances, or redo logfile
groups, the
physical size of the control file changes and then you must
refresh the
standby database control file.

Activating the Standby Database
In the event of a disaster, you should (if possible) archive the
current
on-line logs of the primary database, transfer and apply these
logs to the
standby database before activating the standby database. The
standby database
will then be current to the same point in time and transactional
history as
the primary database before the failure. If you can not archive
your current
on-line logs, then you must activate the standby database
without recovering
the transactions from the unarchived logs of the primary
database.

To activate a standby database, perform the following
procedures:
1. Mount the database in EXCLUSIVE mode by issuing the ALTER
DATABASE MOUNT
STANDBY DATABASE EXCLUSIVE command.
2. Issue the ALTER DATABASE ACTIVATE STANDBY DATABASE command.
3. Shutdown your standby instance.
4. Back-up the database.
5. Startup the instance.

At the completion of the activate command, the database is no
longer
considered a standby database, but is now a production database.
For this
reason it is recommended that the database be backed-up
immediately.

Activating the standby database resets the on-line log files and
modifies the
control file. After activation, the standby database can not be
returned to
standby recovery mode.

Resetlogs Operation
Opening the primary database with the RESETLOGS option or using
the CREATE
CONTROLFILE command with the RESETLOGS option invalidates the
standby
database. If you reset the on-line logs of the primary database
you must
re-create the standby database by following the standby database
creation
procedures. Activating a standby database resets the on-line
logs of the
standby database. You can follow the creation procedures to
create a standby
database from the activated database.

Direct Path Operations
Performing direct loads originating from a direct path load,
table create via
subquery, or index create on the primary database, the
performance gain
applies only to the primary database. There is no corresponding
recovery
process performance improvement on the standby database. The
standby database
recovery process still sequentially reads and applies the redo
information
generated by the unrecoverable direct load. Also, operations
using the
UNRECOVERABLE option are not propagated to the standby database
since the
operations are not logged.

Data files affected by direct path operations on the primary
database can be
altered off-line in the standby database. Data files altered
off-line in the
standby database must be altered off-line with the DROP option.
Tablespaces
containing the off-lined files must be dropped when the standby
database is
activated.
Review & Followup
Rating: 4
standby database January 27, 2002
Reviewer: g.v.n.rao from houston,tx

May 04, 2000 priyanka -- Thanks for the question regarding "how to do "Where column = bind_variable" and bind_variable might be NULL", version
You Asked
I have an sql in which I am passing a host variable to
a column.When the value of host variable is null it does not
retreive any records.Since the query becomes address_id=null it
does not work.How should I write this query.

select name,address,phone_no
from patient
where patient_id = :pat_id
and address_id = :add_id;
and we said...
I'm going to assume that patient_id is the indexed column and
that address_id is not.  If so:

select *
  from patient
 where patient_id = :pat_id
   and ( address_id = :add_id:add_id_ind OR :add_id:add_id_ind
is NULL )
/

is one method.  If address_id is the indexed column, what might
work best is:

select *
  from patient
 where patient_id = :pat_id
   and address_d = :add_id:add_id_ind
UNION ALL
select *
  from patient
 where patient_id = :pat_id
   and :add_id:add_id_ind is null
/

The optimizer will run only one of the 2 parts of the union all
query -- if add_id is NULL, the it realizes the address_id =
:add_id cannot succeed and does the second query.  if add_id is
NOT NULL, it realizes the second query cannot return data and
does not run it.
May 04, 2000 Juan -- Thanks for the question regarding "Is there a way to store Seagate Crystal Reports in Oracle", version
You Asked
Is there a way to store Seagate Crystal Reports in
Oracle?? For example as BLOB's  How would I store/access them
from PL/SQL or VB 6??
and we said...
You say you have Oracle7 but refer to BLOBS which are part of
Oracle8 and up.

I'll tell you about blobs -- they are version 8.0 and up only
though.

If you goto
http://technet.oracle.com/doc/oracle8i_816/appdev.816/index.htm
You'll find all of the documentation on LOBs with specific
examples for PL/SQL and VB.  This documentation is from the
Oracle8i release 2 (8.1.6) documentation set but applies almost
verbaitim to the 8.0 and up releases.  I'm pointing you to this
set specifically because of the new examples they have there
(the language specific examples are new in the 8.1.6 doc set)

If you are not talking about blobs, but rather long raws in
Oracle7 -- the answer is still yes, but only via VB (plsql
cannot manipulate a long raw that is larger then 32k).
May 04, 2000 amit -- Thanks for the question regarding "Can I rename a column?", version
You Asked
How to rename a column? Is there any way using data
dictionary views?
and we said...
There are no ways to rename a column.

Views are an appropriate way to perform a column rename. You
would:

1) rename T to T_TABLE;
2) create view T as select c1 new_name_for_c1, ... from T_TABLE;
3) grant on T
4) revoke on t_table

The view T will behave just like the table T did.
May 04, 2000 VENKATARAMAN -- Thanks for the question regarding "Where are utloidxs.sql and utldidxs.sql?", version
You Asked
In Oracle 7.x, to determine a column of a table
to be indexed or not, two following scripts were
given.
1. utloidxs.sql
2. utldidxs.sql

I could not locate similar scripts in Oracle 8i Enterprise
Edition
( 8.1.6.0.0 ).  Kindly tell me what are the equivalant scripts ?
and we said...
don't need them.  ANALYZE does all of this now.  For example:

ops$tkyte@8i> analyze table emp compute statistics;
ops$tkyte@8i> select column_name, num_distinct
  2  from user_tab_columns where table_name = 'EMP';

Column Name                    NUM_DISTINCT
------------------------------ ------------
EMPNO                                    14
ENAME                                    14
JOB                                       5
MGR                                       6
HIREDATE                                 13
SAL                                      12
COMM                                      4
DEPTNO                                    3
ops$tkyte@8i> select num_rows
  2  from user_tables where table_name = 'EMP';

  NUM_ROWS
----------
        14
ops$tkyte@8i>

It gives you all you need to determine what might be an index
candidate (in one full scan instead of ONE full scan / column )
May 04, 2000 adurthi -- Thanks for the question regarding "Will installing 8.1.5 context cartrage work in 8.0.4 database?", version
You Asked
Will installing 8.1.5 context cartrage work in 8.0.4 database?

the reason why i want is there are third party
products that are not yet certified against 8.1.5, and therefore
require
8.0.4.
Then there are other third party products that are certified
against
8.1.5 and require 8.1.5 context cartrages.
and we said...
No, it will not work at all.  There were major architectural
changes between 8.0 and 8.1 as far as how context works.  They
are almost like 2 different products. 8.1's implementation is
much more kernel based and will not work at all in 8.0
May 04, 2000 Liviu -- Thanks for the question regarding "Using bind variables in DDL", version
You Asked
Can I use placeholders to prepare a statement like this?

drop table ? cascade constraints

If not, which is the fastest method to use instead?
I need to delete about 30 tables from my schema.
Thanks,
and we said...
Bind variables cannot be used in DDL.  You must use dynamic sql
(if you do not know the names until runtime) or you can use
static sql if you know them all.

The "drop table TNAME cascade constraints" is the fastest (and
only) way to drop 30 named tables.  It can be held up from time
to time due to the fact that DML on the catalog is pretty
expensive and prone to getting blocked (and blocking others).
May 04, 2000 Hakan -- Thanks for the question regarding "Question about parameterized view", version
You Asked
i have a view (passwords) and a function (sf_set_key),
function just sets a global variable and view uses this global
variable in it. (view also has some functions in it)

what i do now is ,
select sf_set_key('HAKAN') from dual;
then
do select from the query...
select id,password from passwords where id='ID1';

is it possible to combine these two steps...
i mean just one select, this select first (always) call the
function and do the select...

thanks a lot.
hakan yuksel
and we said...
Not really -- because you have no control over the order of
operations.  You need sf_set_key to happen first, then the view
can be processed.  The only way to be assured the function is
executed BEFORE the view is -- is to explicity execute the
function and then the view.

If you really really want to make it a one step process, you
could select * from a  plsql function instead of a view.  It
might look like this:

ops$tkyte@8i> create or replace type myScalarType as object( id
number, password varchar2(30) )
  2  /

Type created.

ops$tkyte@8i>
ops$tkyte@8i> create or replace type myTableType as table of
myScalarType;
  2  /

Type created.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> create or replace function sf_set_key( p_string in
varchar2, p_id in varchar2 ) return myTableType
  2  as
  3      l_data             myTableType := myTableType();
  4  begin
  5
  6          l_data.extend;
  7          l_data(1) := myScalarType( 100, p_string || ' ' ||
p_id );
  8
  9          -- procedural code to get the values that SHOULD be
returned go here.
 10
 11          return l_data;
 12  end;
 13  /

Function created.

ops$tkyte@8i>
ops$tkyte@8i> select *
  2    from THE ( select cast( sf_set_key('HAKAN', 'ID1') as
mytableType ) from dual ) a
  3  /

        ID PASSWORD
---------- ------------------------------
       100 HAKAN ID1

your routine sf_set_key can get whatever data it wants to put
into l_data and return it.  For exmaple, sf_set_key could be:

   ... set that global variable as you do now ....
   for x in ( select * passwords where id = p_id )
   loop
      l_data.extend;
      l_data(l_data.count) := myScalarType( x.id, x.password );
   end loop;
   return l_data;
May 04, 2000 Gene -- Thanks for the question regarding "Can resize both expand and shrink a file?", version
You Asked
Tom,

I have a question about the "resize" command.  Can the "resize"
command be used in both expanding and shrinking the size of a
datafile?  The only documentation I can find says that "resize"
is used to reclaim space (shrinking).  I cannot find any other
use for the "resize" command, unless of course I am not looking
in the right places.

Thanks,

Gene Martin
and we said...
It can be used to shrink or to grow a datafile.  I use it for
both purposes.

This is from the Oracle8i sql ref manual

RESIZE attempts to increase or decrease the size of the datafile
to the specified absolute size in bytes. Use K or M to specify
this size in kilobytes or megabytes. There is no default, so you
must specify a size. If sufficient disk space is not available
for the increased size, or if the file contains data beyond the
specified decreased size, Oracle returns an error.

In Oracle7, they simply said:

RESIZE attempts to change the size of the
datafile to the specified absolute
size in bytes. You can also use K or
M to specify this size in kilobytes
or megabytes. There is no default,
so you must specify a size.
May 04, 2000 ted -- Thanks for the question regarding "Getting the difference between dates in seconds.", version
You Asked
Thomas,
how do I do a date difference between
two dates and got in the format of seconds.
thanks ted
and we said...
select  ( date2 - date1 ) * 24 * 60 * 60 from dual;

See
http://osi.oracle.com/~tkyte/Misc/DateDiff.html
for more variations on a theme.
May 04, 2000 Amit Malusare -- Thanks for the question regarding "complex decode ", version
You Asked
I would like to know if one can use Decode to use Wild
Characters Like '%'.
Eg.
Select Decode (ename,'A%','Aalpha','B%','BALPLHA") from emp;
This is not possile is there any other way.
and we said...
In Oracle8i release 2 -- there is a new case statement in SQL
that will permit the above directly.

Using decode, you cannot use LIKE.  You can use, in the case of
the above:

select decode( substr(ename,1,1), 'A', 'Aalpha', 'B', 'BALPHA' )
from emp;

you would have to use some combinations of subst and instr to do
it.  If you cannot do it, you can always:

create function mydecode( ename in varchar2 ) return varchar2
as
begin
  if ( ename like 'A%' ) then return 'Aalpha';
  elsif ( ename like 'B%' ) then return 'BALPHA';
  ....

  end if;
end;

select mydecode( ename ) from emp;
May 04, 2000 Saravanan (Saran) -- Thanks for the question regarding "Generic "file open" dialog in forms", version
You Asked
  I want to know, the best possible way for me to
create a button in my form which can perform a function just
like
windows browse button does. It's like if we press the button, we

can search the documents that we need in the browser.
If you are not clear what kind of button function that I need,
just go to windows, press the start button, go to RUN. In that
windows you will see three button's, "Ok" "Cancel" & "Browse". I

want the oracle forms to perform the same function.
How can I do This ??
and we said...
DECLARE
      filename VARCHAR2(256);
BEGIN
    filename := GET_FILE_NAME(File_Filter=> 'DOC Files
(*.doc)|*.doc|');
end;

does it, this is from developer release 6.0
May 04, 2000 Saibabu -- Thanks for the question regarding "blocks column in dba_tables", version
You Asked
Hai,
Can you clarify the differnec between
the blocks column in dba_tables and
High water mark.what i understand is that both are same.But i
read in metalink that both can be differnt.I request you to
explain on this.
Thanks
Saibabu
and we said...
well, the blocks in dba_tables is the number of blocks below the
HWM "as of the last analyze".  It is not 100% accurate -- since
it is current as of the last analyze.  Here is an example with
comments embedded:

ops$tkyte@8i> create table emp as select * from scott.emp;
Table created.

ops$tkyte@8i> select blocks, empty_blocks from dba_tables where
owner = USER;

    BLOCKS EMPTY_BLOCKS
---------- ------------

Initally, blocks is NULL, we have to analyze to fill it in..  We
can see the number of allocated blocks with:

ops$tkyte@8i> select blocks, bytes from dba_extents where owner
= USER;

    BLOCKS      BYTES
---------- ----------
        64     524288

ops$tkyte@8i> analyze table emp compute statistics;
Table analyzed.

ops$tkyte@8i> select blocks, empty_blocks from dba_tables where
owner = USER;

    BLOCKS EMPTY_BLOCKS
---------- ------------
         1           62

Now, we can see that 1 block has data and 62 are emtpy (the last
block is an extent map -- there are 64 blocks allocated, 1 with
data, 1 with a map and 62 empty ones).

ops$tkyte@8i> insert into emp select * from emp;
14 rows created.

ops$tkyte@8i> insert into emp select * from emp;
28 rows created.

ops$tkyte@8i> insert into emp select * from emp;
56 rows created.

ops$tkyte@8i> insert into emp select * from emp;
112 rows created.

So, now we've made the table larger -- lets see what happens:

ops$tkyte@8i> select blocks, empty_blocks from dba_tables where
owner = USER;

    BLOCKS EMPTY_BLOCKS
---------- ------------
         1           62

ops$tkyte@8i> select blocks, bytes from dba_extents where owner
= USER;

    BLOCKS      BYTES
---------- ----------
        64     524288

that data did not change -- still looks like 1 block under the
HWM but really:

ops$tkyte@8i> analyze table emp compute statistics;
Table analyzed.

ops$tkyte@8i> select blocks, empty_blocks from dba_tables where
owner = USER;

    BLOCKS EMPTY_BLOCKS
---------- ------------
         3           60

There are 3.  A full scan would hit 3 blocks now, not 1.

--
Thanks,

    Thomas Kyte                          tkyte@us.oracle.com
    Oracle Service Industries

    Oracle tips and papers
http://www.oracle.com/oramag/code/index.html
May 04, 2000 Saibabu -- Thanks for the question regarding "How long has a query/statement been running", version
You Asked
Being a DBA how can i know when exactly a particular
query is started in a particular session.Is there any script to
monitor the progress of select queries.
and we said...
If you look at the v$session table -- there is a column
last_call_et (last call Elapsed Time).  This will be set to ZERO
when a query is submitted.  It will be set to ZERO when the
query completes.  While the query is progressing -- it'll
increment in seconds.  If you start 2 sessions and in one do
something that will take a couple of seconds (eg: select
count(*) from all_objects) with "set timing on" in sqlplus --
and in the other issue:

select sid, last_call_et from v$session where username = user;

you'll see the progress of the other query ticking off in
seconds.  If you keep hitting slash -- you'll find last_call_et
to be about the same as the amount of time reported by set
timing on.  then last_call_et will become zero -- indicating the
query is not running anymore (and then last_call_et will begin
incrementing again, counting your idle time in the other
session)
May 04, 2000 Venkat -- Thanks for the question regarding "Update Cascade", version
You Asked
What is the simplest way of updating the primary key
and all its child table foreign keys in Oracle 7.3 (apart from
disabling the referential constraints in child tables).
and we said...
See
http://osi.oracle.com/~tkyte/update_cascade/index.html
for a solution.
May 04, 2000 tony -- Thanks for the question regarding "Can I install ORACLE 8.0.5 on Windows 2000?", version
You Asked
Can I install ORACLE 8.0.5 on Windows 2000?
and we said...
That is not a supported configuration.  the only release of
oracle supported on Win2k is Oracle8i, release 2, version 8.1.6
and up, which you can get from
http://technet.oracle.com/
Review &
      Followup

      Rating: 5
Thanks
      Tom!  January 31, 2002
Reviewer:  Paulo
       from Brazil
Gotta love this site!!!

May 04, 2000 Gene -- Thanks for the question regarding "RE:
      Ask Tom Submission", version

      You Asked
Tom,

I had asked a question about rollback segments and their optimal

size being altered online yesterday.  This question is along the

same lines, and I forgot to include it yesterday.  If I need to
increase the extents of the Rollback segments because I am
getting 80+ wraps on a Rollback segment, must I drop and
recreate
that Rollback segment and the TableSpace that the Rollback
segment is in to increase the size of the datafile, or what
needs
to be done to accomplish this with the least amount of headache?

Thank you.

Gene

      and we said...
To increase the NUMBER of extents the rbs may have:

ops$tkyte@dev8i> alter rollback segment demo storage (
maxextents 255 );

Rollback segment altered.

To increase the sizes of them:

  1* alter rollback segment demo storage ( next 1m )
ops$tkyte@dev8i> /

Rollback segment altered.

if you need to increase the size of a datafile:

alter database datafile '/path/to/some/file.dbf' resize
<newsize>;

(i would not go past 2gig) or add a datafile:

alter tablespace add datafile '/path/to/some/newfile.dbf' size
50m;

These can all be done online.

--
Thanks,

    Thomas Kyte                          tkyte@us.oracle.com
    Oracle Service Industries

    Oracle tips and papers
http://www.oracle.com/oramag/code/index.html

May 04, 2000 Lalita -- Thanks for the question regarding
      "finding the size in bytes of an index", version

      You Asked
How can we find the exact size (number of bytes)
of an index segment

      and we said...
well -- you need to be a little more specific.  We can find the
allocated space (how much space has been carved out to be used
only by this index segment) and we can find the amount of space
within that space that is/has been actually used (the 'high
water mark').

Consider -- I have an index T_IDX:

ops$tkyte@8i> select bytes, blocks, extents from user_segments
where segment_name = 'T_IDX';

     BYTES     BLOCKS    EXTENTS
---------- ---------- ----------
   1048576        128          2

There is the amount of space dedicated to this segment.  128
blocks.

If I analyze the index (estimate on a big one)

ops$tkyte@8i> analyze index t_idx compute statistics;
Index analyzed.

ops$tkyte@8i> select blevel, leaf_blocks, num_rows from
user_indexes where index_name = 'T_IDX';

    BLEVEL LEAF_BLOCKS   NUM_ROWS
---------- ----------- ----------
         1          89      20252

I find that there really are about 89 blocks in use.  These
stats will remain in the data dictonary until i re-analyze or
delete the stats.

Further, if I "validate" the index, I can get a little more
data:

ops$tkyte@8i> analyze index t_idx validate structure;
Index analyzed.

ops$tkyte@8i> select height, blocks, lf_blks, br_blks,
btree_space, used_space from index_stats where name = 'T_IDX';

    HEIGHT     BLOCKS    LF_BLKS    BR_BLKS BTREE_SPACE
USED_SPACE
---------- ---------- ---------- ---------- -----------
----------
         2        128         89          1      719672
634258

That shows that of the allocated and used space -- I have about
700k, The space ACTUALLY in use in that allocated and used space
is about 630k.  This is exactly what I expected as this is a
brand new index I just created and the pctfree was set to 10% so
10% of each block has been reserved for furture inserts into
these blocks --700k - 10% is 630k.  Note that the index stats
view "empties" itself after you disconnect -- you would have to
save this data into another table if you wanted to analyze it
further.

May 04, 2000 MANISH -- Thanks for the question regarding "what
      is a meaning of 'WEB ENABLED APPLICATION'", version

      You Asked
1)what is a meaning of 'WEB ENABLED APPLICATION'? and
what it's require if somebody is using oracle8i? Do we need
Oracle Application Server for that? and if forms6 is a frontend
then how it works?

      and we said...
Typically it means an application that is executed from a web
browser/applet viewer. It might be a forms application delivered
as a java applet to the client, it might be an HTML application
like Amazon.com.

If someone is using Oracle8i, that might be all they need.
Oracle8i allows you to do IIOP from a client directly into the
database.  Since IIOP is the protocol used by Enterprise Java
Beans (EJBs), this means you can deploy a java applet to client
and have that client connect directly to the database using
IIOP.

It is more typical to have an application server in the mix
however to serve up HTML pages and images and perhaps run some
dynamic pages as well using java servlets, plsql, perl, etc.

see
http://www.oracle.com/iplatform/
and
http://www.oracle.com/tools/InternetDevTools/index.html
for more info.
May 04, 2000
      blues -- Thanks for the question regarding
      "can i hardcode username/password into a form", version

      You Asked
How can I avoid to ask user/password when firstly run
Form and hardcode the connection information inside Develop/2000
Forms?

      and we said...
Code an ON-LOGIN trigger.  In this trigger simply go:

begin
   logon( 'yourusername', 'yourpassword' );
end;

May 04, 2000 puvulla -- Thanks for the question regarding
      "controlling commit/rollback in a disibuted transaction", version

      You Asked
Can I control commit or rollback
from one database to another database
if the database in distributed database.

      and we said...
In a distributed database, the database you INITIALLY logged
into is the only database that can issue the commit or rollback.
 If you log into "database1" and issues DML on "database1",
"database2" and "database3", only "database1" may commit or
rollback.

By setting up commit point strengths, you may control with
database is the "coordinator" of the 2 phase commit but still
only "database1" would actually issue the commit.

May 04, 2000 KK -- Thanks for the question regarding "Can I do
      mutlithreaded programming in PLSQL", version

      You Asked
Can I do multithread programming in
Oracle proceudres?

By the way, I think dbms_pipe has similar
functions as dbms_alert's signal
functions, what's the difference?
Which one is much better if I want
to use them to write a program which
get stock price from the server?

      and we said...
No, a stored procedure is single threaded.  Using dbms_jobs, you
can have a single procedure initiate many procedures in the
background but this is more like a unix "fork/exec" then a
thread.

dbms_alert is used to send a signal to ALL interested parties.
It is transactional (the signal is not sent until you commit).
It "loses" signals -- if I signal the same event 5 times and
commit -- only one event might get broadcast.  It is like a unix
signal in this way.  Dbms_alert is asyncronous -- the sender
never gets anything back from the reciever.

dbms_pipe is used to send a message to a SINGLE interested party
(although >1 person can be reading the pipe, only ONE person
will get the message).  The message is sent immediately,
regardless of your transactions state.  It is like a unix pipe.
Dbms_pipe can be syncronous -- i can send a message and get a
message back.

If you are getting the stock price from a webserver -- I would
use utl_http (i would probably use utl_http in any case).  Added
in 7.3.3 of the database, utl_http lets me grab a web page.  I
can write a cgi-bin or some other sort of dynamic process
activated by a webserver to return data to my stored procedure.

Short of that -- dbms_pipe would be the logical second choice as
dbms_alert isn't for a 2 way conversation as you would need in a
"request" "answer" situation as you have.  See
http://osi.oracle.com/~tkyte/plex/index.html
for
something that might help you there.

May 05, 2000 Ebenesar -- Thanks for the question regarding
      "utl_file question", version

      You Asked
I want to write the result set to an
operating system file. For this I am using UTL_FILE package and
package has a fopen function which needs one of the the
parameters as the location (ie) the directory where the file can
be found.
And this accepts only the UNIX file directory and not the
Netware
directory.

In the Init Ora file the file security has been provided with
the
*. so that we can write or read from any directory.
what should be further done to have this file in any network
directory apart from the UNIX directories...!!
For inform. the Server resides in UNIX.

      and we said...
UTL_FILE can only see the file system on the server itself.
UTL_FILE is run in the Oracle dedicated/shared server which
resides on the server -- it is not running on the client side --
it cannot see the file systems the client can see.  For utl_file
to write to a netware volumn -- that volumn would have to be
mounted as a unix file system and accessible to the server
itself.

This is not a limitation of utl_file -- utl_file is running on
the server itself and can only see that file system.  Can you
have the netware disk mounted on the unix machine -- making them
available to processes running on the server?  Else you'll have
to bring the result set back to the client and write it there.

May 05, 2000 AB -- Thanks for the question regarding
      "composite primary key", version

      You Asked
I have a table with two columns that need to be defined
as primary keys, order_number and item_number.  A table can have

only one primary key, but I can define composite primary keys in

the table_constraint syntax.  How do I define two columns as
composite primary keys?

      and we said...
create table T ( x int,
                 y int,
                 z int,
                 constraint t_pk primary key (x,y) );

by using a table level constraint.  Additionally you could just:

alter table t add constraint t_pk primary key(x,y);

after the fact.

May 05, 2000 ping -- Thanks for the question regarding "Update
      cascade", version

      You Asked
I create two tables: course, timetable. course is
parent table and timetable is its child table. course includes a

attribute: course_code; timetable includes some attributes:
t_course_code, session_date etc. t_course_code of timetable is a

foreign key which refer to course_code of course. My question
is:
When I update course_code of course, I want t_course_code of
timetable to be updated automatically(that calls update
cascade).
How can I do it?

      and we said...
see
http://osi.oracle.com/~tkyte/update_cascade/index.html
for one solution.

Another, if you are using Oracle8, is to use a deferrable
constraint -- so the foreign key is checked at COMMIT time, not
at update time.  In this fashion, you could write a procedure to
do the update easily. This procedure would set the fkey
constraint to be deferred for this session, it can then update
the parent record and then the child records for you.

Review &
      Followup

      Rating:
      5
  May 20, 2001
Reviewer:  Pauline
       from NY, U.S.A.

May 05, 2000 Uppiliappan -- Thanks for the question regarding
      "Max identifier width.", version

      You Asked
What is the length of the table name we can give
(Please tell me the maximum width)

Can I have some Database Naming Standards

      and we said...
Oracle identifiers are a maximium of 30 characters.

The nice thing about standards is that there are so many of
them.  I cannot recommend any particular one, various tools (eg:
Oracle Designer) implement standard naming schemes for you.

May 05, 2000 Ramana -- Thanks for the question regarding
      "generating create index statements from data dictionary when using
      function based indexes.", version

      You Asked
Hi,

I have Oracle8i installed in one of my boxes and I am using
'Function Based Indexes' in that database.  I want to have a
script which can be used to generate the script for recreation
of
these indexes.. Earlier I used to do it,
based on user_ind_columns.. Now I find some SYS$ values for the
function based indexes..

Where do I find which function or evaluating statement is used
while creating the function based index?

Thanks in advance,
Ramana Damarla

      and we said...
Look at user_ind_expressions.

You'll join to that by index_name and column_position and pick
up the column_expression column

May 05, 2000 Mark -- Thanks for the question regarding ""base
      26"", version

      You Asked
I'm looking for a PL/SQL function that someone might
have already developed that converts a number between two bases,

such as from base 26 to base 10 and visa versa.

My end goal is to have an alpha sequence generator that issues
unique numbers in the range of AAA - ZZZ.  When I issue the
first
number, I need to increase the counter by 1, but adding 1 to AAA

is not allowed.

The desired function will convert the alpha string to a base 26
number and then covert it to base 10 to perform numerical
operations, then convert it back to base 26 and character
format.

-Mark

      and we said...
It could look like this:

ops$tkyte@8i> create or replace function to_base( p_dec in
number, p_base in number )
  2  return varchar2
  3  is
  4          l_str   varchar2(255) default NULL;
  5          l_num   number  default p_dec;
  6          l_hex   varchar2(255) default
'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  7  begin
  8          if ( trunc(p_dec) <> p_dec OR p_dec < 0 ) then
  9                  raise PROGRAM_ERROR;
 10          end if;
 11          loop
 12                  l_str := substr( l_hex,
mod(l_num,p_base)+1, 1 ) || l_str;
 13                  l_num := trunc( l_num/p_base );
 14                  exit when ( l_num = 0 );
 15          end loop;
 16          return l_str;
 17  end to_base;
 18  /

Function created.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> create or replace function to_dec
  2  ( p_str in varchar2,
  3    p_from_base in number default 16 ) return number
  4  is
  5          l_num   number default 0;
  6          l_hex   varchar2(255) default
'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  7  begin
  8          for i in 1 .. length(p_str) loop
  9                  l_num := l_num * p_from_base +
instr(l_hex,upper(substr(p_str,i,1)))-1;
 10          end loop;
 11          return l_num;
 12  end to_dec;
 13  /

Function created.

ops$tkyte@8i> show errors
No errors.
ops$tkyte@8i>
ops$tkyte@8i> select to_base( 1234567890, 26 ) from dual;

TO_BASE(1234567890,26)
-----------------------------------------------------------------
-----------------------------------
DZXPRWK

ops$tkyte@8i> select to_dec( to_base( 1234567890, 26 ), 26 )
from dual;

TO_DEC(TO_BASE(1234567890,26),26)
---------------------------------
                       1234567890

I just modified slightly my generic base conversion routines you
can find at

http://osi.oracle.com/~tkyte/hexdec/index.html
May 05, 2000 HAROON -- Thanks for the question regarding
      "Detect Duplicate records in a Pl/sql table", version

      You Asked
Hi ,
Any Ideas as to how to Detect Duplicate records in a Pl/sql table
of Records .
For example --
Declare
Type My_REC is RECORD
(v_rec1 number ,
v_rec2 varchar2) ;
Type MY_TABLE is Table of MY_REC index by binary integer ;
j pls_integer := 1 ;
BEgin
-- Populate the pl/sql table
--The requirement is given a loaded PL/sql --table of records
find the duplicate Records
--in it .Duplicates can be more than 1 .
for I in my_table.first..my_table.last loop
/* What to do here
any suggestions ?
*/
end loop ;

End ;

      and we said...
In this case, the brute force method is probably the best method.  It could be
something like:

ops$tkyte@8i> Declare
  2      Type My_REC is RECORD (v_rec1 number , v_rec2 varchar2(25) ) ;
  3
  4      Type MY_TABLE is Table of MY_REC index by binary_integer ;
  5
  6      tbl my_table;
  7
  8      function are_equal( x in my_rec, y in my_rec ) return boolean
  9      is
 10      begin
 11          return ( x.v_rec1 = y.v_rec1 OR (x.v_rec1 is null and y.v_rec1 is
NULL) ) AND
 12                 ( x.v_rec2 = y.v_rec2 OR (x.v_rec2 is null and y.v_rec2 is
NULL) );
 13      end;
 14
 15  BEgin
 16      for i in 1 .. 5 loop
 17          tbl(i).v_rec1 := i;
 18          tbl(i).v_rec2 := i;
 19      end loop;
 20      tbl(6).v_rec1 := 5;
 21      tbl(6).v_rec2 := 5;
 22
 23
 24      for i in 1 .. tbl.count-1 loop
 25          for j in i+1 .. tbl.count loop
 26              if ( are_equal( tbl(i), tbl(j) ) )
 27              then
 28                  dbms_output.put_line( 'Entry ' || i || ' and ' || j || '
are the same' );
 29              end if;
 30          end loop;
 31      end loop;
 32
 33  end;
 34  /
Entry 5 and 6 are the same

PL/SQL procedure successfully completed.

there is really no "easy" way to do this in Oracle7

In Oracle8.0 and up, you can do SQL on a new type of plsql variable -- the
nested table type.  It would look like this:

ops$tkyte@8i> create or replace type myScalarType as object
  2  ( x int, y varchar2(25) )
  3  /

Type created.

ops$tkyte@8i>
ops$tkyte@8i> create or replace type myTableType as table of myScalarType;
  2  /

Type created.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> declare
  2          tbl     myTableType := myTableType();
  3  begin
  4          for i in 1 .. 5 loop
  5                  tbl.extend;
  6                  tbl(i) := myScalarType( i, i );
  7          end loop;
  8          tbl.extend;
  9          tbl(6) := myScalarType( 5, 5 );
 10
 11          for x in ( select x, y, count(*)
 12                   from THE ( select cast( tbl as mytableType ) from dual ) a
 13                                  group by x, y
 14                             having count(*) > 1 )
 15          loop
 16                  dbms_output.put_line( 'the entry ' || x.x || ', ' || x.y ||
' is in there twice' );
 17          end loop;
 18  end;
 19  /
the entry 5, 5 is in there twice

PL/SQL procedure successfully completed.

May 05, 2000 Tushar -- Thanks for the question regarding
      "select multiple items in forms 4.5 LOVS", version

      You Asked
How can I select multiple items from either LOV or from
List Item in D2K forms 4.5 or D2K forms 5 ?
Or please tell me the utility by which I can select multiple
items .

      and we said...
the builtin LOV does not support >1 selection.

The way I've done this in the past is to create a modal dialog.
This dialog has 2 fields -- a database text field and a
non-database checkbox.  I do a go-block (brings up the dialog)
and an enter/execute query to populate.  the checkbox is empty
by default.  I then let people check/uncheck items.  When they
hit "OK" on this dialog -- I do a first_record/next_record loop
through the block finding all items they have check marked and
saving them.  Then I do a go block back to the block I was
formally in and a hide window

Hope that helps....

May 05, 2000 Joanne -- Thanks for the question regarding
      "using the SYSTEM account", version

      You Asked
We are a small company providing billing software to
approx 80 customers, on MS Access and MS SQL Server platforms
currently, adding Oracle in the next release.  App has approx
200
tables.  Just getting started.
Have made SYSTEM user the owner of the app tables, granting
select, insert, update, delete on each to a role, then granting
that role to each app user.
Should we create another user to own the tables, if so, why?
Thanks for any advice you can offer.  If there are resources
that
you are aware of that discusses this issue, please let me know
where to find...

      and we said...
You should not use either SYS or SYSTEM for anything.  These are
'special' Oracle users (especially SYS, more so then SYSTEM).
The attributes, priveleges, and characteristics of SYS and
SYSTEM can and will (and have) change over time -- possibly
affecting your application.

SYS and SYSTEM should only be used for Oracle supplied tables
and packages.

May 05, 2000 Venku Reddy -- Thanks for the question regarding
      "blank pages from OAS PLSQL cartridge.", version

      You Asked
This is specifically related to OWS PL/SQL Cartridge.
Iam using OWS 3.0 which is configured on Oracle 8.0.5. Iam
having
two DADS. one dad (User Schema)is having total set of packages
and procedures. it is working fine. I created the second dad and

second PL/SQL agent with set of PL/SQL tool kit procedures. I
created public synonyms for packages in first schema. When i am
accessing from browser using public synoyms iam getting
"content-text/html" no results are shown on browser. i given
execute privilage on the synonyms to the second user. My
question
is Can i use synonyms for packages for executing them through
pl/sql cartridge or not. I executed through SQL PLus they are
executing fine. Then i create the privite synonyms then also iam

not able to achive it. How to work around this problem.

      and we said...
This problem is due to the way the HTP package works.  You have
2 schemas, call them A and B.  A.HTP exists as does B.HTP.  A
procedure written in A will use the package A.HTP.  A package
written in B will use B.HTP.

The HTP package stores the page as it is written.  When you
access code written in A's schema using the DAD from B, the
procedures owned by A "write" to A.HTP -- but when the DAD
accessed from B goes to print the page it will tend to "read"
B.HTP.

the solution (which is implemented in OAS4.0 by default) is to
install AT MOST one copy of OWA, HTP, (etc -- the rest of the
toolkit packages) in a database.

What I do is:

- create a user (say OAS_PUBLIC - that is the name in OAS4.x)
- grant DBA to this user for a moment
- install the toolkit into this schema (drop ALL other copies in
the entire database)
- create public synonyms and grant execute on all packages
- REVOKE DBA from this user.

you now have a schema that cannot log in or do anything but it
owns all of the OWA, HTP, etc packages.  You will not have this
issue you describe above anymore.  Make sure you have in fact
dropped ALL other copies of HTP, OWA, etc....  The only package
you might install into other schemas might be OWA_UTIL as it
does some dynamic sql utilities -- but that would be it.

May 05, 2000 Ramana -- Thanks for the question regarding
      "Product_user_profile question", version

      You Asked
Hi,

I have a question about PRODUCT_USER_PROFILE.  My basic idea is
to disable 'DROP' command for user SYS.

I have inserted a row into PRODUCT_USER_PROFILE table using the
following statement:

insert into system.PRODUCT_USER_PROFILE
(product, userid,attribute,char_value)
values
('SQL*Plus','SYS','DROP','DISABLED');

The above statement got successfully executed and I am able to
select the above values also.

But, when I try the sample testing of
following commands from sqlplus:

create user dtemp identified by dtemp;
drop user dtemp;

!!! It goes thru.. The user is dropped to my surprise.

Even 'Create Table'.. 'Drop table' succeeds...

What could be the problem with above procedure?  Can't I disable

commands for
user SYS?

Please help.

Thanks
Ramana Damarla

      and we said...

You used to be able to in 7.3 and before.  Starting with 8.0,
SQL*Plus is positioned to become the replacement for svrmgrl
(command line interface) and as such will be used to run all
install scripts.  The disabling of commands for the SYS user is
not supported (the SYS user is special in many other ways as
well).

It would be a very bad idea to disable SYS commands in sqlplus.
It would be *much* better if no one used SYS on a day to day
basis.  Create appropriately priveleged users instead (you don't
even need to be sys to startup/shutdown anymore -- you can grant
SYSDBA and or SYSOPER to normal users for this).

May 05, 2000 meghna -- Thanks for the question regarding
      "deleting duplicate rows", version

      You Asked
write a select statment to delete the duplicate rows

      and we said...
delete from t
 where rowid <> ( select min(rowid) from t t2
                   where t2.primary_key_column1 =
t.primary_key_column1
                     and t2.primary_key_column2 =
t.primary_key_column2
                     ....
                     and t2.primary_key_columnN =
t.primary_key_columnN );

for example:

ops$tkyte@8i> create table t ( x int );
Table created.

ops$tkyte@8i> insert into t values (1);
ops$tkyte@8i> insert into t values (1);
ops$tkyte@8i> insert into t values (2);
ops$tkyte@8i> insert into t values (3);
ops$tkyte@8i> insert into t values (3);
ops$tkyte@8i> insert into t values (3);
ops$tkyte@8i> insert into t values (3);

ops$tkyte@8i> delete from t where rowid <> ( select min(rowid)
from t t2 where t2.x = t.x );
4 rows deleted.

ops$tkyte@8i> select * from t;

         X
----------
         1
         2
         3

May 05, 2000 Vinayak -- Thanks for the question regarding
      "changing the default date format.", version

      You Asked
I have a problem of getting sysdate in the proper
format dd-mon-yyyy
when i give the command
select sysdate from dual;
i get the dat in the format dd-mon-yy
i want it in dd-mon-yyyy
i tried alter session ---it works
but i want it to be permanent
i changed NLS_DATE_FORMAT parameter in the init.ora file - no
use
I read that once i set NLS_PARAMETERS in init.ora i before the
database is created i can not change them later
i tried changing them in the init.ora before db-creation --no
use
Let me tell u what i did
i have changed only nls_date_format
there are no entries for any other nls_ parameters

I don't know what to do next

Please tell me how to do it

(i am worried more about the answer . so even if u feel this is
a
dumb question PLEASE ANSWER)
thanx in advance

      and we said...
The best way is the explicit way.  On queries, use:

select to_char( sysdate, 'dd-mon-yyyy' ) ....

on inserts/updates use

set date_col = to_date( :date_string, 'dd-mon-yyyy' );

Also, you might consider RRRR instead of YYYY.  YYYY will allow
people to input "99".  that'll be the YEAR 99 (perfectly valid).
 If you use RRRR, that'll be the year 1999.

You can set an INIT.ORA parameter -- AS LONG AS the client
doesn't set ANY nls_ parameters (i'll bet your database is Unix
and your client is NT) or with Oracle8i use an LOGON trigger --
see
http://osi.oracle.com/~tkyte/Misc/NLSDateFormat.html
for more info on that.

May 05, 2000 Sampangi -- Thanks for the question regarding
      "Hit counter in plsql cartridge", version

      You Asked
In oracle application server 8.0.5, How can I get the
web page hit counter, using PL/SQL catridge.  Can I have source
code, If available.
2) How can I run my javaservlet on Oracle Application server.

I request you to please give tips on above questions.

      and we said...
hit counter it easy.

o create a sequence:

create sequence my_counter NOCACHE;

Then, your hit counter is simplye:

  for x in ( select my_counter.nextval cnt from dual ) loop
     htp.p( 'Welcome, this is the ' || x.cnt || ' time
someone''s been here' );
  end loop;

The nocache will prevent gaps when you shutdown (otherwise it
might skip upto 19 values by default since the default cache
size is 20).  This is highly concurrent (no blocking) and if you
can afford to lose a couple when you shutdown (if you get 10's
of thousands of hits, does overcounting by 19 when you shutdown
once a month really mean anything?), use the cache option.

For jservlets, see
http://www.olab.com/doc/oin/i_all.htm#jserv
May 05, 2000 ted -- Thanks for the question regarding "foreign
      keys and indexes", version

      You Asked
thomas,
emp table has fk deptno from dept table.
deptno fk field in emp table is not indexed.
If you update emp table on deptno, I would
expect the parent table dept is locked. I did
some test and did not find that is the case.
here is my result.
SQL> select * from user_constraints where table_name='EMP'
2  and constraint_type='R'
3  /

OWNER                          CONSTRAINT_NAME                C
TABLE_NAME
------------------------------ ------------------------------ -
------------------------------
SEARCH_CONDITION
-----------------------------------------------------------------
-
--------------
R_OWNER                        R_CONSTRAINT_NAME
DELETE_RU STATUS   DEFERRABLE
------------------------------ ------------------------------
--------- -------- --------------
DEFERRED  VALIDATED     GENERATED      BAD RELY LAST_CHANGE
--------- ------------- -------------- --- ---- -----------
SCOTT                          FK_DEPTNO                      R
EMP

SCOTT                          PK_DEPT                        NO

ACTION ENABLED  NOT DEFERRABLE
IMMEDIATE VALIDATED     USER NAME               01-MAR-1999

SQL> select index_name from dba_indexes where table_name='EMP';

INDEX_NAME
------------------------------
PK_EMP

SQL> update emp set deptno=10 where deptno=40;

3 rows updated.

SQL> select * from v$lock;

ADDR     KADDR          SID TY       ID1       ID2     LMODE
REQUEST     CTIME     BLOCK
-------- -------- --------- -- --------- --------- ---------
--------- --------- ---------
03E3B688 03E3B698         2 MR         6         0         4

0         0         0
03E3B610 03E3B620         2 MR         1         0         4

0         0         0
03E3B5D4 03E3B5E4         2 MR         2         0         4

0         0         0
03E3B598 03E3B5A8         2 MR         3         0         4

0         0         0
03E3B55C 03E3B56C         2 MR         4         0         4

0         0         0
03E3B520 03E3B530         2 MR         5         0         4

0         0         0
03E3B6C4 03E3B6D4         3 RT         1         0         6

0         0         0
095689B4 09568A88        10 TX    720897      2778         6

0       375         0
0409D6D8 0409D6EC        10 TM     10922         0         3

0       427         0

9 rows selected.
##### why parent table dept is not locked ???
SQL> select object_name from user_objects where object_id=10922;

OBJECT_NAME
-----------------------------------------------------------------
-
----------------------------------
EMP

      and we said...
see
http://osi.oracle.com/~tkyte/unindex/index.html
for some more info but...

The **child table** is the table that would get locked if you
UPDATE the parents primary key OR DELETE a row in the parent
table.

In your case above, the parent table HAS an index on DEPTNO (has
too for the fkey to work at all) so there would be no need to
lock the parent table.

May 05, 2000 Ashish -- Thanks for the question regarding
      "shoud I use char or varchar2", version

      You Asked
I have a database column that shall store data always
10 characters long. Which datatype should I use for it CHAR or
VARCHAR2 and What is the specific reason for using that datatype
?

      and we said...
A CHAR datatype and VARCHAR2 datatype are stored identically
(eg: the word 'WORD' stored in a CHAR(4) and a varchar2(4)
consume exactly the same amount of space on disk, both have
leading byte counts).

The difference between a CHAR and a VARCHAR is that a CHAR(n)
will ALWAYS be N bytes long, it will be blank padded upon insert
to ensure this.  A varchar2(n) on the other hand will be 1 to N
bytes long, it will NOT be blank padded.

Using a CHAR on a varying width field can be a pain due to the
search semantics of CHAR.  Consider the following examples:

ops$tkyte@8i> create table t ( x char(10) );
Table created.

ops$tkyte@8i> insert into t values ( 'Hello' );
1 row created.

ops$tkyte@8i> select * from t where x = 'Hello';

X
----------
Hello

ops$tkyte@8i> variable y varchar2(25)
ops$tkyte@8i> exec :y := 'Hello'
PL/SQL procedure successfully completed.

ops$tkyte@8i> select * from t where x = :y;
no rows selected

ops$tkyte@8i> select * from t where x = rpad(:y,10);

X
----------
Hello

Notice how when doing the search with a varchar2 variable
(almost every tool in the world uses this type), we have to
rpad() it to get a hit.

If the field is in fact ALWAYS 10 bytes long, using a CHAR will
not hurt -- HOWEVER, it will not help either.

The only time I personally use a CHAR type is for CHAR(1).  And
that is only because its faster to type char(1) then varchar2(1)
-- it offers no advantages.

Review &
      Followup

      Rating: 5
Use of CHAR vs.
      VARCHAR2  August 08, 2001
Reviewer:  Lynn
      Hopkins  from Philadelphia, PA
Exactly the information I was looking for.

      Rating: 5
shoud I use
      char or varchar2  February 03, 2003
Reviewer:
      A reader

      Rating:
      5
  December 01, 2003
Reviewer:
      A reader

      Rating:
      5
reader  December 29, 2003
Reviewer:
      A reader

May 05, 2000 Suzanne -- Thanks for the question regarding "In
      Oracle Designer 2000 how can I attach the menu of my choice", version

      You Asked
In Oracle Designer 2000 how can I attach the menu of my
choice to a generated form rather than letting Oracle
automatically attach a default menu?

      and we said...
Go into the Design Editor.

Click on the Modules tab.

Right click on the Forms module whose menu you want to set, and
select 'Edit
Generator Preferences'.

In the Preferences Palette, expand the Form/Menu Attachment
node.

The preference you need to set will be either 'FMNDMA' or 'Name
of menu
module if not implicit menu generation'. You can control the
display of
preference names (short or long) by clicking on the 'A' icon on
the
Preferences palette toolbar.

Set this property to the file name of your menu. You do not need
to add the
.mmx suffix.

Note: the .mmx file must already exist (e.g., it must have
already been
generated) and it must be on your FORMS60_PATH.

May 05, 2000 Sampangi -- Thanks for the question regarding
      "RE: Ask Tom Submission", version

      You Asked
In oracle application server 8.0.5, How can I get the
web page hit counter, using PL/SQL catridge.  Can I have source
code, If available.
2) How can I run my javaservlet on Oracle Application server.

I request you to please give tips on above questions.

      and we said...
hit counter it easy.

o create a sequence:

create sequence my_counter NOCACHE;

Then, your hit counter is simplye:

  for x in ( select my_counter.nextval cnt from dual ) loop
     htp.p( 'Welcome, this is the ' || x.cnt || ' time
someone''s been here' );
  end loop;

The nocache will prevent gaps when you shutdown (otherwise it
might skip upto 19 values by default since the default cache
size is 20).  This is highly concurrent (no blocking) and if you
can afford to lose a couple when you shutdown (if you get 10's
of thousands of hits, does overcounting by 19 when you shutdown
once a month really mean anything?), use the cache option.

For jservlets, see
http://www.olab.com/doc/oin/i_all.htm#jserv

--
Thanks,

    Thomas Kyte                          tkyte@us.oracle.com
    Oracle Service Industries

    Oracle tips and papers
http://www.oracle.com/oramag/code/index.html

May 05, 2000 Zhuo -- Thanks for the question regarding "free
      space in database", version

      You Asked
Tom:
Thank you for your advice for my last question.
Today I have some question,too.
How much space has the database used?(or how much space will
the datebase be left?)

      and we said...
run a script like this:

<quote>
-----------------------------------------------------------------
-------------
-- free.sql
--
-- This SQL Plus script lists freespace by tablespace
-----------------------------------------------------------------
-------------

column dummy noprint
column  pct_used format 999.9       heading "%|Used"
column  name    format a16      heading "Tablespace Name"
column  Kbytes   format 999,999,999    heading "KBytes"
column  used    format 999,999,999   heading "Used"
column  free    format 999,999,999  heading "Free"
column  largest    format 999,999,999  heading "Largest"
break   on report
compute sum of kbytes on report
compute sum of free on report
compute sum of used on report

select nvl(b.tablespace_name,nvl(a.tablespace_name,'UNKOWN'))
name,
       kbytes_alloc kbytes,
       kbytes_alloc-nvl(kbytes_free,0) used,
       nvl(kbytes_free,0) free,
       ((kbytes_alloc-nvl(kbytes_free,0))/kbytes_alloc)*100
pct_used,
       nvl(largest,0) largest
from ( select sum(bytes)/1024 Kbytes_free,
              max(bytes)/1024 largest,
              tablespace_name
       from  sys.dba_free_space
       group by tablespace_name ) a,
     ( select sum(bytes)/1024 Kbytes_alloc,
              tablespace_name
       from sys.dba_data_files
       group by tablespace_name )b
where a.tablespace_name (+) = b.tablespace_name
order by &1
/
</quote>

In sqlplus.  It'll show use by tablespace & database the amount
of space ALLOCATED, the amount USED and by tablespace the
LARGEST CONTIGOUS FREE chunk of space (the max size of a next
extent in that tablespace).

May 05, 2000 Michelle -- Thanks for the question regarding
      "String concatenation", version

      You Asked
How do I concatenated two columns into one? In my book
the line to do this is vertical and I'm not sure how to type
that?  thanks Mickey

      and we said...
the 2 vertical bars (also known as pipes, the same thing you
would use at a command line to pipe the output of one process
into another) can be used to concatenate strings.  On my
keyboard, it is above the backslash, on other keyboards, its
above one of the numeric keys.  It varies.

In any case, you don't have to use the pipes, you can:

scott@8i> select concat( 'a', 'b' ) y from dual
  2  /

Y
--
ab

instead of

scott@8i> select 'a' || 'b' y from dual;

Y
--
ab

May 05, 2000 Kimberly -- Thanks for the question regarding
      "how long as someone been idle", version

      You Asked
I need to find out Oracle users who have
been inactive for 30 minutes or more, so I can
kill them.  Any ideas how to do this?

thanks.

      and we said...
Have you looked at resource profiles?  resource profiles are
setup to do exactly this.  You can set a maximum connect idle
time.  The sessions will be marked for kill when they exceed
this limit.

In 7.3 and up, you can get this out of v$session:

ops$tkyte@8i> select sid,
  2             username,
  3             status,
  4             to_char(logon_time,'dd-mm-yy hh:mi:ss') "LOGON",
  5         floor(last_call_et/3600)||':'||
  6
to_char(floor(mod(last_call_et,3600)/60),'fm00')||':'||
  7            to_char(mod(mod(last_call_et,3600),60),'fm00')
"IDLE",
  8             program
  9    from v$session
 10   where type='USER'
 11   order by last_call_et
 12  /

       SID USERNAME        STATUS     LOGON             IDLE
  PROGRAM
---------- --------------- ---------- -----------------
---------- -------------------------
       119 OPS$TKYTE       ACTIVE     28-02-00 02:12:15 0:00:00
  sqlplus@aria (TNS V1-V3)
        89 WEB$LALBRIGH    ACTIVE     28-02-00 02:29:46 0:00:02
  wrb21@aria (TNS V1-V3)
        54 WEB$JGEMMELL    ACTIVE     28-02-00 02:29:44 0:00:03
  wrb21@aria (TNS V1-V3)
        57 SCOTT           INACTIVE   28-02-00 02:19:25 0:09:10
  sqlplus@aria (TNS V1-V3)
       110 OPS$CLBECK      INACTIVE   28-02-00 02:03:22 0:23:10
  sqlplus@aria (TNS V1-V3)
       101 HOTEL           INACTIVE   28-02-00 01:45:44 0:24:01
  sqlplus@aria (TNS V1-V3)
        88 REVIEW          INACTIVE   28-02-00 08:38:16 5:42:45
  sqlplus@aria (TNS V1-V3)

--
Thanks,

    Thomas Kyte                          tkyte@us.oracle.com
    Oracle Service Industries

    Oracle tips and papers
http://www.oracle.com/oramag/code/index.html

Review &
      Followup

      Rating: 5
idel
      time  August 16, 2002
Reviewer:  Mo
       from Reston, USA
Tom:

How do you do this in 8i?

Thanks

May 05, 2000 Praveen -- Thanks for the question regarding
      "starting database from comand line in NT", version

      You Asked
How I start two oracle databases(oracle 8i) in Windows
NT Server /Workstation ?
One option is to through Windows NT Services ,but suppose I want
to
start through Oracle Server Manager(svrmgrl)..is it possible ?
Here I can start one Oracle Database ..but when I try to start
the second one ,I'm getting an error message like this "Cannot
start already - running oracle - shut it down first" how can I
over come this problem ?
Here I want to implement Standby database ..for testing purpose

I configured both in One Machine with different drives ..

Thanks
Praveen

      and we said...
You need to verify your Oracle_Home and Oracle_Sid are set
correctly.  The easiest way to start the database from the
command line is via the service -- I use

c:\> net start OracleServiceORA8Int

for example to start my database from the command line.  It
ensures the database is started correctly under NT.  Depending
on the exact version of Oracle -- there may be 2 services that
must be run in order to start the database.

I would recommend using the service to start the database if
possible.  You can do it right from the command line or a cmd
script as well as the GUI.

May 05, 2000 Venku Reddy -- Thanks for the question regarding
      "Can I get the dependency and hierarchy of calling procedures", version

      You Asked
Can I get the dependency and hierarchy of calling
procedures in packages from database? If so  how?

      and we said...
dependencies are tracked at the Object Level in Oracle.
Packages are objects (but not the procedures within), standalone
stored procedures and functions are objects.  You can see which
packages are dependent on what packages (whom references whom)
but you cannot see that package.procedure1 calls
package2.procedure3.

the dependencies we track are visible in the *_DEPENDENCIES
views.

May 05, 2000 anthony -- Thanks for the question regarding "how
      to attach a help file typed in MS word to any key/button in forms",
      version

      You Asked
 I am developing an application Using D2K. Could you
advice me how to attach a help file typed in MS word to any key
or button?

      and we said...
you could use OLE to embed the word file right into your form if
you wanted.  You could even save the word documents into the
database -- you could have a table:

HELP_TAB ( topic varchar2(255), doc long raw );

and store the word documents as OLE containers in there.  Then,
when something hits a help key, you would

o go block "help block" ( a block you built on this help_tab
table)
o enter query
o :help_block.topic := 'that topic'
o execute query

to see in your form that information.

A quick and dirty solution would be just to:

host( help_topic || '.doc' );

to run word as an external application.

May 05, 2000 Derek -- Thanks for the question regarding "How
      can I trap the oracle errors from csh", version

      You Asked
I have a c shell scrip to run every night to do some
table update. How can I trap the oracle errors if they occur?

      and we said...
Well, I wouldn't use a csh script for starters.  I would write a
stored procedure and then use dbms_job to schedule it.  That way
-- I'm in the database (if it isn't up, i won't try to run until
it is -- if it crashes, it'll restart me -- if I fail, an error
gets logged to the alert and the DBA knows -- if i'm moved to NT
without cron and csh, I'll be ok and so on)....

I suppose you are using sqlplus in the sh.  You can do something
like this:

#!/bin/csh -f

sqlplus scott/tiger <<EOF
whenever sqlerror exit 1
select * from dual
/
exit
EOF

set rc = $status

if ( $rc != "0" ) then
    echo TEST failed
else
    echo TEST succeeded
endif
echo ===================================

sqlplus scott/tigerX <<EOF

whenever sqlerror exit 1
select * from dual
/
exit
EOF

set rc = $status

if ( $rc != "0" ) then
    echo TEST failed
else
    echo TEST succeeded
endif
echo ===================================

sqlplus scott/tiger <<EOF

whenever sqlerror exit 1
declare
    x   number;
begin
    select dummy into x from dual where 1=0;
end;
/
exit
EOF

set rc = $status

if ( $rc != "0" ) then
    echo TEST failed
else
    echo TEST succeeded
endif
echo ===================================

================================================================

When you run this it'll print

suceedded for test1
failed for test2 (password invalid)
failed for test3 (logic error the plsql block flings an
exception)

In all cases the csh script can catch that.

May 05, 2000 Mahomed -- Thanks for the question regarding
      "disable redo", version

      You Asked
I am using Oracle 7.3.4 with archive mode on.
Is there any way of disabling logging for a particular table.
I do not want any redo created for any insertions, additions
deletions from theis table.

      and we said...
In general -- no.

Certain operations, such as direct path loads, direct path
inserts (bulk inserts of many rows), and truncate (deletion of
all rows) can be done in an unrecoverable fashion.

All normal inserts, updates, and deletes must be logged.

May 05, 2000 Ravinder -- Thanks for the question regarding
      "running sql.bsq two times.", version

      You Asked
Hi Tom,

There is a very stupid question for you, but it is very much
scary and my question is why this happens ????

Question:

After creating a new database, if someone runs sql.bsq again on
SVRMGRL prompt. Oracle behaves abnormally. for example, if I
create a user and inquire it will show me two users. Similarly
it
shows every thing double.

I know sql.bsq should not be run, since it is called by oracle
it
self when we give the create database command. But if a new DBA
runs this file again, then why why why oracle behaves
abnormally.
Is it a bug or ?????.

Thanks

Ravinder Singh

      and we said...
It is not a bug -- it is an error on your part.  If a 'new DBA'
runs this, then they are not yet a DBA ;)

The exact cause of the duplicate users is easy to trace.
Looking at the 8.0.6 DBA_USERS view, we see it is:

select u.name, u.user#, u.password,
       m.status,
       decode(u.astatus, 4, u.ltime,
                         5, u.ltime,
                         6, u.ltime,
                         8, u.ltime,
                         9, u.ltime,
                         10, u.ltime, to_date(NULL)),
       decode(u.astatus,
              1, u.exptime,
              2, u.exptime,
              5, u.exptime,
              6, u.exptime,
              9, u.exptime,
              10, u.exptime,
              decode(u.ptime, '', to_date(NULL),
                decode(pr.limit#, 2147483647, to_date(NULL),
                 decode(pr.limit#, 0,
                   decode(dp.limit#, 2147483647, to_date(NULL),
u.ptime +
                     dp.limit#/86400),
                   u.ptime + pr.limit#/86400)))),
       dts.name, tts.name, u.ctime, p.name, u.ext_username
       from sys.user$ u, sys.ts$ dts, sys.ts$ tts, sys.profname$
p,
            sys.user_astatus_map m, sys.profile$ pr,
sys.profile$ dp
       where u.datats# = dts.ts#
       and u.resource$ = p.profile#
       and u.tempts# = tts.ts#
       and u.astatus = m.status#
       and u.type# = 1
       and u.resource$ = pr.profile#
       and dp.profile# = 0
       and dp.type#=1
       and dp.resource#=1
       and pr.type# = 1
       and pr.resource# = 1;

One of the tables that references:

create table user_astatus_map
( status#  number not null,
  status  varchar2(32) not null)
/

is small and totally unindexed (no unique constraints).  We put
into that:

insert into user_astatus_map values (0, 'OPEN');
insert into user_astatus_map values (1, 'EXPIRED');
insert into user_astatus_map values (2, 'EXPIRED(GRACE)');
insert into user_astatus_map values (4, 'LOCKED(TIMED)');
insert into user_astatus_map values (8, 'LOCKED');
insert into user_astatus_map values (5, 'EXPIRED &
LOCKED(TIMED)');
insert into user_astatus_map values (6, 'EXPIRED(GRACE) &
LOCKED(TIMED)');
insert into user_astatus_map values (9, 'EXPIRED & LOCKED');
insert into user_astatus_map values (10, 'EXPIRED(GRACE) &
LOCKED')
/

you'll find if you run it (sql.bsq) two times -- it puts 2 rows
into this table, thus duping every row that joins to it.

It is not a bug, it is something that should never be done.  You
have corrupted the sys data dictionary, I would not trust that
database to be "OK"

May 05, 2000 Michelle -- Thanks for the question regarding
      "grouping by WEEK", version

      You Asked
Given table A with primary keys including a number
(amount) and a date column, with every day represented by at
least 1 record. If I want to get the total amount for each day,
I
just do this: SELECT SUM(amount) FROM A GROUP BY date_column; I
was also able to do the query for each month. My question is,
what if I want to get the total amount for every week, say first

day of the week (Sunday), in one SELECT statement? The only way
I
thought of is to select the sum for a hardcoded date, which is
the computed first-day-of-the-week date based on a counter
inside
a loop, and then increment the counter for the next
first-day-of-the-week date. This is obviously slow. Please tell
me if I have to stick with this, if what I'm asking for is
impossible. Thanks!

      and we said...
Does this work for you:

select trunc(date_column,'w'), sum(amount)
  from A
 group by trunc(date_column,'w')
/

or maybe:

select next_day( date_column-7 , 'Sun' ), sum(amount)
  from A
 group by next_day( date_column-7 , 'Sun' )
/

The trunc of a date to 'w', truncates the date to the first day
of the 'week' in the month.  So for feburary, trunc('w') would
be:

tkyte@ORA734.WORLD> select theDate, trunc(theDate,'w')
  2    from ( select to_date('01-feb-00')+rownum-1 theDate
  3             from all_objects where rownum <= 29 )
  4  /

THEDATE   TRUNC(THE
--------- ---------
01-FEB-00 01-FEB-00
02-FEB-00 01-FEB-00
03-FEB-00 01-FEB-00
04-FEB-00 01-FEB-00
05-FEB-00 01-FEB-00
06-FEB-00 01-FEB-00
07-FEB-00 01-FEB-00
08-FEB-00 08-FEB-00
09-FEB-00 08-FEB-00
10-FEB-00 08-FEB-00
11-FEB-00 08-FEB-00
12-FEB-00 08-FEB-00
13-FEB-00 08-FEB-00
14-FEB-00 08-FEB-00
15-FEB-00 15-FEB-00
16-FEB-00 15-FEB-00
17-FEB-00 15-FEB-00
18-FEB-00 15-FEB-00
19-FEB-00 15-FEB-00
20-FEB-00 15-FEB-00
21-FEB-00 15-FEB-00
22-FEB-00 22-FEB-00
23-FEB-00 22-FEB-00
24-FEB-00 22-FEB-00
25-FEB-00 22-FEB-00
26-FEB-00 22-FEB-00
27-FEB-00 22-FEB-00
28-FEB-00 22-FEB-00
29-FEB-00 29-FEB-00

29 rows selected.

tkyte@ORA734.WORLD> !cal
   February 2000
 S  M Tu  W Th  F  S
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29

An alternative would be to group by weeks that are based on
sunday's (eg: "trunc" each date to the previous sunday).  for
example:

tkyte@ORA734.WORLD> select theDate, next_day( theDate-7 , 'Sun'
)
  2    from ( select to_date('01-feb-00')+rownum-1 theDate
  3             from all_objects where rownum <= 29 )
  4  /

THEDATE   NEXT_DAY(
--------- ---------
01-FEB-00 30-JAN-00
02-FEB-00 30-JAN-00
03-FEB-00 30-JAN-00
04-FEB-00 30-JAN-00
05-FEB-00 30-JAN-00
06-FEB-00 06-FEB-00
07-FEB-00 06-FEB-00
08-FEB-00 06-FEB-00
09-FEB-00 06-FEB-00
10-FEB-00 06-FEB-00
11-FEB-00 06-FEB-00
12-FEB-00 06-FEB-00
13-FEB-00 13-FEB-00
14-FEB-00 13-FEB-00
15-FEB-00 13-FEB-00
16-FEB-00 13-FEB-00
17-FEB-00 13-FEB-00
18-FEB-00 13-FEB-00
19-FEB-00 13-FEB-00
20-FEB-00 20-FEB-00
21-FEB-00 20-FEB-00
22-FEB-00 20-FEB-00
23-FEB-00 20-FEB-00
24-FEB-00 20-FEB-00
25-FEB-00 20-FEB-00
26-FEB-00 20-FEB-00
27-FEB-00 27-FEB-00
28-FEB-00 27-FEB-00
29-FEB-00 27-FEB-00

29 rows selected.

Review &
      Followup

      Rating:
      5
  April 05, 2003
Reviewer:  Phil
      Singer  from Brighton, MI USA
I had exactly the same question, and was going down the wrong path.

May 05, 2000 vikas -- Thanks for the question regarding "using
      dbms_lob.read and write", version

      You Asked
1.Can you tell me how to use the
DBMS_LOBS.READ and DBMS_LOBS.WRITE
package as if we have to insert and
retrive a document (as CLOB ) or image
(as BLOB) of size in megha bytes.As
every time the buffer size is  a
constraint and also while using these
package the variable of type varchar2
( eg. buffer_var) which stores the data
temperory is not taking  more then 2kb.

2.How to implement the UTF-8 character
set technique for storing data in more
then  one languages as it was not clear
from the document provided by ORACLE8i.
By using this character set do we need
NCLOB to store the data if in multibyte
form.

I will be replicating  the whole
data through snapshots, which I am
storing in form of images and documents
( in many languages ).

      and we said...
What is the API you are using -- typically it is the
constraining factor.  PLSQL limits a varchar2 or raw to be 32k
max in a variable (so you can read/write 32k at a time).

For example, here is an example in Java that writes a blob
32,000 bytes at a time:

import java.sql.*;
import java.io.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;

class test {

public static void main (String args []) throws SQLException ,
FileNotFoundException, IOException
{
    DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());

    Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@aria:1521:ora8i",
"scott", "tiger");

    conn.setAutoCommit(false);
    Statement stmt = conn.createStatement();
    stmt.execute( "delete from demo" );
    System.out.println( "deleted from demo" );

    stmt.execute( "insert into demo (id,theBlob) values
(1,empty_blob())" );
    System.out.println( "inserted into demo" );

    conn.commit();
    System.out.println( "committed" );

    ResultSet rset = stmt.executeQuery ("SELECT theBlob FROM
demo where id = 1 FOR UPDATE");
    System.out.println( "Executed Query" );

    if(rset.next())
    {
        System.out.println( "Fetched row " );

        BLOB l_mapBLOB = ((OracleResultSet)rset).getBLOB(1);

        File binaryFile = new File("/tmp/binary.dat");
        FileInputStream instream=new
FileInputStream(binaryFile);

        int chunk = 32000;

        System.out.println( "Chunk = "+ chunk );

        byte[] l_buffer = new byte[chunk];

        int l_nread = 0;

        OracleCallableStatement cstmt =
            (OracleCallableStatement)conn.prepareCall( "begin
dbms_lob.writeappend( :1, :2, :3 ); end;" );

        cstmt.registerOutParameter( 1, OracleTypes.BLOB );
        while ((l_nread= instream.read(l_buffer)) != -1) // read
from file
        {
            cstmt.setBLOB(  1, l_mapBLOB );
            cstmt.setInt(   2, l_nread );
            cstmt.setBytes( 3, l_buffer );

            cstmt.executeUpdate();

            l_mapBLOB = cstmt.getBLOB(1);
        }
        instream.close();

        conn.commit();
        rset.close();
        stmt.close();

      }
}

}

If you have 8.0, you'll have to use dbms_lob.write NOT
dbms_lob.writeappend (or write your own lob append routine,
might be easier).  This sets the write chunksize to almost 32k
(biggest we can do in the thin driver or whenever we use
PL/SQL).....

To support UTF-8, you require a database that was created with
the UTF-8 characterset.
You should create your database using the UTF-8 character set.

Using UTF-8, you could have one client accessing the database
in English with NLS_LANG set to American_America.US7ASCII and
another client accessing the database with an NLS_LANG value
of Japanese_Japan.JA16SJIS.  A database character set of
UTF-8 will be able to accomodate both of these client character
sets, and with minimal overhead.

For more information and other character set considerations,
please see Chapter 3 of the Oracle8i National Language Support
Guide, available online at:

http://technet.oracle.com/doc/server.815/a67789/toc.htm

May 05, 2000 BELBAHRI -- Thanks for the question regarding
      "sqlldr and loading date/time", version

      You Asked
salut,
I'm using SQL LOADER to load data from flat file to oracle tables.
in my flat file i have a caracter string
like(Timestamps) '2000-02-23-15.15.15.573961', how can i convert
it to a date format.

thanks.

      and we said...
One method:

LOAD DATA
INFILE *
INTO TABLE T
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(deptno,
 datefield "to_date( substr( :datefield, 1, 19 ), 'yyyy-mm-dd-hh24.mi.ss' )"
)
BEGINDATA
12,2000-02-23-15.15.15.573961

you will not be able to convert the .573961 component of the time as Oracle
dates goto the second only.

May 05, 2000 Carol -- Thanks for the question regarding "copy
      passwords from one instance to another", version

      You Asked
Tom,

I have a test instance that I imported from
production.  I did a full import. Now I currently
have the production roles and passwords. I know how
to reset the roles and privileges to mirror
the old test instance.  How can I reset
the passwords in this test instance
to the original state?

      and we said...
if by "reset the passwords to the original state" you mean

How can i put the passwords in the test instance back to what
they were before I did the import

Then the answer is, you cannot -- unless you saved the contents
of the dba_users view from the test instance BEFORE you did the
import.  If you did not save this -- those passwords are lost.

If you have that table (if you had copied that view to a temp
table somewhere), you could issue:

alter user USERNAME identified by values 'ENCODED PASSWORD FROM
COPY OF DBA_USERS';

to reset the passwords back to what they where.

May 05, 2000 Thomas -- Thanks for the question regarding "how
      to determine what columns are modified in a trigger.", version

      You Asked
Hi Tom!

Does it exist a function (or something) I can use in a trigger
to
identify which columns that have been updatet on the table?

I can use: IF updatet ('col1') then...
but then I have to know the columnname.

Cheers!
Thomas

      and we said...
the function is called UPDATING.

ops$tkyte@dev8i> create table t ( a int, b int, c int );
Table created.

ops$tkyte@dev8i> create or replace trigger t_trigger
  2  before update on t
  3  for each row
  4  begin
  5          if ( updating( 'A' ) ) then
  6                  dbms_output.put_line( 'update a' );
  7          end if;
  8          if ( updating( 'B' ) ) then
  9                  dbms_output.put_line( 'update b' );
 10          end if;
 11          if ( updating( 'C' ) ) then
 12                  dbms_output.put_line( 'update c' );
 13          end if;
 14  end;
 15  /
Trigger created.

ops$tkyte@dev8i> insert into t values ( 1,1, 1 );
1 row created.

ops$tkyte@dev8i> update t set a = 1;
update a
1 row updated.

ops$tkyte@dev8i> update t set b = 1;
update b
1 row updated.

ops$tkyte@dev8i> update t set c = 1;
update c
1 row updated.

ops$tkyte@dev8i> update t set b = 1, c = 1;
update b
update c
1 row updated.

ops$tkyte@dev8i> update t set a = 1, b = 1;
update a
update b
1 row updated.

ops$tkyte@dev8i> update t set a = 1, c = 1;
update a
update c
1 row updated.

ops$tkyte@dev8i> update t set a = 1, b = 1, c = 1;
update a
update b
update c
1 row updated.

May 05, 2000 -- Thanks for the question regarding "passing a
      plsql table over a database link", version

      You Asked
-----Original Message-----
From: Ranjan Tripathy [mailto:ran_jan@hotmail.com]
Sent: Tuesday, February 22, 2000 2:06 PM
To: tkyte@us.oracle.com
Subject: Another Question

Hi Tom

Thanks for your solution. I have another question to ask you.

I have a pl/sql table of scalartype e:g
type t_table is table of varchar2(50) index by binary integer.

I want to call a procedure over database link where this table
is
passed as
a parameter.
e:g  x_ret:=pak_name.proc_name@dblink_name(t_table);
where inside the remote procedure this pl/sql table is used as a
OUT
variable.
proc_name(t_table OUT)

Now the QUESTION IS

IS IT POSSIBLE TO MAKE A DYNAMIC SQL TO ACHIEVE THE ABOVE.
in summary is it possible to pass a pl/sql table of scalar type
as parameter
in dynamic sql.

Thanks in advance.

Ranjan

______________________________________________________
Get Your Private, Free Email at
http://www.hotmail.com/

      and we said...
Yes (and no).  Yes you can but you must do it in a special way.
You will not BIND the plsql table (dbms_sql does not understand
binding of plsql tables, database link or no database link).
You will use a PACKAGE GLOBAL variable declared in a spec.

Lets say you have this code at the remote database:

create or replace package demo1_pkg
as
    type myTableType is table of varchar2(25) index by
binary_integer;

    procedure do_something( p_table out myTableType );
end;
/

create or replace package body demo1_pkg
as

procedure do_something ( p_table out myTableType )
is
begin
    for i in 1 .. 10 loop
        p_table(i) := 'line ' || i;
    end loop;
end;

end;
/

IT MUST be the owner of the TYPE (the remote database).  We must
use that type elsewhere.

In the 'local' database you have a package:

create or replace package demo2_pkg
as
    g_myTable demo1_pkg.myTableType@oracle8.world;
end;
/

Notice how I use the database link in the type above -- we are
using the SAME type borrowed from the remote site.  Now I can
statically invoke the procedure as such:

begin
    demo1_pkg.do_something@oracle8.world( demo2_pkg.g_myTable );

    for i in 1 .. demo2_pkg.g_myTable.count loop
        dbms_output.put_line( demo2_pkg.g_myTable(i) );
    end loop;
end;
/

and that is straight forward.  To see how to dynamically do it,
we will:

create or replace procedure execute_immediate( p_sql in varchar2
)
is
    cursor_name     pls_integer default dbms_sql.open_cursor;
    ignore          pls_integer;
BEGIN
    dbms_sql.parse(cursor_name, p_sql, dbms_sql.native);
    ignore := dbms_sql.execute(cursor_name);
    dbms_sql.close_cursor(cursor_name);
END;
/

declare
    empty_table demo1_pkg.myTableType@oracle8.world;
begin
    demo2_pkg.g_myTable := empty_table;

    execute_immediate( 'begin
demo1_pkg.do_something@oracle8.world( demo2_pkg.g_myTable );
end;' );
    for i in 1 .. demo2_pkg.g_myTable.count loop
        dbms_output.put_line( demo2_pkg.g_myTable(i) );
    end loop;
end;
/

Notice that instead of trying to BIND a table -- we just
reference a global package variable.  That does the 'binding'
for us.

May 05, 2000 Casey -- Thanks for the question regarding "using
      & in sqlplus", version

      You Asked
Is there an escape character or something I can use so
I can insert an '&' (ampersand) into a field without getting
prompted for a value?

      and we said...

I assume you are using SQLPlus.  By default, the macro
definition character in sqlplus is an &.  We can either

- change this character
- turn off macro preprocessing.

To change this character you would:

ops$tkyte@8i> set define ^
ops$tkyte@8i> select '&1' from dual;

'&
--
&1

ops$tkyte@8i> select '^1' from dual;
Enter value for 1: Hello
old   1: select '^1' from dual
new   1: select 'Hello' from dual

'HELL
-----
Hello

That made the define character a ^.  To turn off this feature,
you could either issue:

SQL> set define off
SQL> set scan off

for example:

ops$tkyte@8i> set scan off
ops$tkyte@8i> select '^1' from dual;

'^
--
^1

Review &
      Followup

      Rating: 5
succinct soln
      to freq occuring problem  December 06, 2001

Reviewer:  Paul  from London
straight to the point

May 05, 2000 Ron -- Thanks for the question regarding
      "begintrans/commitrans and autocommit", version

      You Asked
I'm trying access Oracle 7.2 from Visual Basic 6 via
ADO.The BeginTrans and CommitTrans commands don't work. Looks
like Oracle ignore them and excutes commit at every update.

      and we said...
Well, Oracle isn't ignoring them -- Oracle doesn't have a
BeginTrans
really (a transaction is always implicity begun with the first
statement
that modifies the database). Your ODBC driver must have
autocommit set on.

In native ODBC, there are 2 API calls that affect transactions:
SQLSetConnectOption and SQLTransact. The SQLSetConnectOption is
used
to set the transaction mode for that connection to read write or
read only and also to enable/disable the Autocommit transaction
mode.  The SQLTransact call is used to commit or rollback
atransaction.

Autocommit is enabled by default as defined by the Microsoft
ODBC
specification.  With Autocommit, a transaction is committed as
soon
as it is executed.  While this increases user concurrency, it
does
not allow the programmer to control when a transaction is
committed
nor does it allow a transaction to be rolled back.  To disable
Autocommit, call SQLSetConnectOption with the SQL_AUTOCOMMIT_OFF
qualifier.  If you disable Autocommit, be sure to commit or
rollback
transactions as often as possible to avoid excessive locking.

Since there are native ODBC calls to handle transactions, the
ODBC
driver must keep track of the transaction state at all times.
For
this reason, executing any statement that affects transactions
is
not supported via SQLExecute or SQLExecDirect calls.  This
includes
SET TRANSACTION, DECLARE TRANSACTION, COMMIT, and ROLLBACK.

May 05, 2000 Mugdha -- Thanks for the question regarding "OAS
      / Oracle8i questions", version

      You Asked
We are creating the Web page for our company. We intend
to use Oracle 8i database. But there are a few questions in our
mind can you help us to solve them :
1) Can the database store the Powerpoint presentation slides,
video clippings , unstructured information , if yes how?

2)Oracle 8i supports Oracle Application Server can it support
Lotus Domino Go Server or any other server other than Oracle
Application Server?

      and we said...
Yes, by storing it in blobs.  If you are interested in adding
value to these blobs, check out
http://www.oracle.com/intermedia/
 With many multi-media
types (sound, image, video, spatial, text) Intermedia can not
only store the objects but extract useful meta data from the
objects such as the image type, runtime length and so on.  It
can provide functions to convert from one media type into
another (Tiff into GIF and so on).  Textual features are keyword
searching, theme generation and gisting.

Yes, any application server that supports open standards such as
JDBC and so on can access Oracle8i.

\
May 05, 2000 Sunil -- Thanks for the question regarding
      "extracting DDL from a dmp file", version

      You Asked
I have a full export (.dmp) of an oracle 7 database
I'd like to extract some ddls that will create
tablespaces,tables
etc direct from the export file.

I've tried the show=yes but this gives me " around all of the
fields.

Is there an alternative method of creating a ddl directly from
an
export.dmp file that I would not have to edit to remove the "
and
join the words that are split onto the next line?

Any help would be most appreciated

      and we said...
for tablespaces - no.  show=y is the only way I know to get
them.

for tables/indexes/etc -- yes.

Try:

$ imp userid=system/manager indexfile=test.lst full=y show=y

And you'll get a file (test.lst) that looks like:

REM  CREATE CLUSTER "SCOTT"."EMP_DEPT_CLUSTER"
("DEPARTMENT_NUMBER"
REM  NUMBER(2, 0)) SIZE 512 PCTFREE 10 PCTUSED 40 INITRANS 2
MAXTRANS 255
REM  STORAGE(INITIAL 122880 NEXT 57344 MINEXTENTS 1 MAXEXTENTS
505
REM  PCTINCREASE 50 FREELISTS 1 FREELIST GROUPS 1) TABLESPACE
"SYSTEM" ;
CONNECT SCOTT;
CREATE INDEX "SCOTT"."EMP_DEPT_CLUSTER_IDX" ON CLUSTER
"EMP_DEPT_CLUSTER"
PCTFREE 10 INITRANS 2 MAXTRANS 255 STORAGE (INITIAL 16384 NEXT
16384
MINEXTENTS 1 MAXEXTENTS 505 PCTINCREASE 50 FREELISTS 1)
TABLESPACE
"SYSTEM" ;
REM  CREATE CLUSTER "SCOTT"."PERSONNEL" ("DEPARTMENT_NUMBER"
NUMBER(2, 0))
REM  SIZE 512 PCTFREE 10 PCTUSED 40 INITRANS 2 MAXTRANS 255
REM  STORAGE(INITIAL 122880 NEXT 57344 MINEXTENTS 1 MAXEXTENTS
505
REM  PCTINCREASE 50 FREELISTS 1 FREELIST GROUPS 1) TABLESPACE
"SYSTEM" ;
REM  CREATE TABLE "SYSTEM"."DEF$_CALL" ("DEFERRED_TRAN_DB"
VARCHAR2(128),
REM  "DEFERRED_TRAN_ID" VARCHAR2(22), "BUFFER_NUMBER" NUMBER,
"CALLNO"
REM  NUMBER, "SCHEMANAME" VARCHAR2(30), "PACKAGENAME"
VARCHAR2(30),
REM  "PROCNAME" VARCHAR2(30), "ARGCOUNT" NUMBER, "PARM_BUFFER"
LONG RAW,
REM  "DESTINATION_LIST" CHAR(1), "ORIGIN_USER_ID" NUMBER,
"ORIGIN_USER"
REM  VARCHAR2(30), "DELIVERY_ORDER" NUMBER, "ORIGIN_TRAN_ID"
VARCHAR2(22),
REM  "ORIGIN_TRAN_DB" VARCHAR2(128), "START_TIME" DATE,
REM  "DESTINATION_COUNT" NUMBER(*,0), "COMMIT_COMMENT"
VARCHAR2(50))
REM  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
STORAGE(INITIAL 16384
REM  NEXT 16384 MINEXTENTS 1 MAXEXTENTS 505 PCTINCREASE 50
FREELISTS 1
REM  FREELIST GROUPS 1) TABLESPACE "SYSTEM" ;
REM  ... 0 rows
CONNECT SYSTEM;
CREATE INDEX "SYSTEM"."DEF$_TRANORDER" ON "DEF$_CALL"
("DELIVERY_ORDER" ,
"DEFERRED_TRAN_ID" , "DEFERRED_TRAN_DB" ) PCTFREE 10 INITRANS 2
MAXTRANS
255 STORAGE (INITIAL 16384 NEXT 16384 MINEXTENTS 1 MAXEXTENTS
505
PCTINCREASE 50 FREELISTS 1) TABLESPACE "SYSTEM" ;
REM  CREATE TABLE "SYSTEM"."DEF$_CALLDEST" ("DEFERRED_TRAN_DB"
REM  VARCHAR2(128), "DEFERRED_TRAN_ID" VARCHAR2(22), "CALLNO"
NUMBER,
REM  "DUMMY_BUFFER_NUMBER" NUMBER DEFAULT 1, "DBLINK"
VARCHAR2(128))
REM  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
STORAGE(INITIAL 16384
REM  NEXT 16384 MINEXTENTS 1 MAXEXTENTS 505 PCTINCREASE 50
FREELISTS 1
REM  FREELIST GROUPS 1) TABLESPACE "SYSTEM" ;
.....

All of the CREATE TABLES/CLUSTERS are there as comments.  If you
"grep -v '^REM \.\.\.' test.lst" and then remove the REM's
you'll have nicely formatted DDL for your objects.

May 05, 2000 west -- Thanks for the question regarding
      "dynamically execute a procedure", version

      You Asked
I have some procedures ,for example:
p1(x:in varchar2,y: in out nimber),p2(...),p3(...),etc...
and I want to execute them from one procedure (for example:
runprocedure(s:varchar2) ),using this format:
runprocedure('p1('string1',100)');
how to do it?

      and we said...
You want to use DBMS_SQL to do this.

for example, if you have a procedure:

create or replace procedure execute_immediate( p_sql in varchar2
)
is
    cursor_name     pls_integer default dbms_sql.open_cursor;
    ignore          pls_integer;
BEGIN
    dbms_sql.parse(cursor_name, p_sql, dbms_sql.native);
    ignore := dbms_sql.execute(cursor_name);
    dbms_sql.close_cursor(cursor_name);
END;
/

You can now code:

begin
    execute_immediate( 'begin some_procedure( 1, 2, ''Hello'' );
end;' );
end;

to dynamically execute some_procedure.

I will advise you to USE BIND VARIABLES, not hard coded values
when doing this.  Something like:

ops$tkyte@8i> set echo on
ops$tkyte@8i> create or replace procedure execute_immediate(
p_sql in varchar2,
  2                     p_name1 in varchar2 default NULL, p_val1
in varchar2 default NULL,
  3                     p_name2 in varchar2 default NULL, p_val2
in varchar2 default NULL,
  4                     p_name3 in varchar2 default NULL, p_val3
in varchar2 default NULL,
  5                     p_name4 in varchar2 default NULL, p_val4
in varchar2 default NULL)
  6  is
  7      cursor_name     pls_integer default
dbms_sql.open_cursor;
  8      ignore          pls_integer;
  9  BEGIN
 10      dbms_sql.parse(cursor_name, p_sql, dbms_sql.native);
 11      if ( p_name1 is not null )then
 12          dbms_sql.bind_variable( cursor_name, p_name1,
p_val1 );
 13      end if;
 14      if ( p_name2 is not null )then
 15          dbms_sql.bind_variable( cursor_name, p_name2,
p_val2 );
 16      end if;
 17      if ( p_name3 is not null )then
 18          dbms_sql.bind_variable( cursor_name, p_name3,
p_val3 );
 19      end if;
 20      if ( p_name4 is not null )then
 21          dbms_sql.bind_variable( cursor_name, p_name4,
p_val4 );
 22      end if;
 23      ignore := dbms_sql.execute(cursor_name);
 24      dbms_sql.close_cursor(cursor_name);
 25  END;
 26  /

Procedure created.

ops$tkyte@8i>
ops$tkyte@8i> begin
  2      execute_immediate( 'begin dbms_output.put_line( :1 ||
:2 || :3 ); end;',
  3                         '1', 'hello ',
  4                         '2', 'World',
  5                         '3', '!!!!' );
  6  end;
  7  /
hello World!!!!

PL/SQL procedure successfully completed.

will do it.
May 05, 2000 Gary -- Thanks for the question regarding
      "extracting to ascii delimited files", version

      You Asked
using oracle 7.3 and above, is there
away to produce a text or ascii file
with either a tab or character delimiter.
also, there should not be any spaces
before or after the delimiter - each
field/row is returned at its exact length
without padding?

      and we said...
we can use sqlplus for this.

See
http://osi.oracle.com/~tkyte/flat/index.html
May 05, 2000 Cleo -- Thanks for the question regarding
      "calling a procedure with an output type of PLSQL table", version

      You Asked
How do you execute a procedure which has one input
parameter of type number and one output of a PL/SQL table type?
Is this actually possible?

      and we said...
Yes it is possible.  The trick is to make sure the CALLER uses
the SAME EXACT type as the procedure that has the OUT table
parameter -- it cannot create its own 'similar' type.  Here is
an example show how this is done:

ops$tkyte@dev8i> create or replace package demo_pkg
  2  as
  3          type myTableType is table of varchar2(25) index by
binary_integer;
  4
  5          procedure foo( p_num in number, p_tbl out
myTableType );
  6  end;
  7  /

Package created.

ops$tkyte@dev8i>
ops$tkyte@dev8i> create or replace package body demo_pkg
  2  as
  3
  4          procedure foo( p_num in number, p_tbl out
myTableType )
  5          is
  6          begin
  7                  for i in 1 .. p_num loop
  8                          p_tbl(i) := 'Entry ' || i;
  9                  end loop;
 10          end;
 11  end;
 12  /

Package body created.

ops$tkyte@dev8i>
ops$tkyte@dev8i>
ops$tkyte@dev8i>
ops$tkyte@dev8i> declare
  2          l_data  demo_pkg.myTableType;
  3  begin
  4          demo_pkg.foo( 5, l_data );
  5
  6          for i in 1 .. l_data.count loop
  7                  dbms_output.put_line( l_data(i) );
  8          end loop;
  9  end;
 10  /
Entry 1
Entry 2
Entry 3
Entry 4
Entry 5

PL/SQL procedure successfully completed.

--
Thanks,

    Thomas Kyte                          tkyte@us.oracle.com
    Oracle Service Industries

    Oracle tips and papers
http://www.oracle.com/oramag/code/index.html

Review &
      Followup

      Rating:
      3
  April 24, 2001
Reviewer:  Helena
      Markova  from Bratislava, Slovakia

May 05, 2000 Hani -- Thanks for the question regarding
      "connecting as another user without their password", version

      You Asked
I have an amazing trick, all what I need if it possible
to connect as x user
without changing his password if I am SYS, SYSTEM or internal.

      and we said...
You *have* this amazing trick or you would *like to have* this
amazing trick.

You cannot have this amazing trick because you do have to change
their password for a second -- but -- you can change it right
back (without ever knowing what it was).  Is that enough of a
trick?

See the SQLPlus script at
http://osi.oracle.com/~tkyte/Misc/su.html
May 05, 2000 monica -- Thanks for the question regarding
      "about mutating tables.", version

      You Asked
what is the mutating error during trigger execution?
why does it occur and how can it be solved?

      and we said...
see
http://osi.oracle.com/~tkyte/Mutate/index.html
In most cases -- you can avoid it by modifying your row level
trigger (eg: you are attempting to enforce referential integrity
via a trigger, instead of using a trigger to perform this
operation -- use the "foreign key constraint" instead.  You are
attempting to modify the values of a row in a table being
updated -- you are trying to do this with an UPDATE statement in
the trigger -- you did not realize that you can simly write to
the :new.* record in the trigger to effect the update).

May 05, 2000 Brenda -- Thanks for the question regarding
      "adding time to a date", version

      You Asked
How Can I add a time (e.g. 5 mins) stored in a DATE
field to a date (e.g. 2/21/2000) stored in a DATE field also?

      and we said...
see
http://osi.oracle.com/~tkyte/Misc/DateDiff.html
for more info but in short -- you add "days" to a date.
 To add 5 minutes:

select sysdate + (1/24/60) * 5 from dual;

1/24/60 = 1 minute of a day.

    Copyright © 2003 Oracle Corporation, All rights reserved.


Recent Archives Advanced Search FAQ by Category Most Popular Hot Articles Your Questions [ Listing ]
Subject | Article | Last Updated (East coast time)
How do I know the value of MAXDATAFILES parameter | article only | May 10, 2000 04:06 pm
is utl_file upwards compatible with later releases of oracle | article only | May 10, 2000 04:09 pm
where can I get documentation | article only | May 10, 2000 04:12 pm
remove user who have not logged in for 3 months.. | article only | May 10, 2000 04:14 pm
case insensitive searching | article only | May 10, 2000 04:21 pm
suggest the best set of books for the newcomer to Oracle. | article only | May 10, 2000 04:30 pm
some questions on exceptions | article only | May 10, 2000 07:17 pm
userenv('sessionid') -- are the values reused? | article only | May 11, 2000 08:47 am
delphi/ref cursor question | article only | May 11, 2000 08:48 am
"temporary table" question with reports | article only | May 11, 2000 08:49 am
mutating table question | article only | May 11, 2000 08:53 am
locked tables and rows. | article only | May 11, 2000 08:54 am
access Post script files on WAS | article only | May 11, 2000 04:16 pm
row(s) 1 - 13 of 13
May 10, 2000 Avinash -- Thanks for the question regarding "How do I know the value of MAXDATAFILES parameter ", version
You Asked
How do I know the value of MAXDATAFILES parameter
without actually going and looking into the init.ora parameter
file?
and we said...
Well, MAXDATAFILES is part of the control file and is not in the
init.ora file.  In the init.ora file, you will find db_files (or
you can query "select * from v$parameter where name =
'db_files')

  1* select value from v$parameter where name = 'db_files'
sys@8i> /

VALUE
------------------------------
200

If you want maxdatafiles from the control file, you would query:

  1* select records_total from v$controlfile_record_section
where type = 'DATAFILE'
sys@8i> /

RECORDS_TOTAL
-------------
          254

showing I have db_files set to 200 (max files the database will
manage for me is 200).  I have maxdatafiles set to 254 (meaning
i can set db_files to 254 if I wanted to)
May 10, 2000 BELBAHRI -- Thanks for the question regarding "is utl_file upwards compatible with later releases of oracle", version
You Asked
I'm using the package UTL_FILE to extract data from
flate file to oracle tables with oracle 7.
My question is : is it compatible with oracle 8 or not ?

Thank you,
and we said...
Yes it is.  UTL_FILE was added to the database in Oracle7.3.3.  In Oracle8.0.5,
it was enhanced to support IO on files with linesizes upto 32k in size (instead
of its current 1033 byte linesize).

All code written for 7.3.3 will compiled in 8.0 and up unchanged with regards to
UTL_FILE.  There are new optional parameters on some routines that have defaults
that make it behave like the 7.3 version.
May 10, 2000 Madan -- Thanks for the question regarding "where can I get documentation", version
You Asked
Hello Tom,
I am here once again, can you please tell me
the books online which I can go through,which may be
available online free.Please tell the site's if
any is available now,
and we said...
http://technet.oracle.com/
has tons of books online -- in either html or pdf format.

If you want to read about Oracle -- I would suggest starting
with the Getting to Know Oracle8i document (new features over
previous release with quick blurbs about each) and then the
Oracle8i Server concepts manual.

http://technet.oracle.com/doc/server.815/a68020/toc.htm
http://technet.oracle.com/doc/server.815/a67781/toc.htm
May 10, 2000 Carine -- Thanks for the question regarding
      "remove user who have not logged in for 3 months..", version

      You Asked
I work on Oracle 7.3.4 and want to clean up users who
haven't logged on for more than 3 months. How to...?
Thanks very much in advance.

      and we said...
Well, we will have to wait 3 months to drop the first user
however -- the process you follow is:

o enable AUDITING in your database.  You do this by setting
"audit_trail=true" in your init.ora and restarting

o directing the system to audit connections, it might look like
this:

SVRMGR> audit session by access;
Statement processed.

Then, to monitor logins, you can:

SVRMGR> select username, to_char( timestamp, 'dd-mon-yyyy
hh24:mi:ss' ), priv_used from dba_audit_trail;

USERNAME        TO_CHAR(TIMESTAMP,'DD-MON-YYYYHH24:MI:SS')
PRIV_USED
--------------- --------------------------------------------
--------------------
SCOTT           16-feb-2000 08:30:09
CREATE SESSION
1 row selected.

beware -- watch the size of your sys.aud$ table!!! you might
have to copy it to another place and delete from it periodically
to avoid having your system tablespace grow and grow over time.
SYS is not audited (so if system fills up and no one can log in
due to system being full and no room for audit entries, SYS can
still log in and clean up).

May 10, 2000 Erik -- Thanks for the question regarding "case
      insensitive searching", version

      You Asked
Good morning!

I represent a major sofware house here in Norway and we have
supported Oracle databases since 97.  A major frustration among
several of our customers relates to case sensitivity when
retrieving data.  Is there an easy way we can instruct Oracle
NOT
to be case sensitve?

      and we said...
In Oracle8i, release 8.1 -- this is pretty much solved.

In Oracle7, the standard solution for this is programatic.
Create a 'mirror' column of the data you want to search in a
case insensitive fashion. eg: alter table t add ename_upper
varchar2(25);.  Then create a trigger to maintain that column:

create or replace trigger t before insert or update on t for
each row
begin
   :new.ename_upper := upper(:new.ename);
end;

Then, in the search application, your developers would know to
code:

select ename from T where ename_upper = upper(:search_criteria);

In Oracle8i, release 8.1, a new feature (perhaps reason enough
to upgrade for you) was added.  This is called function based
indexes.  See
http://osi.oracle.com/~tkyte/article1/index.html
for a paper on this feature and how it works.
 It solves this issue much more elegantly.

May 10, 2000 Judith -- Thanks for the question regarding
      "suggest the best set of books for the newcomer to Oracle.", version

      You Asked
Sorry for this absolute newbie question...
My background includes Sybase (training
only, never applied on-the-job),
UNIX SysAdmin, and intranet
Webmaster.  I'm now contemplating a new
career path as an Oracle DBA.  Can
you suggest the best set of books,
courses, or magazine subscriptions
for the newcomer to Oracle?  The wealth
of source material on Amazon, Fatbrain,
and technet.oracle.com is massive and
bewildering.  Many thanks for any tips!

      and we said...
The best place, in my opinion, to start is with the server concepts manual.

http://technet.oracle.com/doc/server.815/a67781/toc.htm
I myself continue to read this one from cover to cover with each major release.
It covers all of the  basics and the concepts.  It is one of the best -- but for
some reason one of the least used -- documents we have.

After that, I would get into the getting to know Oracle8i document.  Goes over
the major features - which are include with what release and so on.

If you read and fully understand the concepts manual -- you'll have a great
start

May 10, 2000 Max -- Thanks for the question regarding "some
      questions on exceptions", version

      You Asked
My question is also about exception.  Please see the code first:

/* When adding a grade of a course into Grade table, its
prerequisite courses have to be taken first.

EXCEPTION
WHEN PRE_REQUIRED THEN
RAISE_APPLICATION_ERROR(-20001, 'PREREQUISITE COURSE
REQUIRED');

END;

I used error code -20001, but really I don't know what it
excatly
is and whether I used it correctly.  My question is that, if I
don't use raise_application_error, simply using
dbms_output.put_line('...'), why a grade is still inserted
though
the trigger is fired?  Assuming I define the following
exception:

EXCEPTION
WHEN PRE_REQUIRED THEN
DBMS_OUTPUT.PUT_LINE('PREREQUISITE COURSE REQUIRED: ' ||
V_PRECNO);

Please let me know whether you will answer by emailing me or I
need to go to certain page for answer.

      and we said...
[snip]

You used raise_application_error() correctly. You have access to
the error codes -20000 to -20999, you pick the ones that have
meaning to YOU.

Your second question is why does the row get inserted when I use
dbms_output instead of raise error?  the reason is that you did
not let the exception propagate out of the trigger -- you caught
the exception in the WHEN PRE_REQUIRED block -- and you exited
the exception block without either:

  - reraising the execption via the builtin "raise;" command
  - raising a user defined error code via
raise_application_error.

If you change the exception block to (or just REMOVE the entire
exception block):

EXCEPTION
  WHEN PRE_REQUIRED THEN
     DBMS_OUTPUT.PUT_LINE('PREREQUISITE COURSE REQUIRED: ' ||
V_PRECNO);
     raise;

it'll not insert the row without using raise_application_error

May 11, 2000 anthony -- Thanks for the question regarding
      "userenv('sessionid') -- are the values reused?", version

      You Asked
I use the following query to get session id.
Select userenv('SESSIONID') From Dual.

I have two doubts about using the above query.
(1). Let us assume that Session Id  1188 is created for one
session.
After some time this session is over( logged out)and another
user
gets connected to database. Can the session id 1188 be assigned
to the new session?.Is there any possibilities for that?

(2). Can the session id 1188 get repeated if the database is
shutdown and restarted Or the session id is uniqe throughout the

life of the database?

Please clear my doubts.

      and we said...
Yes. sessionid is really the audses$ sequence.  It is set to
cycle.  Its max_value may vary by implementation but eventually
it can cycle.  Once upon a time (7.3) there was a bug in Context
and the fix was to make the max_value of audses$ 32,765.  In
that case, it would cycle frequently.

sys@8i> select * from user_sequences where sequence_name =
'AUDSES$';

SEQUENCE_N  MIN_VALUE  MAX_VALUE INCREMENT_BY C O CACHE_SIZE
LAST_NUMBER
---------- ---------- ---------- ------------ - - ----------
-----------
AUDSES$             1 2000000000            1 Y N         20
10535706

sys@8i> select userenv('sessionid') from dual;

USERENV('SESSIONID')
--------------------
            10535689

After  2,000,000,000 (2 billion) logins -- the numbers will be
reused.  If you export/import the whole database -- the sequence
will be reused.  If you use a database where the max_value is
set smaller, it'll be reused faster.  You might consider using
your own 28 digit sequence with its own characteristics instead
of relying on sessionid if uniqueness and portability across
database instances is important to you.

May 11, 2000 garza -- Thanks for the question regarding
      "delphi/ref cursor question", version

      You Asked
Hi Tom,
I'm a developer using Delphi 4.0 and Oracle 8i Ver. 8.1.5. in
NT 4.0 and service pack 5.

I'm trying to build a function (using PL/SQL) that return a
cursor to my grid.

1  CREATE OR REPLACE FUNCTION DEPT_CON_FN RETURN
types.cursortype AS
2    v_cursordept   types.cursorType;
3  BEGIN
4    OPEN v_cursordept FOR SELECT * FROM dept;
5    RETURN v_cursordept;
6    CLOSE v_cursordept;
7* END DEPT_CON_FN;

LINE/COL ERROR
-------- --------------------------
0/0      PL/SQL: Compilation unit analysis terminated
1/30     PLS-00201: identifier 'TYPES.CURSORTYPE' must be
declared

the user/password is tiger/scott and the table is dept.

Why I'm getting this error?, Is correct my approach to build a
function to get less traffic in the network?.

Thank's in advance for your help.

      and we said...

You need to create this package once in your database:

create or replace package TYPES
as
   type cursorType is ref cursor;
end;
/

Then, you can reference types.cursortype as a new type in all
other packages/procedures.

Additionally -- lose the close v_cursordept after the return

o the code will never be executed as it is after the return
o the client is responsible for closing the cursor -- not the
plsql routine that opened it.

Yes, this is one way to reduce network traffic but it is mostly
used to encapsulate the logic and privs needed to get a result
set.

see
http://osi.oracle.com/~tkyte/ResultSets/index.html
for an example of this as well.

Review &
      Followup

      Rating: 4
returning
      result sets from a PL/SQL Procedure  May 29, 2001

Reviewer:  Alessandro Mariotti  from Italy

I'm not a Delphi developer but I found this tips very useful for my needs.

May 11, 2000 anthony -- Thanks for the question regarding
      ""temporary table" question with reports", version

      You Asked
Thanks a lot for clearing my earlier doubts.
The follwing are the problems I face.

1. I use temporary tables in Reports2.5 to dynamically
insert,delete or update rows. If two or more users run the same
report simultaneously, the rows inserted by one user appear in
the report output of another user. I don't want that. The rows
inserted,deleted or updated by one user should not be accessible

by another user. Can you advice me how to avoid this multiuser
problem?

2. Reports2.5 autocommits DML operations. Can you advice me how
to avoid this autocommit?

      and we said...
If you are using a version of Oracle prior to release 8.1 (which
has temporary tables) you must be using real tables.  Since
other users can see these changes -- that must be the case.

Alter each of your temporary tables as such:

alter table T add sess_id number default userenv('sessionid');
create index t_sess_idx on T(sess_id);
rename T to T_TBL;
create view T as select <all columns EXCEPT for sess_id> where
sess_id = userenv('sessionid');

And if T has any UNIQUE indexes make sure to add sess_id to
those indexes.  In this fashion -- you'll see only the data that
was added to the table during your session.

AUTOCOMMIT=YES|NO on the command line (as a parameter to
reports)

May 11, 2000 Eng -- Thanks for the question regarding
      "mutating table question", version

      You Asked
I am trying to create a database trigger to update
emp.upd_ind='Y' when
there is an update on the column emp.emp_address.

Pls advise what have i left out and what's wrong to my scripts.
Thanks.

ERROR at line 1:
ORA-04091: table SCOTT.EMP is mutating, trigger/function may not
see it
ORA-06512: at "SCOTT.EMP_AFT_ROW_ALL", line 5
ORA-04088: error during execution of trigger
'SCOTT.EMP_AFT_ROW_ALL'

Database trigger scipts
=======================
create or replace trigger emp_bef_stm_all
before insert or update or delete on emp
begin
/*
Remember to reset the pl/sql table before each statement
*/
emp_pkg.emp_index := 0;
end;
/

create or replace trigger emp_aft_row_all
after insert or update or delete on emp
for each row
begin
/*
Store the rowid of updated record into global pl/sql table
*/
update emp set upd_ind='Y' where emp_address=:new.emp_address;
emp_pkg.emp_index := emp_pkg.emp_index + 1;
emp_pkg.emp_tab(emp_pkg.emp_index) := :new.rowid;
end;
/

create or replace trigger emp_aft_stm_all
after  insert or update or delete on emp
begin
for i in 1 .. emp_pkg.emp_index loop
dbms_output.put_line(emp_pkg.emp_tab(i));
end loop;
emp_pkg.emp_index := 0;
end;
/

      and we said...
If emp_address points to many records (eg: emp_address is not a
unique key), you need to defer the update until the AFTER
trigger.  See
http://osi.oracle.com/~tkyte/Mutate/index.html
for examples of doing this.

In emp_address is in fact UNIQUE then a single trigger is what
you need:

create or replace trigger T
before insert or update on T
for each row
begin
   :new.upd_ind := 'Y';
   dbms_output.put_line( :new.rowid );
end;

May 11, 2000 Henry -- Thanks for the question regarding
      "locked tables and rows.", version

      You Asked
Hi Tom, how to query what tables and records are locked
by another users?

      and we said...
You can see the objects another user has locked by querying the
v$lock dynamic performance view (see the Server Reference manual
for a description of the columns in this view).

Addtionally, consider executing the catalog script
"catblock.sql" found in $ORACLE_HOME/rdbms/admin.  It creates
some views that are of great use.

You cannot get a list of 'rows' a process has locked for the
simple reason that no such list exists.  We store locks as an
attribute of the data -- not in a list that would generate a
point of serialization (to get and release locks).  You want a
lock on a row -- goto the row and see if it is locked, if it is
-- wait for it (or not depending on the lock request).   No
where does there exist a set of rows i have locked.....

Review &
      Followup

      Rating: 5
locked
      rows  April 12, 2002
Reviewer:
      y.l.narasimham  from INDIA
Hi! Tom,

Never before, I was so amazed like I am now. I am a silent reader and learner of
user mails and your replies. I thank you (and all the people concerned) very
much for the service you are doing to the Oracle Users.

As you said, I could able to get the information regarding locked rows from the
archives. AND whats more my long time doubt regading "is it possible to list
locked records" is answered.

Thank you very much

May 11, 2000 Shruti -- Thanks for the question regarding
      "access Post script files on WAS", version 4.0.8.1

      You Asked
Hi Tom,

We use troff to print some data from our database using Perl
. How can i access the postscript
file on UNIX machine from WEB using oracle application server?

Shruti

      and we said...
Well, accessing the postscript files is easy.  You'll have the
perl application write its output into some known directory with
some known file extension like ".ps".  In the OAS configuration,
you'll have mapped this directory to some virtual path (eg:

/ps-files/   gets mapped to /path/to/where/postscript/output/is

and you'll add a mime-type "application/postscript" to the OAS
listener configuration as well for files that have an extension
.ps.  that way, when the webserver sends them back to the
browser -- the browser will know what they are.

Then, to access from the browser, you simply use a URL such as:

http://yourhostname/ps-files/somefilename.ps

Now, thats only half the problem because the browser won't
really know what to do with these "application/postscript"
files.  You'll need to get a plugin or helper app that does
understand them.  You can get free viewers for postscript from
the following:

http://www.cs.wisc.edu/~ghost/aladdin/index.html
Aladdin Ghostscript, a PostScript interpreter for OS/2, Unix,
SunView, VMS, Windows, Mac.

http://www.cs.wisc.edu/~ghost/gnu/index.html
GNU Ghostscript, another version for Unix, SunView, and VMS
only.

http://www.cs.wisc.edu/~ghost/gsview
GSView, a Screen viewer for Windows or OS/2.

http://www.cs.wisc.edu/~ghost/ghostview/index.html
Ghostview, a screen viewer for Unix, X-Windows.

http://www.cs.wisc.edu/~ghost/mac/index.html
Macintosh Ghostscript, a PostScript interpreter and screen
viewer for Macintosh.

http://www.cs.wisc.edu/~ghost/index.html
Ghostscript, Ghostview & GSview home page, with general
information about PostScript interpreters.


Subject | Article | Last Updated (East coast time)
Export to a named file on NT | article only | May 15, 2000 08:10 am
Export to a file named after the date | article only | May 15, 2000 08:12 am
Inverted Index | article only | May 15, 2000 08:51 am
Rollback segments going offline | article only | May 15, 2000 11:45 am
Question on dbms_jobs | article only | May 15, 2000 11:51 am
ORA-2091 Question | article only | May 15, 2000 11:55 am
Date fields and milliseconds | article only | May 15, 2000 11:57 am
To keep database up round the clock. | article only | May 15, 2000 12:17 pm
scheduling backups | article only | May 15, 2000 01:11 pm
base2base question | article only | May 15, 2000 01:24 pm
ftp 5 csv files daily. | article only | May 15, 2000 01:25 pm
slow import | article only | May 15, 2000 01:30 pm
getting rows M through N | article only | May 15, 2000 01:31 pm
data integrity question. | article only | May 15, 2000 01:32 pm
converting from Sybase to Oracle. | article only | May 15, 2000 01:32 pm
interfacing with oracle questions | article only | May 15, 2000 01:34 pm
How key mapping is done in D2K?. | article only | May 15, 2000 01:36 pm
'Oracle coding standards' | article only | May 15, 2000 01:37 pm
difference between 2 dates | article only | May 15, 2000 01:45 pm
getting a linefeed. | article only | May 15, 2000 01:47 pm
transactions with OAS3.0 | article only | May 15, 2000 01:48 pm
copy data from one user to another. | article only | May 15, 2000 01:49 pm
read or write OS files. | article only | May 15, 2000 01:56 pm
RE: Ask Tom Submission | article only | May 15, 2000 01:59 pm
varchar >2000 | article only | May 15, 2000 02:00 pm
Oracle Expert questions | article only | May 15, 2000 02:01 pm
how to start with java stored procedures. | article only | May 15, 2000 02:02 pm
When-Tree-Node-Selected question. | article only | May 15, 2000 03:05 pm
Can we use a CD as input to SQL*LOADER? | article only | May 15, 2000 03:06 pm
pinning a sequence | article only | May 15, 2000 03:07 pm
update cascade | article only | May 15, 2000 03:15 pm
proc question | article only | May 15, 2000 03:18 pm
long copy over a db link | article only | May 15, 2000 03:21 pm
using quotes in sqlplus | article only | May 15, 2000 03:22 pm
How can I print data/files to printer inside a PL/SQL | article only | May 15, 2000 03:25 pm
returning object type to oci | article only | May 15, 2000 03:27 pm
How to copy a set of tables from one user to another user | article only | May 15, 2000 03:27 pm
i need some documentation on creating triggers | article only | May 15, 2000 03:41 pm
RE: inserting images into BLOB column | article only | May 15, 2000 03:41 pm
RE: Ask Tom Submission | article only | May 15, 2000 03:44 pm
Inserting long strings | article only | May 15, 2000 03:46 pm
how can I clear the buffer with regards to a column heading | article only | May 15, 2000 03:47 pm
forms with a firewall | article only | May 15, 2000 03:50 pm
index question | article only | May 15, 2000 03:58 pm
paritioning option | article only | May 15, 2000 04:01 pm
display result sets from plsql in sqlplus | article only | May 15, 2000 04:03 pm
sqlcxt undefined | article only | May 15, 2000 04:03 pm
what does error XXXX mean | article only | May 15, 2000 04:04 pm
drop index with special characters | article only | May 15, 2000 04:05 pm
using dynamic sql in SQLJ | article only | May 15, 2000 04:05 pm
printing a word doc | article only | May 15, 2000 04:06 pm
FRM-40202 | article only | May 15, 2000 04:08 pm
I want to develop java appliction | article only | May 15, 2000 04:09 pm
skipping columns with sqlldr | article only | May 15, 2000 04:11 pm
blob storage question | article only | May 15, 2000 04:13 pm
SQLNet on a WAN | article only | May 15, 2000 04:14 pm
RE: [Fwd: Ask Tom Submission] TkProf/Explain Plan question | article only | May 15, 2000 04:15 pm
are reserved words in a table? | article only | May 15, 2000 04:16 pm
RE: Ask Tom Submission, How often to backup | article only | May 15, 2000 04:18 pm
array processing | article only | May 15, 2000 04:23 pm
ORACLE WEB SERVER | article only | May 16, 2000 08:49 am
Executing AFTER row trigger on failed insert | article only | May 17, 2000 04:02 pm
How to increase data block size properly ? | article only | May 18, 2000 10:06 am
Generic Search Window | article only | May 18, 2000 11:48 am
sql unload utility | article only | May 18, 2000 04:17 pm
Help Required | article only | May 18, 2000 04:21 pm
Web-to-go Configuration with OAS | article only | May 18, 2000 04:29 pm
problem regarding trigger related to long column | article only | May 19, 2000 07:51 am
estimate Initial Extent size of a table | article only | May 19, 2000 09:16 am
Deletion of duplicate rows from all tables in a database.. | article only | May 19, 2000 10:51 am
Frame Drivers | article only | May 19, 2000 12:38 pm
Why doesn't Oracle support joins in updates, are there plans to in the future? | article only | May 19, 2000 12:48 pm
Ordering by max of multiple columns with preferences | article only | May 19, 2000 04:37 pm
Mutating Tables (cont'd) | article only | May 19, 2000 08:39 pm
row(s) 1 - 74 of 74
May 15, 2000 Ravi -- Thanks for the question regarding "Export to a named file on NT", version
You Asked
When I take Export on NT How do I embed date for the file.

Example.
exp file=exp_prod_xxxxxxxx

xxxxxxxx should be the system date(12012000).

On Unix I can use shell variable like $A How do I do the same On
NT.
and we said...
I'll cheat.  I'll show you a way to do this that works in Unix
and NT.  Instead of trying to force the NT .cmd script language
into unnatural acts or tell you to buy a 3'rd party "Unix" shell
-- we'll use SQLPlus as our general purpose scripting tool.

Say you have a file, export.cmd, that looks like this:

--------------- export.cmd -----------------
echo off

sqlplus scott/tiger @doexport
---------------- eof ---------------------

the line sqlplus scott/tiger @doexport is in place of

exp userid=scott/tiger ......

the script doexport.sql looks like:

-------------- doexport.sql ----------------------------
column today new_val dt

select to_char( sysdate, 'ddmmyyyy' ) today from dual;

host exp userid=scott/tiger tables=emp file=exp_prod_&dt..exp

exit
-------------- eof -------------------------------------

That should work on all platforms.
Review & Followup
Rating: 5
July 04, 2001
Reviewer: Martin Haltmayer from Munich, Bavaria, Germany

Rating: 4
July 21, 2001
Reviewer: A reader from OH USA
Finally got the solution for my problem

May 15, 2000 Bhavendra -- Thanks for the question regarding "Export to a file named after the date", version Oracle 8.04
You Asked
Hi Tom,

Again I disturb you.

How to pass the parameter in batch file?.

I has been taken daily export of Oracle User.
For that purpose I have make a schedule for automatic export
using batch file. But in parfile I hardcode the name of file.
So I want to change that dynamically.
e.g. bhaven.01-05-00
     bhaven.02-05-00 etc.

Please advise for the same.

Thanks in advance.

Bhavendra
and we said...
One method that allows for the current date to be assigned to
the export file can be found at:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:612348047
This uses SQLPlus as the scripting environment to dynamically
pass the current sysdate as a parameter to export.
May 15, 2000 Saibabu -- Thanks for the question regarding "Inverted Index", version 8.1.5
You Asked
Hi Tom,
  Iam not able to clearly understand the IR(Information
Retrival)
processing application by modelling inverted index of Index
organized table in Server concepts manual.Could you please
explain about inverted index modelling.
 Thanks
Saibabu
and we said...
the above referenced documentation made be viewed at:
http://technet.oracle.com/doc/server.815/a67781/c08schem.htm#13434
The inverted list is simply a list taken backwards.  If you
consider a document for example, it consists of a series of
words.  It is natural to think of a document having a series of
words in it.  An inverted list index built on documents would
have a list of WORDS pointing to their documents -- instead of a
document with its list of words.

So, to build an inverted list index on documents -- you would
typically write a parser to decompose the documents and then you
might come up with a relational schema such as:

create table document
( document_id     number primary key,
  text            clob );

create table keywords
( word              varchar2(80),
  document_id       number,
  document_offset   number,
  document_part     varchar2(80) check ( document_part in
  ('SUBJECT', 'AUTHOR', 'PARAGRAPH', 'INDEX', 'CONTENTS', ...
)),
  .. (other relevant pieces of information) ...,
  constraint keywords_pk primary key
                  (word,document_id,document_offset)
);

as documents were loading into the system, we would parse them
and fill in the keywords inverted list index table so we knew
where each word occurred in the document (eg: the 500'th word is
"Hello"), what words were in the document, where the word
occurred in the document (in the subject, in a paragraph and so
on) and other attributes we deem relevant to our searching.

So, that would allow us to have a query such as:

REM find all documents that contain Hello:
select *
  from document
 where document_id in ( select document_id
                          from keywords
                         where word = 'Hello' );

REM find all documents that contain Hello AND Goodbye:
select *
  from document
 where document_id in ( select document_id
                          from keywords
                         where word in ( 'Hello', 'Goodbye' )
                         group by document_id
                        having count(*) = 2 );

REM find all documents such that Hello is NEAR goodbye by
REM finding all documents with HELLO that have a row in keywords
REM such that the document_id is the same, the word is GOODBYE
REM and the different between the offsets in the document is
less
REM then 50 words:

select *
  from document
 where document_id in ( select document_id
                          from keywords a
                         where word = 'Hello'
                           and EXISTS
                           ( select null
                               from keywords b
                              where word = 'Goodbye'
                                and b.document_id =
a.document_id
                                and abs(a.document_offset -
                                        b.document_offset ) <
50)
                      )

Now, in order to effectively use this data in the keywords table
-- it needs to be indexed, at least on the "word" column.  We
always query on the word column.  In fact, the table itself so
far in this example has been redundant -- we've never use it --
we always queried on WORD, DOCUMENT_ID and DOCUMENT_OFFSET --
they are in the index and we never accessed the table.  So far,
the table is just wasting space.  Now, if we ask a question such
as:

REM find all documents that contain "Oracle" in a SUBJECT
section

select *
  from document
 where document_id in ( select document_id
                          from keywords
                         where word = 'Oracle'
                           and document_part = 'SUBJECT' );

Now this time we needed the table however -- performance would
have suffered since for all of the thousands of entries for
Oracle in the keywords table -- we would have had to do a TABLE
ACCESS BY ROWID to see if the document_part is SUBJECT.  We
would have to do that thousands of times.  It would be very
costly.

By using an index organized table, we could avoid these two
issues, the issues of:

o redundant storage, we really do not want the table at all,
just the index.

o the table access by rowid (scattered read) for attribute data.
May 15, 2000 Mahmoud Reza -- Thanks for the question regarding "Rollback segments going offline", version
You Asked
Dear Tom,

I'm using Oracle 8.0.5 Enterprise
Edition for NT and I don't know why my
rollback segments go offline every
once in a while. I have four rollback
segments: SYSTEM and SYSROLL in the
SYSTEM tablespace and RB0 and RB1 in
a tablespace called RBS.

Thanks
Mahmoud
and we said...
the probably go offline after every restart of the database.

Do you have a line like:

rollback_segments = (rb0, rb1)

in your init.ora startup file?  If not, these rollback segments
will not be brought online during startup.
May 15, 2000 Ivanka -- Thanks for the question regarding "Question on dbms_jobs", version
You Asked
Oracle v.8.0.4
There are two jobs in two different
schemas(s1 and s2). I would like to submit another
job in order to execute procedure,
which checks if there is broken job
(in s1 and s2) and if yes executes
dbms_job.rin(job_id).Is this possible
to be made only with one job and one
procedure, or in each schema has to be
submitted separate job?
and we said...
The person who submits a job to the job queue is considered the
job's owner. The job's owner is the only one who can alter the
job, force the job to run, or remove the job from the queue.  If
you need to look up any information regarding a submitted job,
DBA_JOBS and USER_JOBS contain a lot of information such as the
job number, user, status, etc.

If the jobs exist in different schemas, then a job would have to
be submitted in each schema to 'monitor' them.
May 15, 2000 Amy -- Thanks for the question regarding "ORA-2091 Question", version
You Asked
I receive error 02091

Oracle 8.0.5
Win/nt sp 6

I do not have a distributed database.

I am working on a client pc getting to the server via net 8.

After a large transaction, when the process tries to commit, I
receive the error ORA 02091 (only this error
not ORA 02092).
There are not errors in alert log or trace files.

I have increased the number of rollback segments and
log file groups. But this did not help.

Any ideas as to why I am getting this error?
and we said...
You are using deferrable constraints I'll bet.  They will throw
this error.... Something should be after the ORA-2091 in any
case.

ops$tkyte@dev8i> create table ktest
  2    (col1 varchar2(3) constraint pk_column
                         primary key deferrable
  3    initially deferred);

Table created.

ops$tkyte@dev8i>
ops$tkyte@dev8i> insert into ktest values ( 1 );

1 row created.

ops$tkyte@dev8i> insert into ktest values ( 1 );

1 row created.

ops$tkyte@dev8i> commit;
commit
*
ERROR at line 1:
ORA-02091: transaction rolled back
ORA-00001: unique constraint (OPS$TKYTE.PK_COLUMN) violated
May 15, 2000 ted -- Thanks for the question regarding "Date fields and milliseconds", version
You Asked
Thomas, can oracle date field store millisec information ?
thanks in advance
ted chyn
and we said...
No, the SQL92 date/time elements will be able to in the future
(this feature did not make it into 8.1.6).  Current the
granularity of time is down to the second only.

you can use Java stored procedures or C external procedures to
get time at a finer level of detail but you will have to store
it in a number field your self -- it cannot be saved in an
Oracle DATE field.
Review & Followup
Rating: 1
What??????? Oracle is *incapable* of storing milli-seconds??? February 06, 2002
Reviewer: SC from This World, California
This is so frustrating!!

As many other little things.. Oracle has away of *complicating* easy needs!
Microsoft is way better!

May 15, 2000 raj kumar -- Thanks for the question regarding "To keep database up round the clock.", version oracle 7.3.4.4.0
You Asked
Hi Mr.Tom,
Ours is a Telecomm service industries. Our customer base is very
high.
We are having HP K370 server ( HP ux 10.20) and Oracle 7.3.4.4.0
with Oracle Financials Application. We have one another server
HP K570 (HP-UX 10.20) on which BSCS Billing software is running
round the clock on Oracle 7.3.4.4.0 to provide the services to
the customers regarding their query about mobile, billing or
like that. So, we have to keep the database up all the time. We
find it very difficult to get time for any preventive
maintenence or any kind of maintenance in the server. Also, the
backup is very critical and important. Applications are also
interlinked between both the server. So, to shutdown one server,
another server needs to be down, this becomes very difficult. We
also have another server which we are using for test application
and daily database is exported/improted to that server. So, in
case needs come to shutdown the server, user can login to this
server and reply the customers queries. But, again due to large
database, daily import/export is also a cumbersome,time
consuming and resource intensive exercise. Can you please
suggest, which kind of architecture we should adopt to maintain
these servers and keep them up 100 percent and on the other hand
keeping the database secure.

Thanks & Regards,
and we said...
You might be interested in reading:
http://www.oracle.com/oramag/oracle/00-May/o30tom.html
which is a new article on this topic from Oracle magazine.

With 7.3.4.4, some of the options are:

o Standby databases.  If you have the capacity, we can have
a database in constant recovery mode on another machine.  If you
need to take a machine down for a period of time, you could
"fail over" to another location and run from there -- fix the
problem you have, and then "fail back" to the primary site.
This "fail back" will involve backing up the database you failed
over to, restoring it and catching it up via the archived redo
logs (in effect making the primary a standby site and then
"failing over" to it).

o OPS (Oracle Parallel Server).  This is much more feasible
with Oracle8i release 2 (8.1.6) when a new feature is added to
OPS for high availability without any impact to performance.
See:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/816.htm#43990
for info on that new feature.

o Hardware/Software OS oriented solutions.  EMC/Veritas and
others have many good options for availability.  I won't purport
to speak for them here but can attest to the fact that they have
some very good solutions in this space as well.

Some of the other solutions, such as replication, probably don't
apply in your particular case given the applications you have.
You cannot replicate Oracle Financials for example -- but you
can use Standby databases with it.

As for the export/import to the "test" instance -- you may
consider a backup/restore scenario.  Do a hot backup of your
production system, restore it on test and do a point in time
recovery.  That way -- you get a consistent view of the data,
you test your backup strategy, and it happens as fast as you can
copy bits from one disk to another.  It should be much faster
then export/import (no rebuilding of indexes and such)
May 15, 2000 prashant -- Thanks for the question regarding "scheduling backups", version
You Asked
1.How do I schedule Rman Online backup scripts.

2.How do I write a script for automating online backup (using
ocopy on NT).My script should run from OS prompt.I want to
schedule this scripts at OS (NT) level .
and we said...
OEM (Oracle Enterprise Manager) is the tool for doing that.  You
would schedule everything about the database through this tool

Well, for this you would have to write a .cmd file and use
SQLPlus or SVRMGRL to issue the necessary "alter tablespace
tablespacename begin/end backup" commands to Oracle.  This is a
straightforward exercise in NT .cmd scripting though.

To schedule this, you would use the NT 'at' scheduler or
something more sophisticated from some other 3'rd party.
May 15, 2000 steve -- Thanks for the question regarding "base2base question", version
You Asked
in the 1999 code archive there is a program :
base2base

however there appears to be a bug in it
when passed
33,10,2,8
which should produce a binary digit 8 long

when infact it produces a result only 4 long and incorrect

for
32,10,2,8
the result is 9 binary digets long
any fixes.
and we said...
Sorry -- i didn't write base2base and don't know anything about
it (although I confirmed it does not work).  I'll ask them to
pull base2base from the website.

In the meanwhile, you can goto
http://osi.oracle.com/~tkyte/hexdec/index.html
and get one that works.  It
has generic to_* functions to do base conversion functions so I
can for example:

ops$tkyte@dev8i> select lpad( to_bin(33), 8, 0 ) from dual;

LPAD(TO_
--------
00100001

ops$tkyte@dev8i> select lpad( to_bin(32), 8, 0 ) from dual;

LPAD(TO_
--------
00100000

There are to_hex, to_bin, to_oct, functions as well as

to_dec -- takes in a string and a base and returns a decimal
number after converting the string in that base to base 10.

to_base -- takes in a decimal number and a base and returns a
string after converting the decimal number to that base..

You would use lpad() to get the 'fixed' length string.
May 15, 2000 Calista -- Thanks for the question regarding "ftp 5 csv files daily.", version
You Asked
Hi Tom,
Since you were so helpful yesterday, here's
another little question -

I have five tables that I need to spool(?)
daily to comma delimited text files and then
FTP to a client.  I'd like to automate this
as much as possible - write a procedure that does
this rather than do it from the SQL command line.
What do you think would be the best way to do this?

Thanks.
and we said...
well, automating the ftp is the 'hard' part.

Here is how I would do it.  This assumes Unix as I use cron.  On
NT you would haveto find smething else to schedule the job.

I would use my utility "flat" (see
http://osi.oracle.com/~tkyte/flat/index.html
 and then automate the
task in a csh (i like the csh -- recode to whatever shell you
use)

------------------------------------------------------
#!/bin/csh -f

# need to setup environment set cron will not...

setenv ORACLE_HOME /export/home/oracle8i
setenv ORACLE_SID  ora8i
set path = ( $ORACLE_HOME/bin $path )

flat scott/tiger emp > emp.csv

ftp aria-dev <<EOF
cd /tmp
put emp.csv
quit
EOF

----------------- end of script -----------------------

to make it so the ftp can work without prompting for a
username/password, you need to setup a .netrc file in the home
directory of the account running this.  Do a "man netrc" for
more info on setting this up.

Then, I would use crontab -e to edit my crontab and add an entry
to be run once a day.
May 15, 2000 Stephen -- Thanks for the question regarding "slow import", version
You Asked
I'm trying a direct path import to a table that is
750MB in size.  The exported file I am using to import was
exported in a direct path method.  I have the buffer set at
200000 and commit=y but it takes 4 hours just to load this
table.
DB version is 8.1.5 and OS is Dynix/PTX.  Any suggestions?
and we said...

there is no such thing as a direct path IMPORT, only a direct
path load with SQLLDR and a direct path export with EXP.  Import
always

things to check for:

o do you see messages like ".... cannot allocate new log" in
your alert_$ORACLE_SID.log file?

o are you sure its just the data that is getting loaded -- you
aren't also importing the indexes which will get built right
after the table is loaded?  how about constraints as well -- are
they in there as well?  They will all take time after the data
is loaded.

o have you timed to see approximately how many rows/minute imp
is doing.  since you have commit = y, you can run:

select to_char( sysdate, 'hh24:mi:ss' ), count(*) from T;

and then run it again about a minute or so later.  Or use
feedback=N to get progress as it is loading.  Do you seem to be
loading a reasonable number of rows/minute?

o how is space management being done here?  what do the extents
look like.  Perhap you could pre-create the table and allocate a
good initial extent for it instead of doing lots of space
management during the load.
May 15, 2000 Ranjan -- Thanks for the question regarding "getting rows M through N", version
You Asked
How to select 10th to 20th record from a table.
i.e Suuppose table EMP contain 50 records but
I want to select 10th to 20th record then how to do that.

Thanks

Ranjan
Please e-mail the answer to
and we said...
You can use the psuedo column ROWNUM and INLINE views to perform
this operation.  For example:

scott@8i> select empno, ename, job, sal
  2    from (select emp.*, rownum r from emp where rownum <= 20)
  3   where r >= 10
  4  /

     EMPNO ENAME      JOB              SAL
---------- ---------- --------- ----------
      7844 TURNER     SALESMAN        1500
      7876 ADAMS      CLERK           1100
      7900 JAMES      CLERK            950
      7902 FORD       ANALYST         3000
      7934 MILLER     CLERK           1300

the trick here is to assign the rownum "R" in the inline view
and get all records less then the max.  Then the outer view can
use "R" to get rid of records below the low bound you don't
want.

You cannot use ORDER BY in the inline view in versions 8.0 and
below of the database.  In Oracle8i, release 8.1 and up you may
code:

scott@8i> select empno, ename, job, sal
  2    from ( select a.* , rownum r
  3             from ( select * from emp order by sal ) a
  4            where rownum <= 20
  5             )
  6   where r >= 10
  7  /

     EMPNO ENAME      JOB              SAL
---------- ---------- --------- ----------
      7698 BLAKE      MANAGER         2850
      7566 JONES      MANAGER         2975
      7788 SCOTT      ANALYST         3000
      7902 FORD       ANALYST         3000
      7839 KING       PRESIDENT       5000

scott@8i>

Here we created an ordered set in the inner most query, assigned
rownums to it and performed much the same operation as before.
May 15, 2000 Gloria -- Thanks for the question regarding "data integrity question.", version
You Asked
I have created 2 tables. examples

Create Table TestGroup (
Measkey  number(9) not null,
Location varchar(12),
Measure  varchar(15),
Type     varchar(12),
Userid   varchar(10),
Primary Key (MeasKey),
Unique (Type, Location, Measure,
userid)
);

Create Table ReportGroup(
GroupNum  number(9) not null,
GroupName varchar(12),
Span      varchar(15),
Type      varchar(12),
StartTime Number(4) not null,
Primary Key (GroupNum),
Unique (GroupName, Type);

I need to ensure that the value in the "Type" column in the
ReportGroup Table exists in the TestGroup table.

When I try to do this using a foreign key table contraint I
receive an error message that there is not a unique key for that

column in the TestGroup table.

Is there a way to enforce this data integrity.
and we said...
I would strongly suggest you do not use the word "TYPE" as an
identifier.  It can be used but will cause troubles for you in
Oracle8.0 and up --  in Oracle8.0 and up you can "create type
mytype ......"  so using TYPE as an identifier would be like
using TABLE as an identifier.

Referential integrity relies on a unique constraint on the
parent record.  RI is used to enforce a PARENT/CHILD
relationship.  A parent has 0, 1 or more children.  A child has
exactly one parent.  If ReportGroup.Type must exist in
TestGroup.type -- the Type column in TestGroup must be UNIQUE.
If you want to enforce this constraint with declaritive RI, you
need another table with unique types in it.
May 15, 2000 Arlando -- Thanks for the question regarding "converting from Sybase to Oracle.", version
You Asked
Greetings,

Is there a way to convert Sybase
datatypes to Oracle datatypes.

Thanks in advance.
and we said...

see:
http://technet.oracle.com/software/tech/migration/workbench/software_index.htm
you need a password for technet but they are free and you can get one right
away.
May 15, 2000 dhiraj -- Thanks for the question regarding "interfacing with oracle questions", version
You Asked
I got two questions both related to
interfacing

1) How to communicate between two instances of ORACLE other then
DB_LINK
as DB LINK has limitations of COMMIT
and ROLLBAK on remote instance.
Basically any way to implement message system with
acknowledgement without using third party software

2)How to communicate between B* TRIEVE
and ORACLE
and we said...
the database link has the natural limition that only the node
that INITIATED the transaction may end it.  The other nodes do
not know how many other nodes are involved in the transaction.

What do you mean by "limitations of COMMIT and ROLLBACK on
remote instance"  -- what limitations do you mean?  Can you
elaborate on that -- maybe then I can answer the question.

If you want to implement a messaging system -- I would suggest
you look at the Oracle Advanced Queues.  A simple implementation
of this as well would be the dbms_job package (thats available
with 7.3).  AQ is messaging software built into the database.

AQ is available with Oracle8.0 and up only.

As well, you can look into the deferred queues  -- they are in
7.3 as well.  See the replication manual or the distributed
systems II manual.

o A client application that connects to both data sources (eg
using odbc) could get data back and forth

o Using Oracle8.0 and up, you can write an EXTPROC (external
procedure) which lets you link in C code and make that callable
from a stored procedure/trigger.  Using this, you could provide
the B*Trieve api as a stored procedure.  that would let you get
to b*trievefrom Oracle.
May 15, 2000 anthony -- Thanks for the question regarding "How key mapping is done in D2K?. ", version
You Asked
How key mapping is done in D2K?. I want to chagne the
key mapping to assign some procedure or function to key triggers

such as KEY-F4 and KEY-F6 so that that function or procedure
will
be executed when pressing the function keys such as F4 and F6.
Kindly advice me how to do it.

Thanking you.
and we said...
Forms doesn't work with "f4" and "f6" because these function
keys do not exist on all keyboards of all types.  Rather forms
works with "keys that do functions".  What you would do is
discover what "f4" on your keyboard does and then implement the
appropriate trigger.  See the chapter "Function Key Triggers" in
the "Oracle Developer Form Builder Reference" document for a
list of all such key triggers.  You may override the default
behaviour of most -- but not all -- of these keys.
Review & Followup
Rating: 2
Mapping Keys October 30, 2001
Reviewer: Mohammed shabeeruddin from Saudia Arabia
It's true but Using Oracle Terminal We an Map Functions
Keys...
But I dont Know How to Map combination of Keys like
CTRl+F1 etc...

May 15, 2000 Kodiddala -- Thanks for the question regarding "'Oracle coding standards'", version
You Asked
Will you advice me, where to get 'Oracle coding standards'
and we said...
Try Feuerstein's PL/SQL Books published by O'Reilly.

You can find it at amazon.com (search for feuerstein under books
or try this link:
http://www.amazon.com/exec/obidos/ASIN/1565922387/qid=950030332/sr=1-1/104-0887172-9041204
)
May 15, 2000 PEDRO S -- Thanks for the question regarding "difference between 2 dates", version
You Asked
how can I calculate the difference in time between two
datetime stamp columns
and we said...
see
http://osi.oracle.com/~tkyte/Misc/DateDiff.html
May 15, 2000 tyrone -- Thanks for the question regarding "getting a linefeed.", version
You Asked
do you know where and how I can find ASCII code for
carriage return character in oracle 7.3.4 on HPUX
and we said...
decimal 13 is carriage return but it is more likely you are
looking for linefeed which is decimal 10.

ops$tkyte@8i> select '"' || chr(10) || '"' from dual;

'"'
---
"
"

ops$tkyte@8i> c/10/13
  1* select '"' || chr(13) || '"' from dual
ops$tkyte@8i> /

'"'
---
"

the carriage return (13) just points the line pointer back to
column 1.  Linefeed is like 'enter'.  On DOS, the pair
chr(13)||chr(10) is the end of line character, in Unix chr(10)
is.
May 15, 2000 ping -- Thanks for the question regarding "transactions with OAS3.0", version
You Asked
Now I'm developing a project on browser with Web
Application Server 3.0.1(advanced version) and oracle
database8.0. I wonder if there is a function of undoing some
steps in Web Application Server(that is, after the transaction is
committed, then I want to rollback it by clicking a button. Is
there a way to accomplish it?)
and we said...
Starting with v3 of OAS, yes, there is a transaction service you can use with
the plsql cartridge.

See:
http://www.olab.com/doc/books/plsql/pl_trans.htm
for a quick overview.  This is extraced from the "PL/SQL and ODBC Cartridges"
guide found at
http://www.olab.com/
 This is from the v4.x documentation (i don't have a copy of
the 3.x doc set) but the feature is basically the same.  you should be able to
find it in your docs given this information...
May 15, 2000 alex -- Thanks for the question regarding "copy data from one user to another.", version
You Asked
How can i copy a table from somebody else am put it on
my computer meaning from one user to other, also i apriciated if

you can send me the instruccion or syntaxes to how to do it
thank u Tom
and we said...
Well, if you are in the same database -- a simple:

SQL> create table my_table as select * from
other_user.their_table;

in sqlplus will do it.

If the table you want resides on another database -- you can use
a DATABASE LINK to get to it, so the above would become:

SQL> create table my_table as select * from
other_user.their_table@some_other_datbase;

You would need to setup the database link first though.

Another method that works on either a single database or on
databases on different machines would be to have the first user
do an export of the table:

$ exp userid=user1/pw tables=that_table

they would give you the expdat.dmp file that results and you can
then:

$ imp userid=your_name/pw fromuser=user1 touser=your_name

that will import their data into your schema.
May 15, 2000 Ahmad -- Thanks for the question regarding "read or write OS files.", version
You Asked
Can I write or read an operating system file
using oracle(8) package?
and we said...

Yes -- see the documentation in the "Supplied Packages Guide" (8i doc set) or
"Application Developers Guide" (8.0 doc set) for into on the UTL_FILE package.
It allows IO to and from TEXT files.

If you need to read a binary file, the BFILE operator and dbms_lob package
(documentation in same location as for utl_file) will do the job.

You cannot write a binary file using PL/SQL directly.  You can accomplish this
with an external procedure written in C or using Java stored procedures in
Oracle8i.
May 15, 2000 Ashish -- Thanks for the question regarding "RE: Ask Tom Submission", version
You Asked
1. how can we insert multiple century values into oracle tables

2.If we design a oracle based web application on developer 2000
which
requires frequent items validations
can we do this solely through d2k and oracle web server.if so
what is the effect.
and we said...
Use the to_date() function on input data to input any values you
wish.  for example:

insert into date_table values ( to_date( '01-jan-1983',
'dd-mon-yyyy' ) );
insert into date_table values ( to_date( '01-jan-1783',
'dd-mon-yyyy' ) );

Or, change the default date mask for your session with an alter
session command so that all dates default to your format (i
would use RRRR instead of YYYY if you do this).  For example:

ops$tkyte@8i> create table t ( x date );
Table created.

ops$tkyte@8i> alter session set nls_date_format = 'dd/mm/rrrr';
Session altered.

ops$tkyte@8i> insert into t values ( '01/4/1856' );
1 row created.

ops$tkyte@8i> insert into t values ( '01/01/00' );
1 row created.

ops$tkyte@8i> select * from t;

X
----------
01/04/1856
01/01/2000

The nice thing about RRRR is it defaults to the 50 year window
rule for the century.  It did not try to insert the year 0.
Trying this with YYYY shows:

ops$tkyte@8i> delete from t;

2 rows deleted.

ops$tkyte@8i> alter session set nls_date_format = 'dd/mm/yyyy';

Session altered.

ops$tkyte@8i> insert into t values ( '01/01/00' );
insert into t values ( '01/01/00' )
                       *
ERROR at line 1:
ORA-01841: (full) year must be between -4713 and +9999, and not
be 0

ops$tkyte@8i> insert into t values ( '01/01/01' );

1 row created.

ops$tkyte@8i> select * from t;

X
----------
01/01/0001

ops$tkyte@8i>

This inserts the year 1 -- which probably should have been the
year 2001

Can you elaborate on this .  I'm not sure what you are asking
here.

--
Thanks,

    Thomas Kyte                          tkyte@us.oracle.com
    Oracle Service Industries

    Oracle tips and papers
http://www.oracle.com/oramag/code/index.html
May 15, 2000 William -- Thanks for the question regarding "varchar >2000 ", version
You Asked
Using PL/SQL, how can I create a table
that have type varchar fields larger
than 2000?
and we said...
This is not really a PL/SQL question but a SQL question I
believe.  If you mean "table" as in persistent tables (not plsql
table types -- like arrays), then the VARCHAR2 type is limited
to 2000 characters in that release.  In Oracle8.0 and up, the
varchar2 type supports varchar2(4000) in database tables.

Prior to that -- the alternatives are:

o use the LONG type.  If you mainain 32k or less of text in this
field -- plsql can fully operate on this type.  For ease of use
-- i always recommend you store your longs "out of line" so that
you join to them.  For example do not:

create table T ( x int, y int, z int, ......<other scalar
fields>, TEXT long );

Instead:

create table T ( x int, y int, z int, ......<other scalar
fields>, text_id int );
create table t_text ( text_id int primary key, text LONG );

Having a long field in a table can really slow down operations
such as full table scans, index builds and limit your ability to
perform some operations such as "insert into ... select * from".
 Having the field factored out is the easiest approach.

o use >1 varchar2 field.  I myself do not like this approach too
much but many people use it.
May 15, 2000 Paul -- Thanks for the question regarding "Oracle Expert questions", version
You Asked
Is Oracle Expert still a product ?
Is it part of another product ?
If so, which one ?
How do you get oracle Expert ?
Thank You,
Paul Andrews
and we said...
Yes, Oracle Expert lives.  It is part of the OEM tuning pack.

See
http://www.oracle.com/take_control/index.html?/take_control/tuning.html
for info on that.

See
http://www.oracle.com/take_control/demos/tc399/expert.html
for a quick demo in shockwave.
or
http://www.oracle.com/take_control/demos/tn2_qt/exp1_01.htm
for an HTML version.

You would get this by getting the OEM tuning pack
May 15, 2000 srinivasan -- Thanks for the question regarding "how to start with java stored procedures.", version
You Asked
where can i get information on tutorials,examples,and
working code on java stored procedures in oracle 8i ?
and we said...
http://technet.oracle.com/
would be a great place to start.  In addition to having all
of the documentation online -- you can get access to examples
and samples, papers, etc.

technet is free - you need a login/password and they will send
you one right away after you sign up.

May 15, 2000 Getulio -- Thanks for the question regarding
      "When-Tree-Node-Selected question.", version

      You Asked
I've created a tree and it is populating correctly during the
when-new-form-instance trigger, but my question is that when I
click the mouse on a tree node, the when-tree-node-selection
trigger fires properly and the node is highlighted. But when I
select another node, the when-tree-node-selection trigger fires
twice. Once for the node it is "leaving" and once for the node
it is "entering" (the one I clicked on). I thought this trigger
should ONLY fire for the node I just clicked, not twice.

Is this a bug, or "a feature"???? Is there anyway just to have
the trigger fire for the node selected? I've heard that there
are many bugs with the new navigator tree item. Does anyone have

a list of these bugs/features?

Any help would be greatly appreciated.

Getulio

      and we said...
the documentation for when-tree-node-selected states:

---------------------------------------------------------
When-Tree-Node-Selected Trigger
Description
Fires when a node is selected or deselected.
Definition Level form or block
---------------------------------------------------------

Perhaps you can keep a global variable "last_node_selected" and
incorporate logic such as:

if ( nvl( global.last_node_selected, 'na' ) =
:SYSTEM.TRIGGER_NODE )
then
    return;  -- do not do anything, we must be leaving this node
end if;

global.last_node_selected := :system.trigger_node;

.... rest of code here .....

That way, you'll only process the 'tree-node-selected' event
ONCE per node -- not when leaving and entering.

Review &
      Followup

      Rating: 1
avoid to fire
      the WHEN-TREE-NODE-SELECTED trigger, when leaving the
      node  July 30, 2002
Reviewer:  Gerd Droscher
       from styria/austria/europe
In my case, I must avoid to fire the trigger when the last node is leaving!

I'm using Ftree.Set_Tree_Selection(htree, :system.trigger_node ,
Ftree.SELECT_ON);
in the WHEN-TREE-NODE-EXPANDED trigger to mark the new node, if've clicked on!

In this case, the WHEN-TREE-NODE-SELECTED trigger fires also for the previous
node!

How can I avoid this?!

gerd

May 15, 2000 Lise -- Thanks for the question regarding "Can we
      use a CD as input to SQL*LOADER?", version

      You Asked
Can we use a CD as input to SQL*LOADER?

      and we said...
The answer is absolutely.  To SQLLDR the CD just looks like a
file system (albeit a slow one).  If you can reference files on
the cd with normal file names and need no special utilities to
read them -- sqlldr will be able to use it natively.

May 15, 2000 David -- Thanks for the question regarding
      "pinning a sequence", version

      You Asked
Hi Tom,

I have been asked to 'pin a sequence' into the SGA.  I have a
vauge understanding of what is required, and i have researched
various books and althoughth they say you can do it, there's no
syntax to explain how.  Is it possible for you to explain how to
pin a sequence in the SGA.

The oracle version is 8.0.5 Enterprise for NT

Thanks Tom

      and we said...
to do this, we need to make sure the dbms_shared_pool package exists.  For
example, if you:

sys@ORA806.WORLD> connect sys/manager
Connected.
sys@ORA806.WORLD> grant execute on dbms_shared_pool to tkyte;
grant execute on dbms_shared_pool to tkyte
                 *
ERROR at line 1:
ORA-04042: procedure, function, package, or package body does not exist

find that it does not exists (it would ALWAYS be owned by SYS), you can install
it as such:

$ cd $ORACLE_HOME/rdbms/admin
$ svrmgrl

Oracle Server Manager Release 3.0.6.0.0 - Production

(c) Copyright 1999, Oracle Corporation.  All Rights Reserved.

Oracle8 Enterprise Edition Release 8.0.6.0.0 - Production
With the Partitioning and Objects options
PL/SQL Release 8.0.6.0.0 - Production

SVRMGR> connect internal
Connected.
SVRMGR> @dbmspool.sql
Statement processed.
Statement processed.
Statement processed.
Statement processed.
SVRMGR> @prvtpool.plb
Statement processed.
Statement processed.

that is -- run dbmspool.sql and the prvtpool.plb when connected as SYS or
INTERNAL using SVRMGRL (only those users!!!)

Now:

SVRMGR> grant execute on dbms_shared_pool to tkyte;
Statement processed.
SVRMGR>

works.  I can then:

SVRMGR> execute sys.dbms_shared_pool.keep('OWNER.SEQUENCE_NAME','Q');
ORA-06564: object OWNER.SEQUENCE_NAME does not exist
ORA-06512: at "SYS.DBMS_UTILITY", line 67
ORA-06512: at "SYS.DBMS_SHARED_POOL", line 35
ORA-06512: at "SYS.DBMS_SHARED_POOL", line 43
ORA-06512: at line 2

which shows what will happen if it cannot find the sequence you named.  Doing
this again with valid inputs:

SVRMGR> create sequence foo start with 1 increment by 1;
Statement processed.
SVRMGR> execute sys.dbms_shared_pool.keep('TKYTE.FOO','Q');
Statement processed.

I can see what I would see in a successful PIN operation on that sequence.

May 15, 2000 Denton -- Thanks for the question regarding
      "update cascade", version

      You Asked
How do I cascade update on the key
fields of linked tables thereby ensuring
referencial integrity.

      and we said...
see
http://osi.oracle.com/~tkyte/update_cascade/index.html
May 15, 2000 Tom -- Thanks for the question regarding "proc
      question", version

      You Asked
when trying to precompile an existing application we
are now getting the following error.

Pro*C: Release 2.0.5.0.0 - Production on Fri Feb  4 09:50:09
2000

Copyright (c) Oracle Corporation 1979, 1994.  All rights
reserved.

System default option values taken from: ora_proc20:pmscfg.cfg

Syntax error at line 331, column 13, file ora_precomp20:stdio.h:
typedef const char * __const_char_ptr32;
............1
(1) PCC-S-02201, Encountered the symbol "const" when expecting
one of the
follow
ing:

char, double, enum, float, int, long, short, signed, struct,
union, unsigned, varchar, void, a typedef name, etc.

An extract from the indicted header file follows to illustrate
what the compiler finds objectionable.

We get the same error even when trying to precompile the sample
files.
Any idea why this version of the precompiler doesn't like this
typedef construct?
Do you know of any recommended work arounds?

      and we said...
[snip]

wow, that precompiler is really really old (like 7 years old).

Try adding "parse=none" to the pro*c command line.  that was the
first version of pro*c to support advanced C constructs and
attempted to parse the C code.  By adding "parse=none", it
should be able to accept any C code valid or invalid.

May 15, 2000 Chris -- Thanks for the question regarding "long
      copy over a db link", version

      You Asked
Insert into "table" select * from view@dblink is taking
far too long. Any suggestions on how to improve this performance
?.

      and we said...
If you are doing this from the command line or can use SQLPlus,
I would recommend using the sqlplus COPY command.  It can be
many times faster then an insert into select from....  the copy
command will array fetch from the source and array insert into
the target (insert into does row at a time processing).  the
copy command can also commit batches of inserts if you wish.

See
http://osi.oracle.com/~tkyte/Misc/MoveLongs.html
for an example and the sqlplus documentation for more
information.

May 15, 2000 abhishek -- Thanks for the question regarding
      "using quotes in sqlplus", version

      You Asked
how can i ignore special characters such as single
quote (') in sql queries using SQL Plus ?

      and we said...
Two ways.

To put a quote in a character string constant -- you use two
quotes.  for example:

insert into t value ( 'How''s this work' );

the '' is really a '.

The other way is to concatenate it in.  for example:

insert into t values ( 'How' || chr(39) || 's this work' );

Review &
      Followup

      Rating: 5
Excellent
      answer: "using quotes in sqlplus"  March 19, 2002

Reviewer:  Lusiana Lusiana  from Wollongong,
      Australia
As always, a right-to-the-point answer. I've been looking
for the answer to this question for a while until I found this. Your effort in
answering these questions is much appreciated.

May 15, 2000 Linda -- Thanks for the question regarding "How
      can I print data/files to printer inside a PL/SQL ", version

      You Asked
How can I print data/files to printer inside a PL/SQL
stored procedure? Or if it's impossible to print directly, may I

call some UNIX shell scripts to do so? My database server is
located on UNIX system. Thank you!

      and we said...
sorry for the delay in answering.  Some of the questions got
stuck in the queue and did not get forwarded to me in a timely
fashion.  I just recieved yours today (Feb 5'th).  I hope this
is still of some help....

If you are using Oracle8i, release 8.1 -- much can be done with
Java.  java would be able to print directly from the server.

using plsql your options would be:

o write an external procedure in C that did the actual printing.
 I've attached a small extproc sample so you can see what it
looks like

o use UTL_FILE to print the report from plsql and then use a
unix CRON job to pick up and print spooled files.  You might do
something like:

- have the procedure create the file "123456.dat" and when that
is done (it contains the report) and when you are done creating
the report, you would create the file "123456.done".  The cron
job would find all of the .done files, print the .dat files and
remove them.  This is how sendmail works for example.  123456
would be generated via a sequence.

o use UTL_FILE like the above but then use UTL_HTTP to run a
cgi-bin program if you have a webserver on the same machine as
the database.  the cgi-bin program would print the file that
plsql just wrote.  I use this to send emails from the database
-- the cgi-bin program emails the file utl_file wrote.

May 15, 2000 Carl -- Thanks for the question regarding
      "returning object type to oci", version

      You Asked
We have a procedure that operates on a table called orders

create or replace procedure set_tbl_orders      (
a_odr_id                in      int     := 0,
a_odr_taken_date        in      int     := 0,
--
a_orders                out     TBL_Orders,
a_order_count           out     int
)

It returns the rows that have been changed or added on the
TBL_ORDERS parameter.
This type is defined thus:

CREATE or REPLACE TYPE TBL_Orders as table of REC_Orders;

Where the the complete set of columns of a table is defined as
an
object type REC_Orders

CREATE or REPLACE TYPE REC_Orders as OBJECT (
odr_id                  int,
jf_odr_id               varchar2(10),
del_f                   varchar2(1),
grp_odr_id              int,
    status                  varchar2(10),
ext_sys_mnem            varchar2(20),
ext_sys_odr_id_1        varchar2(32),
ext_sys_odr_id_2        varchar2(32),
odr_taken_loc_mnem      varchar2(10),

);

We want to call this stored procedure from a C program using
Oracle OCI and
have the results passed back through the OUT parameter
(TBL_Orders)of type table.
Is it possible to do this with Oracle Call Interface?  If it is
possible
could you show me an example.  I'm finding it difficult to work
out.

      and we said...
I do not have an example interfacing directly to an Object Type
from OCI however, I feel I might have an interesting solution.
It allows for a SQL based solution.

ops$tkyte@8i> CREATE or REPLACE TYPE REC_Orders as OBJECT (
  2           odr_id                  int,
  3           jf_odr_id               varchar2(10),
  4           del_f                   varchar2(1),
  5           grp_odr_id              int,
  6          status                  varchar2(10),
  7           ext_sys_mnem            varchar2(20),
  8           ext_sys_odr_id_1        varchar2(32),
  9           ext_sys_odr_id_2        varchar2(32),
 10           odr_taken_loc_mnem      varchar2(10)
 11   );
 12  /

Type created.

ops$tkyte@8i> create or replace type myTableType as table of
Rec_Orders;
  2  /

Type created.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> REM now, we want to "select * from
PLSQL_FUNCTION()" not from a table:
ops$tkyte@8i>
ops$tkyte@8i> create or replace function getMyTableType(
p_inputs in int ) return myTableType
  2  as
  3          l_x     myTableType := myTableType();
  4  begin
  5          for i in 1 .. p_inputs loop
  6                  l_x.extend();
  7                  l_x(l_x.count) := Rec_Orders(i,'id='||i,
'a', i*10, 'valid', 'a','b','c','d');
  8          end loop;
  9          return l_x;
 10  end;
 11  /

Function created.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> REM here we go... selecting from it:
ops$tkyte@8i>
ops$tkyte@8i> select *
  2    from THE ( select cast( getMyTableType(5) as mytableType
) from dual ) a
  3  /

    ODR_ID JF_ODR_ID  D GRP_ODR_ID STATUS     EXT_SYS_MNEM
  EXT_SYS_ODR_ID_1
---------- ---------- - ---------- ----------
-------------------- --------------------------------
EXT_SYS_ODR_ID_2                 ODR_TAKEN_
-------------------------------- ----------
         1 id=1       a         10 valid      a
  b
c                                d

         2 id=2       a         20 valid      a
  b
c                                d

         3 id=3       a         30 valid      a
  b
c                                d

         4 id=4       a         40 valid      a
  b
c                                d

         5 id=5       a         50 valid      a
  b
c                                d

Perhaps you can use this.  If your function that fills the table
is not 'pure' enough to be called from SQL -- you can use a
PACKAGE to do this.  The package would have the l_x variable as
a global and you would have two entry points -- one procedure to
fill the global table and a function to return this global
variable.

this'll let you WHERE on the object type, SORT it, join it, etc
etc etc.

May 15, 2000 sanchaita -- Thanks for the question regarding
      "How to copy a set of tables from one user to another user", version

      You Asked
How to copy a set of tables from one user to another user.

      and we said...
The easiest method is to EXP the tables from the one user.  For
example:

exp userid=user1/pw  'tables=(table1,table2,table3....)'

or

exp userid=user1/pw owner=user1      (gets everything)

and then IMP the data using the FROMUSER TOUSER options:

imp userid=user2/pw fromuser=user1 touser=user2

May 15, 2000 hemant -- Thanks for the question regarding "i
      need some documentation on creating triggers ", version

      You Asked
i need some documentation on creating triggers

      and we said...
That is in the Application Developers Guide

http://technet.oracle.com/doc/server.815/a68003/01_13dbt.htm#376
You need a password for technet but its free and you can get one
right away.  Technet has lots of other resources as well
(samples, papers, etc)

May 15, 2000 -- Thanks for the question regarding "RE:
      inserting images into BLOB column", version

      You Asked
-----Original Message-----
From: Geoff Muldoon [mailto:gmuldoon.nospam@scu.edu.au]
Sent: Thursday, February 03, 2000 3:24 AM
To: tkyte@us.oracle.com
Subject: Re: inserting images into BLOB column

On Tue, 25 Jan 2000 08:37:05 -0500, you wrote:
>
>Here is a short example but see the plsql manual in 8.0 or the
LOB manual in 8i.

Thomas,

Any chance of some sample code that will allow me to use the
HTML FORM
tag:
<input type="file" name="file_name" >
so that a user with a web browser can pass an image file as a
variable
to a procedure and drop the image straight into a blob column?

PS.  You do a great PR job for Oracle in UseNetLand!

Geoff Muldoon
Southern Cross Uni
Australia
email: gmuldoon@scu.edu.au

      and we said...
No, but you can use the OWA Replacement cartridge at my web site
(below) to do that  if you have a C compiler.

--
Thanks,

    Thomas Kyte                          tkyte@us.oracle.com
    Oracle Service Industries

    Oracle tips and papers
http://osi.oracle.com/~tkyte/

thanks much.

May 15, 2000 Premal -- Thanks for the question regarding "RE:
      Ask Tom Submission", version

      You Asked
Any caveats with configuring the Oracle Gateway for SQL
Server?  Followed documentation to the t, no success.
Individual
components check out OK.  Cannot connect to SQL Server database
from Oracle.  Get FDS_CLASS_NAME not defined error message.  Any

help wil be appreciated.

      and we said...
I found this note in the support database:

=================================================================
========
   When trying a select get the following error :-

ora-28557 - fds_class_name unknown for database link to non
oracle system.
ora-2063 - preceding lines from msql.

   A gateway debug trace has the following entries :-

DEBUG LEVEL = DEBUG <101>
*** HGINIVAL ***
hginival: <2> <TARGET>
hginival: env  <TARGET> not found
hginival: exit returning <942>
hgagprd: default <TARGET> => <9> <CORE_ODBC>

Oracle Transparent Gateway for MS SQL Server 6: Version Version
8.0.4.1.0
- Production

*** HGAGPRD ***
Connection Information <FDS_CLASS> => <>
Connection Information <FDS_INSTANCE> => <MSQL>
hgagprd: exit returning <0>

   The entries for a working system should be :-

hginival: env  <TARGET> => <6> <MSSQL6>

   and

Connection Information <FDS_CLASS> => <ODBC2_8.0.4_MSQL_65>

  This is caused by an incorrect gateway INITsid.ORA file.
  The entries for TARGET and DATA_SOURCE_NAME will have been
entered as :-

  SET TARGET = MSSQL6
  SET DATA_SOURCE_NAME = odbc_data_source_name

  Remove the "SET", stop and restart the gateway and it should
now work.
  That is, entries should be :-

  TARGET = MSSQL6
  DATA_SOURCE_NAME = odbc_data_source_name
=================================================================
========

If that does not correct the error, please be sure to include
the versions of all products involved and the OS platforms as
well.  A cut and paste of the error message would be great as
well.

--
Thanks,

    Thomas Kyte                          tkyte@us.oracle.com
    Oracle Service Industries

    Oracle tips and papers
http://www.oracle.com/oramag/code/index.html

May 15, 2000 uli -- Thanks for the question regarding
      "Inserting long strings", version

      You Asked
When inserting a field value into a LONG
Datatype, I get a 1704 oracle error which
means that the String literal which bears
the field Value, is too long. How do I
get around this? Is there an Oracle
Function that I need to use to massage the
String value?? Otherwise, it's a catch22
I have a datatype which allows 2 gig, yet
when using a String exceeding 2500 characters
the insert or update using this field blows out.

      and we said...
Character string constants in SQL (things in quotes) cannot
exceed 2000 characters in Oracle7 and 4000 characters in
Oracle8.  In order to use longer strings, you must use a bind
variable.

See
http://osi.oracle.com/~tkyte/Misc/LargeStrings.html
for more information.

May 15, 2000 Ivan -- Thanks for the question regarding "how
      can I clear the buffer with regards to a column heading", version

      You Asked
Hi Tom,

In SQL*Plusw how can I clear the buffer with regards to a column

heading without setting the values again?

An example is:
column fname format a10 heading 'First Name'

how do I get the next script to export the column heading as
just
fname and the full 20 characters?

Thanks again ahead of time

      and we said...

Use the SQLPlus clear command:

ops$tkyte@8i> column object_name format a1
ops$tkyte@8i> column object_name clear
ops$tkyte@8i> select object_name from user_objects;

OBJECT_NAME
-----------------------------------------------------------------
-----------------------------------
A
ADDRESSES
B
BAD_CHARS
BONUS
C
CHECK_PASSWORD

May 15, 2000 Kadikatla -- Thanks for the question regarding
      "forms with a firewall", version

      You Asked
Applications developed in Developer6.0
and using Oracle Developer Server, Oracle Application Server and

Oracle 8i in Server Side, Still I cannot deploy my applications
on the Internet. Reasons mentioned are 'Firewall' at client-side

doesn't permit. But,most client PC's will have Firewall
Protection which is mandatory.Can you explain in  detail how to
come across this issue??

      and we said...
Currently, a facility to use HTTP/1.1 as the protocol between
the forms java client and the forms server is in BETA with the
Developer 6.0 product.  It is slated to go production with the
6i release this spring.  That will allow the java client to go
behind a firewall and still talk to the webforms server.

May 15, 2000 Sudhakar -- Thanks for the question regarding
      "index question", version

      You Asked
Hi !
We have a Item Master in Oracle 7.
Primary Key = Company, ItemCode.
Also some other fields like :
Desc VARCHAR(30)
Model VARCHAR(15)
LOOKUPNO VARCHAR(10)
etc.

Since the item master is a large file (appr.220,000 rows),
we use LOOKUPNO to search the item code.
eg. for an item like Model No. X717,
LOOKUPNO will contain : 717.
Also lookupno is not unique.
So, when we go for lookup table , in context menu,
when 717 is typed, all the codes having '717' in LOOKUPNO
should be listed together. In fact, this is happeing now.
Only problem is, it takes a long time to search.

Here, I would like to ask, whether we can index on that field
i.e.LOOKUPNO., and in SELECT clause USE THE INDEX ?
By just indexing on that field did not solve the problem.
At present, we creted a table (with the trigger on item master)
having the fields as company,LOOKUPNO,itemcode as primary key,
and only other fields need to show in the lookup list.
Since the company and lookupno fields are part of the primary
key,
this has improved the performance - select,
but this is the burden for the server.
Please letus know any other alternatives.

      and we said...
are you using the Cost Based Optimizer of the Rule Based.  It
sounds like you are using the CBO and you have not analyzed the
tables in a long time.  Can you verify which optimizer you are
using and verify that statistics have been collected.

Short of that, if I submit a query:

select * from T where lookupno = :variable

I would anticipate it using the index using the RBO (always) and
when using the CBO if:

o statistics are up to date
o the table has lots of rows (it does but do the stats reflect
that)
o lookupno is SELECTIVE (eg: if you have 220,000 rows you should
have at least 22,000 distinct lookupno -- if you do not, the CBO
may opt for a full tablescan).

You can try setting the optimizer goal to first rows which would
have the CBO pick the index over the full scan in the last case
above.

May 15, 2000 GARCIA -- Thanks for the question regarding
      "paritioning option", version

      You Asked
Hi Tom, I need to create a partitioned table in Oracle
8.0.5 Server (Workgroup Edition for UnixWare 7.1.0) do i need
some kind of package to enable this feature instead of install
Oracle Enterprise Server?

      and we said...
The partitioning option is an extra cost option available only
with the enterprise server.

See
http://technet.oracle.com/doc/server.815/a68020/ch4.htm#58509
for a feature/function matrix.  It is for 8i but most
of it applies to 8.0 as well.  You need a password for technet
-- they are free and may be gotten right away.  Good resource to
have access to in any case.

May 15, 2000 sunil -- Thanks for the question regarding
      "display result sets from plsql in sqlplus", version

      You Asked
When I use this script to display a record set only it
shows that Pl sql successfully complteted .?
I want to display all the row and column in a table;
The sript used was

create or replace Procedure  test1  as
c1 integer;
--- other declarations
begin
c1 := dbms_sql.open_cursor;
dbms_sql.parse(c1, 'select *  from test' , 1);
----  other statements
----  other statements
end;

test is the datatable

      and we said...

You need to do 1 of 2 things:

o use a ref cursor or..
o format and print the results yourself using dbms_output.

For the first, I'll refer you to
http://osi.oracle.com/~tkyte/ResultSets/index.html
 It shows ref cursors from interacting in
various environments. In Oracle8i, release 8.1 (i assume that is the version you
have), a real short example for sqlplus would be:

ops$tkyte@8i> variable x refcursor
ops$tkyte@8i>
ops$tkyte@8i> begin
  2          open :x for 'select * from dept';
  3
  4          -- other statements;
  5  end;
  6  /

PL/SQL procedure successfully completed.

ops$tkyte@8i>
ops$tkyte@8i> print x

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON

for the second, you would use dbms_output.  It could look like this (and it will
only work in SQLPlus and SVRMGR)

ops$tkyte@8i> set serveroutput on
ops$tkyte@8i> declare
  2          type rc is ref cursor;
  3          c       rc;
  4          r       dept%rowtype;
  5  begin
  6          open c for 'select * from dept';
  7          loop
  8                  fetch c into r;
  9                  exit when c%notfound;
 10                  dbms_output.put_line( r.deptno || ' ' || r.dname );
 11          end loop;
 12          close c;
 13  end;
 14  /
10 ACCOUNTING
20 RESEARCH
30 SALES
40 OPERATIONS

PL/SQL procedure successfully completed.

Review &
      Followup

      Rating:
      5
  March 20, 2003
Reviewer:
      A reader

May 15, 2000 subhash -- Thanks for the question regarding
      "sqlcxt undefined", version

      You Asked
Sir, I have typical problem.
I am writing proc code first time,
I have written simple code to connect database and display
emp_no
and name.

When i have issued the follwoing command

$proc sample1.pc

It has created a sample1.c file and
when i issued command

$cc sample1.c
It has given me error
Undefined                       first referenced
symbol                             in file
sqlcxt                              sam1.o
ld: fatal: Symbol referencing errors. No output written to a.out

Actually sir i don't known what all the settings i have to do in

my .profile
or any thing else

Can you pls mail me the details at
bhandari@irs.co.id

Thanks

Subhash Bhandari

      and we said...
You need to link in the Pro*C Libraries.

See
http://govt.oracle.com/~tkyte/proc_makefile/
 for an example, generic makefile for Pro*C.

May 15, 2000 Paulinda -- Thanks for the question regarding
      "what does error XXXX mean", version

      You Asked
Where can i find the codumentation for error messages
from SQL*LOADER, i.e.
ORA-000904, ORA-02373

      and we said...
You can see the document "Oracle8i Error Messages" which is
online at
http://technet.oracle.com/doc/server815.htm
 You need a password for this site but they are
free and you can sign up immediately.  You should have an online
copy of this document yourself as well (from the install CD).

Also, on UNIX, you can always go:

$ oerr ora 2373

02373, 00000, "Error parsing insert statement for table %s."
// *Cause: self-evident.
// *Action: Check the error given below this one.

The command oerr will print this out.  Additionally -- in
sqlplus you can:

ops$tkyte@8i> set serveroutput on

ops$tkyte@8i> exec dbms_output.put_line( sqlerrm(-904) );
ORA-00904: invalid column name

PL/SQL procedure successfully completed.

To see what the error text is briefly.

May 15, 2000 Gobchai -- Thanks for the question regarding
      "drop index with special characters", version

      You Asked
how do i drop an index with an invalid character in
it's name? The name contains the character "~".

      and we said...
Using quoted identifiers allows you to manipulate any object
name -- ones in mixed case, with special characters and so on.

it would look like this:

ops$tkyte@8i> create index "with a-dash" on emp (job);

Index created.

ops$tkyte@8i> drop index "with a-dash";

Index dropped.

ops$tkyte@8i>

May 15, 2000 Gregory -- Thanks for the question regarding
      "using dynamic sql in SQLJ", version

      You Asked
Using SQLJ, Is there a way to dynamically create a
query and its associated Iterator for the result set?

      and we said...
Yes, you would drop down to JDBC at this point.  You can convert
a SQLJ connection into a JDBC connection (and vice versa).  This
is snipped from the SQLJ documentation, chapter 7, "SQLJ and
JDBC Interoperability":

JDBC and SQLJ Connection Interoperability for Dynamic SQL

Following is a sample method that uses the underlying JDBC
connection instance of the default SQLJ connection context
instance to perform dynamic SQL operations. The dynamic
operations are performed using JDBC java.sql.Connection,
java.sql.PreparedStatement, and java.sql.ResultSet objects. (For
information about such basic features of JDBC programming, see
the Oracle8i JDBC Developer's Guide and Reference.)

import java.sql.*;

public static void projectsDue(boolean dueThisMonth) throws
SQLException
{
   // Get JDBC connection from previously initialized SQLJ
DefaultContext.
   Connection conn =
DefaultContext.getDefaultContext().getConnection();

   String query = "SELECT name, start_date + duration " +
                  "FROM projects WHERE start_date + duration >=
sysdate";

   if (dueThisMonth)
      query += " AND to_char(start_date + duration, 'fmMonth') "
+
               " = to_char(sysdate, 'fmMonth') ";

   PreparedStatement pstmt = conn.prepareStatement(query);
   ResultSet rs = pstmt.executeQuery();
   while (rs.next())
   {
      System.out.println("Project: " + rs.getString(1) + "
Deadline: " +
      rs.getDate(2));
   }
   rs.close();
   pstmt.close();
}

May 15, 2000 Kyrna -- Thanks for the question regarding
      "printing a word doc", version

      You Asked
I want print a document of Microsoft word make from
Oracle. I Make this document using the library Word, by I need
too print and close this document

      and we said...
You have 2 options that I can see.

o In order to print a word document natively, you need to
retrieve the document to a client machine that has word
installed and using whatever client tool you used to retrieve
the document -- tell word to print that document using OLE or
some other technique.  If the database is on an NT machine -- it
may be possible to print right from the database using a java
stored procedure to write the document to the file system and
then invoking a copy of word that is installled on the database
server.  I have not tried that myself but it may be something to
investigate.

o you can use the filters in Intermedia (the context component)
to convert the word document that is in the database to some
other format (HTML, plain text, etc)  and then print this other
format without the use of word.

May 15, 2000 Sunil -- Thanks for the question regarding
      "FRM-40202", version

      You Asked
In Developer form 6.0 if the required property of a
feild is set as true i am not able to close the screen using
Alt+F4 . it says that the field must be entered. Is it possinle
to remove this constraint when i want to come out of the screen
?

      and we said...
This is the way forms is designed to work.

If the field is required but you want to give users the freedom
to fill out the record in any order, consider setting the
Required property to FALSE and adding a WHEN-VALIDATE-RECORD
trigger to ensure that the item is filled in with a legal value.
 This will let you close the block as well.

Another option might be the clear_record builtin:

To cancel changes made in a record without having to enter
values in the
required fields:

1.  Use the Record->Clear Menu Option:
    ----------------------------------
    The form operator can use the Record->Clear menu option from
the default
    Oracle Forms Runform menu.

2.  Use the CLEAR_RECORD built-in:
    ------------------------------
    You can programmatically call the CLEAR_RECORD Oracle Forms
built-in.

    For example:

    You could have a button labelled 'Cancel', and the following

    When-Button-Pressed trigger:

    BEGIN
        CLEAR_RECORD;
    END;

    NOTE:

    Make sure the 'Mouse Navigate' item property for the button
is FALSE.
    Otherwise required field validation will not allow
navigation out of a
    required field when trying to press the 'Cancel' button, if
data has not
    been entered.

May 15, 2000 tony -- Thanks for the question regarding "I want
      to develop java appliction ", version

      You Asked
Hi:
I want to develop java appliction on web pages.But I have to use
IE 4,5.
Can I use that?

      and we said...
Do you want to create a java applet that is downloaded to the
browser and run on the client.  If so, that is straightforward
(and isn't really an Oracle question -- you can use Jdeveloper
or virtually any java development environment to do this).

Or

Do you want to create HTML pages using java?  If so

o OAS 4.0.8 supports java servlets.
o OAS 4.0.8.2 supports JSP (java server pages, like ASP but with
java, not VB)
o OAS 2.x and up support writing cartridges in Java
o Oracle8i, release 8.1 and up support the writing of Java
Stored Procedures which may be invoke by the plsql catridge of
any release of OAS
o Oracle8i supports also EJB's in the database.  You can write
java that executes on the client and talks directly to the
database using EJB's (as well as of course JDBC).

the choice of a browser is not relevant.
May 15, 2000 Valerio -- Thanks for the question regarding
      "skipping columns with sqlldr", version

      You Asked
I have a csv file that I want to import with SQL loader
but I don't want to import some of the csv fields. What can I
do?

      and we said...
see
http://osi.oracle.com/~tkyte/SkipCols/index.html
for a couple of methods of doing this....

May 15, 2000 Hans-Martin -- Thanks for the question regarding
      "blob storage question", version

      You Asked
I have a table with a blob column.
It's possible to specify an extra
storage clause for this column ?

      and we said...
Yes, the following example is cut and pasted from the SQL
Reference Manual, the CREATE TABLE command:

CREATE TABLE lob_tab (col1 BLOB, col2 CLOB) STORAGE (INITIAL 512
NEXT 256)
LOB (col1, col2) STORE AS
    (TABLESPACE lob_seg_ts
       STORAGE (INITIAL 6144 NEXT 6144)
       CHUNK 4
       NOCACHE LOGGING
       INDEX (TABLESPACE lob_index_ts
       STORAGE (INITIAL 256 NEXT 256)
    )
);

The table will be stored in the users default tablespace with
(INITIAL 512 NEXT 256).  The actual lob data will be in
LOB_SEG_TS with (INITIAL 6144 NEXT 6144).  The lob index built
on the pages constituting the lob will be stored in yet a 3'rd
tablespace -- lob_index_ts with (INITIAL 256 NEXT 256).

May 15, 2000 vincent -- Thanks for the question regarding
      "SQLNet on a WAN", version

      You Asked
Hi,

Poor performance (compared to IBM Mainframes) of our
client/server
applications using Sql*Net on the WAN leads us to consider
forbidding
the use of Sql*Net (V2/V8) on the WAN.

May I have your opinion on this ?

Do you know where to find some whitepapers or case studies on
Sql*Net
performance on the WAN ?

      and we said...
I need more information.  Properly done, SQLNet on a WAN is as
good as anything else.  We use SQLNet on a WAN frequently in
Oracle.

o What is the client tool you are using?  It has a major impact
on this.

o What is your approach to client/server design?  do you use
stored procedures?

o Do you use our Array processing -- particularly array
fetching?  This reduces the network round trips dramatically.

o Are you comparing Apples to Oranges when you compare the
mainframe apps to a client/server gui over SQLNet.  For example,
with the Mainframe, typically you are doing block oriented
'screen' io to the server (much like a web page).  The client
sends some screen data to the mainframe, mainframe processes and
sends at most a screen of data to the client.  In a
client/server app, you are typically pulling the data (more then
a screen full) back to the client.  They are very different.
What would be a fair comparision would be to place a webserver
or application server on a LAN with the database and use HTML
pages to interact with the database via the application server
(eg: use HTTP over the WAN, SQLNet on the LAN).  Then we would
be comparing similar environments.  I myself am extremely fond
of this solution -- for more then just performance reasons
(maintenance comes to mind immediately).

o What are your WAN characteristics?  (eg; speed/latency.  Is it
a fast WAN with long turnaround times?  This will impact client
server radically as client server tends to be 'chatty'.  We
would use array processing and stored procedures to reduce this
chat)

May 15, 2000 I Gusti -- Thanks for the question regarding "RE:
      [Fwd: Ask Tom Submission] TkProf/Explain Plan question", version

      You Asked
hi , Mr. Tom ...!!! I come from Bali island ( bali is a part
of Indonesian country). To the point , I want to ask you more about
optimization query ...!!!
what should I do if I use Oracle (personal Oracle7) as a tool to build
an information system with optimization query.

One more, sir !!! I can use TKProf72.exe to compile the EXPLAIN PLAN
from sqlplus editor. The question is : can I use Visual Basic 5 to load
TKPROF72.exe and display the result on the form of visual basic that
I've made .

Sir, If you have the source code or the sample program, please send to
my email !!! I am an analyst system from TELKOM (one of the
telecomunication company in Indonesia) and I am doing a project thant
has relationship with optimization query.

thank you very much for your help !!!!
I will wait for your comment !!!!
please send to igusti@mailcity.com

      and we said...
I like to use "autotrace" to perform tracing in SQLPlus.  I forget which version
of SQLPlus added autotrace (it might have been 7.2) but 7.3 has it for sure
(reason enough to upgrade -- 7.2 is very very old).

Here is a sample of autotrace (directions for setting it up are attached)

SQL> SET AUTOTRACE ON

SQL> SELECT D.DNAME, E.ENAME, E.SAL, E.JOB
2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO = D.DEPTNO
SQL> /

DNAME          ENAME             SAL JOB
-------------- ---------- ---------- ---------
ACCOUNTING     CLARK            2450 MANAGER
ACCOUNTING     KING             5000 PRESIDENT
ACCOUNTING     MILLER           1300 CLERK
RESEARCH       SMITH             800 CLERK
RESEARCH       ADAMS            1100 CLERK
RESEARCH       FORD             3000 ANALYST
RESEARCH       SCOTT            3000 ANALYST
RESEARCH       JONES            2975 MANAGER
SALES          ALLEN            1600 SALESMAN
SALES          BLAKE            2850 MANAGER
SALES          MARTIN           1250 SALESMAN
SALES          JAMES             950 CLERK
SALES          TURNER           1500 SALESMAN
SALES          WARD             1250 SALESMAN

14 rows selected.

Execution Plan
-----------------------------------------------------------
0      SELECT STATEMENT Optimizer=CHOOSE
1    0   MERGE JOIN
2    1     SORT (JOIN)
3    2       TABLE ACCESS (FULL) OF 'DEPT'
4    1     SORT (JOIN)
5    4       TABLE ACCESS (FULL) OF 'EMP'

Statistics
----------------------------------------------------------
148  recursive calls
  4  db block gets
 24  consistent gets
  6  physical reads
 43  redo size
591  bytes sent via SQL*Net to client
256  bytes received via SQL*Net from client
 33  SQL*Net roundtrips to/from client
  2  sorts (memory)
  0  sorts (disk)
 14  rows processed

So, the autotrace shows the query plan and various server statistics (much like
the tkprof report would) but it does it in "real time" -- you do not have to
find the trace file, and then run tkprof against it and then edit the report.
It is all right there.

Probably but what be easier is to use VB to directly submit a query to the
database to be explained and then query the plan table.  You would want to
review the documentation for the EXPLAIN SQL command.  this will allow your VB
program to submit a query to the server and have the query plan appear in the
PLAN_TABLE.  You can then use SQL to review / query this plan.  See the SQL
Language manual for the EXPLAIN command.

May 15, 2000 PRAMOD -- Thanks for the question regarding "are
      reserved words in a table?", version

      You Asked
Does Oracle store "oracle reserved words" in any table ? If so
how to get them in SQLPLUS/SQL-WORKSHEET environment.

      and we said...
No but we can write a function to tell us if a given word is a
reserved word (don't know if this will help in your case but you
might be able to use it).

it would look like this:

ops$tkyte@8i> create or replace function is_reserved( p_word in
varchar2 ) return varchar2
  2  as
  3      exec_cursor     integer default dbms_sql.open_cursor;
  4      rows_processed  number  default 0;
  5      stmt            varchar2(255);
  6  begin
  7      stmt :=  'select dummy ' || p_word || ' from dual';
  8      dbms_sql.parse(exec_cursor, stmt, dbms_sql.native );
  9      stmt :=  'declare ' || p_word || ' number; begin null;
end;';
 10      dbms_sql.parse(exec_cursor, stmt, dbms_sql.native );
 11      dbms_sql.close_cursor( exec_cursor );
 12          return 'N';
 13  exception
 14          when others  then
 15                  if ( dbms_sql.is_open( exec_cursor ) ) then
 16                          dbms_sql.close_cursor( exec_cursor
);
 17                  end if;
 18                  return 'Y';
 19  end;
 20  /

Function created.

ops$tkyte@8i> begin
  2          dbms_output.put_line( 'SELECT ' || is_reserved(
'SELECT' ) );
  3          dbms_output.put_line( 'OK     ' || is_reserved(
'OK' ) );
  4          dbms_output.put_line( 'BEGIN  ' || is_reserved(
'BEGIN' ) );
  5          dbms_output.put_line( 'X      ' || is_reserved( 'X'
) );
  6          dbms_output.put_line( 'COMMIT ' || is_reserved(
'COMMIT' ) );
  7  end;
  8  /
SELECT Y
OK     N
BEGIN  Y
X      N
COMMIT N

PL/SQL procedure successfully completed.

In Oracle8i, release 8.1, we can make the above function
callable in SQL (in 8.0 and before we cannot).  In Oracle8i,
release 8.1 we would add the "pragma autonomous_transaction to
the plsql routine as such:

ops$tkyte@8i> create or replace function is_reserved( p_word in
varchar2 ) return varchar2
  2  as
  3          pragma autonomous_transaction;
 ...
 21  /

Function created.

And then "is_reserved" will work like a builtin function --
callable from SQL:

ops$tkyte@8i> select is_reserved('select') is_res from dual;

IS_RES
---------------
Y

ops$tkyte@8i> select is_reserved('ok') is_res from dual;

IS_RES
---------------
N

Review &
      Followup

      Rating:
      4
Reader  September 16, 2002
Reviewer:
      A reader
Tom,

I used "when" as a column in create table.
When I select the column from SQL>, it works fine
When I select from the PL/SQL, it errors out
Do I have to re-create the table, renaming "when" or a
work around, to use it in PL/SQL

create table t ( when date );
SQL>select when from t;       //This works

declare l_t date;
begin
select when into l_t from t where rownum = 1;
end;
/

Thia PL/SQL errors

Thnks

May 15, 2000 Ajay -- Thanks for the question regarding "RE:
      Ask Tom Submission, How often to backup", version

      You Asked
How often the data and index tablespaces be backed up
in 24x7, highly critical, and very large DB; where there is not
enough space on the disks to retain more than one copy of the
hot
backed up data files.

      and we said...
I am assuming that the database is running in archive log mode
(if not, make it so -- not running in archive log mode is a
recipe for disaster if you cannot afford to lose data).

The real question here is "how long can YOU afford to take to
recover a datafile".  In order to use your backup, you will have
to copy at least one datafile back into place and then apply
archived and online redo log files to this file.  If you wait 1
month between backups, you may have to apply 1 months of
archived redo logs to catch this file up -- can you afford that
much time?

Also, if this is mission critical data -- you need to copy your
backups to some other storage (another physical machine, a tape
drive, somewhere else).  Backing up your datafiles to the same
machine is asking for trouble.  If the entire machine becomes
unavailable for some reason -- your backups may be unaccessible
for some time.  If they are on tape -- they are immediately
available.

Here is what I do on my system.  I perform hot backups.  I put a
tablespace into backup mode.  I copy and compress the
datafile(s) associated with that tablespace to the same machine.
 I take that tablespace out of backup mode.  I then copy that
compressed datafile to another system and after testing the
integrity of the compressed file -- I remove the older
compressed backup (actually I keep 2 backups arounds, i'm
erasing the oldest backup).  We keep many copies of our archive
log files around as well (2 on disk, 1 one on tape).  At any
point in time we have about 3 copies of archived redo logs, 3
copies of the datafiles at different points in time (one online,
one newly backed up, one older then that).  The 2 copies of the
datafiles are compressed and online on another machine -- this
other machine is backed up regularly to tape as well (so we have
copies of the copies).  We do hot backups every mon/wed/fri.  We
perform biweekly exports as well.

It sounds like a lot but datafiles compress very well as do redo
log files.  Disk is relatively cheap and for these purposes --
you can use really cheap ones.  They don't have to perform very
well -- they are just backups.  At the very least -- use tape.

May 15, 2000 Steve -- Thanks for the question regarding "array
      processing", version

      You Asked
Does Oracle8i allow bulk inserts?
In Microsoft SQL Server 7 you have
a group of API for binding your
variable to columns. Then you can
send many rows of data and call insert
once. For example I can send 100 rows
and then call bcp-done to commit the
data. Is there anything simillar in
Oracle8i.

Thanks.

      and we said...
Absolutely.  In Oracle this is called array processing.  We can
do array FETCHES as well as INSERTS/UPDATES and DELETES.

How this is done varies by the language being used.  In Pro*C
for for example, you simply code using ARRAYS and then tell us
how many elements are in the array.  It might look like this:

void process(void)
{
int    some_number_data[50];
char   some_char_data[50][25];
int    number_to_insert;
int    i;

    for( i = 0; i < 35; i++ )
    {
       some_number_data[i] = i;
       sprintf( some_char_data[i], "data = %d", i );
    }
    number_to_insert = 35;

    EXEC SQL FOR :number_to_insert
       INSERT INTO T ( x, y ) VALUES ( :some_number_data,
:some_char_data );
}

In a stored procedure, it might look like:

declare
    type numTab is table of number(4) index by binary_integer;
    data numTab;
begin
    for j in 1 .. 50 loop
        data(j) := j;
    end loop;

    forall i in 1 .. 50
        insert into insert_into_table values( data(i) );
    commit;
end;
/

There are API calls to do this in OCI as well.  In fact, using
OCI we can use API calls to do what is known as a direct path
load.  In this load method data is written directly from your
application to the data files bypassing the SQL engine all
together (there are certain restrictions on this method, for
example your application must be running on the same machine as
the server -- it needs to get right at the files).

May 16, 2000 -- Thanks for the question regarding "ORACLE WEB
      SERVER", version 2.1

      You Asked
I HAVE IIS INSTALLED IN MY SYSTEM. CAN I INSTALL ORACLE WEB SERVER ALSO IN THE
SAME SYSTEM?

      and we said...
Yes you may.  In fact, you can use IIS as the "web listener" and just use the
Web Request Broker component of OAS if you wish.

If you use the included web listener, you will not be able to have it running on
any of the "ports" IIS is (eg: you probably have IIS running on the default port
80, you'll need to pick a different, non-default port for OAS).

May 17, 2000 Alla -- Thanks for the question regarding
      "Executing AFTER row trigger on failed insert", version 8.1.6

      You Asked
I always believed that AFTER triggers are being executed after
integrity constraints are checked. For example, if I am
inserting
a row and FK is violated (parent key is not found), then the
statement will fail and "after row" trigger won't be fired.

I just upgraded to 8.1.6. and my application started behaving
weird - the after row triggers are being fired even if the
statement fails (Constraints are immediate and not deferred and
I do get ORA-02291)

Is it something new in 8.1.6? How do I deal with it? How do I
stop these triggers from firing.

You can say, so what if they are firing, the transcation will
be rolled back anyway. This is true, but as a part of the
trigger
I am calling an external procedure to do someting and it's
definitely not reversable, even if the statement rolls back.

Please, help. It's a very urgent problem for me

Thank you very much for giving this your attention.

      and we said...
It doesn't have to work like this (the way you describe above)
--the EARLIEST a referential constraint might be able to be
verified would be right after the "before for each row" and
before the "after for each row" but there are many times when it
cannot be verfied at that time.

The documentation actually says:

<quote concepts manual, v7.3, section in "the mechanisms of
constraint checking">

• A multiple row INSERT statement, such as an INSERT statement
with nested SELECT statement, can insert rows that reference
one another. For example, the first row might have EMPNO as
200 and MGR as 300, while the second row might have EMPNO
as 300 and MGR as 200.

Each case reveals something about how and when Oracle performs
constraint checking.

The first case is easy to understand; a null is given for the
foreign key value. Because nulls are allowed in foreign keys,
this row is inserted successfully into the table.

The second case is more interesting. This case reveals when
Oracle effectively performs its constraint checking: after the
statement has been completely executed. To allow a row to be
entered with the same values in the parent key and the foreign
key, Oracle must first execute the statement (that is, insert
the new row) and then check to see if any row in the table has
an EMPNO that corresponds to the new row’s
MGR.
</quote>

the relevant part of this is:

This case reveals when Oracle effectively performs its
constraint checking: after the statement has been completely
executed.

I agree that in earlier releases, it would *sometimes* not fire
the after, for each row trigger but that was never gauranteed or
promised (quite the contrary actually).  Here is an example
showing it could fire the AFTER for each row trigger before
checking constraints in earlier releases:

tkyte@ORA734.WORLD> create table c ( a int primary key,
                    x references c(a) );

Table created.

tkyte@ORA734.WORLD> create or replace trigger c_bi
                    before insert on c
  2  begin
  3          dbms_output.put_line( 'Before insert' );
  4  end;
  5  /
Trigger created.

tkyte@ORA734.WORLD> create or replace trigger c_bifer
                   before insert on c for each row
  2  begin
  3          dbms_output.put_line( 'Before insert FER '
             || :new.a   || ' ' || :new.x );
  4  end;
  5  /
Trigger created.

tkyte@ORA734.WORLD> create or replace trigger c_aifer
                    after insert on c for each row
  2  begin
  3          dbms_output.put_line( 'Before after FER ' ||
                     :new.a || ' ' || :new.x );
  4  end;
  5  /
Trigger created.

tkyte@ORA734.WORLD> create or replace trigger c_ai
                    after insert on c
  2  begin
  3          dbms_output.put_line( 'After insert ' );
  4  end;
  5  /
Trigger created.

tkyte@ORA734.WORLD> set serveroutput on
tkyte@ORA734.WORLD> insert into c
  2  select 1, 2 from dual
  3  union all
  4  select 2, 3 from dual
  5  /
Before insert
Before insert FER 1 2
Before after FER 1 2
Before insert FER 2 3
Before after FER 2 3
insert into c
*
ERROR at line 1:
ORA-02291: integrity constraint (TKYTE.SYS_C00382) violated -
parent key not found

See - it fired the AFTER FOR EACH ROW trigger 2 times before
checking the consraint -- and that was release 7.3.

Back to the root problem -- your extproc.  That is not
transactional (the maintaining of the external data source).
You should be aware that just because something makes it past
the AFTER FOR EACH ROW trigger does not mean it'll be in the
table!!!!  Regardless of trigger firing order/RI or anything.

What about:

insert into T select * from really_big_table;

and you run out of space in the middle?  or the server crashes?
or the end user rolls back?  half of the rows will make it out,
half will not.  the half that made it out will get rolled back
and won't exist -- you have a mess.

Here is what I would do in your case.

1) my after, for each row trigger would queue a job in dbms_job
to be executed right after I commit and the changes are
permanent.

2) this job it queues would simply be a call to the procedure
its calling in real time right now.

3) set up the job queues to check for jobs to run every 15
seconds or so.

that way -- its transactional -- if I commit - the extproc gets
called. If I get rolled back (for WHATEVER reason and there are
dozens that could affect you -- regardless of RI or not), then
the jobs themselves will get removed from the queue.  The rows
will be propagated in the background --probably providing a
better experience for the end user.

how does that sound?  I use dbms_job for lots of stuff to make
it transactional (like sending emails and such).  I queue the
request to perform the operation -- I do not perform the
operation I cannot rollback.  Very safe, very efficient, much
more robust.

May 18, 2000 Anthony -- Thanks for the question regarding "How
      to increase data block size properly ?", version 8.1.5

      You Asked
Hi ,
    I try to increase data block size in oracle version 8.1.5.
But when I finished modify the parameter of data block size in
init.ora and restart the database , an error occured "mismatch
block size in control file ".
    Could you tell me how to modify the block size properly ?
And how to do it ?

      and we said...
You cannot modify the data block size after a database is
created.  You can only create a new database with the correct
block size, export the old database and do a full import into
the new database.

Changing the block size would require the entire database to be
rewritten block by block -- each index would have to be rebuilt
as well (since the rowids they contain would be invalid).  Given
that -- the only way to do a block size change is a total
rebuild from scratch.
May 18, 2000
      Steve -- Thanks for the question regarding
      "Generic Search Window", version 8i

      You Asked
I'm trying to setup a generic Search window so I can search on
 a generic field in any file I pass as a variable but I don't
 know if it is possible.  Can I somehow set up a cursor and
 pass it variables for the filename and fieldname to search on?
 For example can I do something like this?

procedure search_window(c_filename varchar2,
                        c_fieldname varchar2,
                        c_search varchar2)  as

 cursor c_answer_cur is
   select c_fieldname from c_filename
           where c_filename = c_search;

 begin

  htp.htmlopen;
  htp.headopen;

    for answer_rec in c_answer_cur loop
       htp.print(answer_rec.c_fieldname);
    end loop;

  htp.bodyclose;
  htp.htmlclose;

 end search_window;

I realize the syntax is probably not quit right but you get
 the idea.  Is this possible?

      and we said...
The easiest way to do this for you will be to use some of the
OAS toolkit functions.  For example:

ask_tom@OSI1.WORLD> declare
  2      p_tname  varchar2(30) default 'dual';
  3      p_fieldname varchar2(30) default 'dummy';
  4      p_searchstr varchar2(30) default 'X';
  5  begin
  6    owa_util.cellsprint(
  7      owa_util.bind_variables( 'select ' || p_fieldname ||
  8                                 ' from ' || p_tname ||
  9                                 ' where ' || p_fieldname
                                                    || ' = :x',
 10                               ':x', p_searchstr )
 11                       );
 12  end;
 13  /

PL/SQL procedure successfully completed.

ask_tom@OSI1.WORLD> set serveroutput on
ask_tom@OSI1.WORLD> exec owa_util.showpage
<TR>
<TD>X</TD>
</TR>

PL/SQL procedure successfully completed.

cellsprint prints out the data in an HTML table for you.  You
would need to call htp.tableOpen/tableClose and set up the
column headings yourself but the table is done for you.

Another method, with more control perhaps, would be to use a ref
cursor.  That would look like:

ask_tom@OSI1.WORLD> declare
  2      p_tname  varchar2(30) default 'dual';
  3      p_fieldname varchar2(30) default 'dummy';
  4      p_searchstr varchar2(30) default 'X';
  5
  6      type rc is ref cursor;
  7      p_cursor rc;
  8      l_value    varchar2(255);
  9  begin
 10      open p_cursor for 'select ' || p_fieldname ||
 11                         ' from ' || p_tname ||
 12                        ' where ' || p_fieldname || ' = :x'
 13           using p_searchstr;
 14
 15      loop
 16          fetch p_cursor into l_value;
 17          exit when p_cursor%notfound;
 18
 19          dbms_output.put_line( '*** ' || l_value );
 20      end loop;
 21      close P_cursor;
 22  end;
 23  /
*** X

PL/SQL procedure successfully completed.

May 18, 2000 saalik -- Thanks for the question regarding "sql
      unload utility", version 8.1.6

      You Asked
Hello,

In the past I have used a utility called sqlunld (sqlunload) to
unload data from a table.  After the utility is kicked off, a
csv and ctl file is created.  Is this utility a third party
software package.  Our current $ORACLE_HOME/bin does not have
the sqlunld utility.

Why would oracle supply an sqlldr utility in the bin directory
and not a utility to unload data?  Do you you somewhere on the
web where I can find the sqlunld utility?

Thanks a lot....

      and we said...
see
http://osi.oracle.com/~tkyte/flat/index.html
there I have a utility for NT (.cmd) and Unix (shell script)
that will either:

o unload all data to a delimited file
o unload all data into a single file that combines the CTL and
data together for loading.

I believe it will fully replace your sqlunld utility you have
been using.
May 18, 2000 Pertisth -- Thanks for the question regarding
      "Help Required", version 8i(Windows NT)

      You Asked
Dear TOM
I have got some question , can u answer those

(1)Some-time Oracle database Hangs up and when I check the event
viewer on windows NT, It gives me message that ' oracle instance
terminated'. But when I re-start the server everythingh works.
Why this is happening and what sholud i do to avoid this.

(2) Can i make 300-400 mb datafile. Will it improve the
performance

 If u can help me on above issues i would be thankfull to u.

Pertisth Mankotia

      and we said...
For (1) you should review your ALERT log for your database.  If
the instance is "terminated", it will have logged an error to
the alert log on the server and as part of this error -- it will
have included the full path to a file that contains more
information.  This trace file can be used by support to diagnose
the cause of the crash and then to supply a fix/patch for it.

For (2) -- yes, you can easily make a 300-400 mb datafile.  In
fact you can create a datafile of many gigabytes on NT.  I
myself never like to go over 2gig but you can.  As to whether it
will increase performance -- I doubt it will have any material
effect on performance whatsoever.  The size of the datafile is
not very relevant to the performance (unless of course you were
to user tiny datafiles of a couple of kilobytes apiece).

May 18, 2000 Daniel -- Thanks for the question regarding
      "Web-to-go Configuration with OAS", version 4.0.8.1

      You Asked
I need help to configure Web-to-go Server with OAS. I have
configured applications and cartridge and will invoque URL and
obtain a message : Web-to-go server not running.
I need a documentation or others docs for this product.

Thanks

      and we said...
That may be found at

http://technet.oracle.com/doc/lite/wtg/wtgindex.html

you need an account on technet but they are free and you can
sign up right away.
May 19, 2000
      aremanda -- Thanks for the question
      regarding "problem regarding trigger related to long column", version
      version7.3.4

      You Asked
I am facing problem with migrating data from one table to
another table which contains long datatype.The trigger is
working well with respect to other fields but only in case of
long column it is behaving differently like it is not inserting
any images related to that column and at the same type it is not
showing any error message.The structure of the source and target
are same.The following is the structure and trigger.
SQL> desc images
 Name                            Null?    Type
 ------------------------------- -------- ----
 IMAGE_ID                        NOT NULL NUMBER
 IMAGE_FILEPATH                  NOT NULL NUMBER
 IMAGE_FILENAME                  NOT NULL VARCHAR2(12)
 IMAGE_FILETYPE                  NOT NULL VARCHAR2(10)
 IMAGE_DATA                               LONG RAW
Trigger
-------
CREATE OR REPLACE TRIGGER images_testing
  after INSERT OR UPDATE
  ON IMAGES
  FOR each ROW
BEGIN
INSERT INTO TEST_IMAGES
    (image_id,
     image_filepath,
     image_filename,
     image_filetype,
     image_data)
  VALUES
    (:NEW.image_id,
     :NEW.image_filepath,
     :NEW.image_filename,
     :NEW.image_filetype,
     :NEW.image_data);
END;

Pls try to sort out this problem.
Thanks
Sudha

      and we said...
from the application developers guide:

http://technet.oracle.com/doc/server73x/ADG73/ch9.htm#toc093
<quote>

LONG and LONG RAW Datatypes

LONG and LONG RAW datatypes in triggers are subject to the
following restrictions:

o A SQL statement within a trigger can insert data into a column
of LONG or LONG RAW datatype.

o If data from a LONG or LONG RAW column can be converted to a
constrained datatype (such as CHAR and VARCHAR2), a LONG or LONG
RAW column can be referenced in a SQL statement within a
trigger. Note that the maximum length for these datatypes is
32000 bytes.

o Variables cannot be declared using the LONG or LONG RAW
datatypes.

o :NEW and :OLD cannot be used with LONG or LONG RAW columns.
</quote>

So, you cannot use your approach to copy a LONG RAW from one
table to another.  In fact, if the LONG RAW exceeds 32k, you
simply will not be able to do this via a trigger at all.

What you can do, if the LONG RAW is less then 32k, is to use an
AFTER trigger (not for each row) to process the copy.  A FOR
EACH ROW trigger would be used to capture the primary keys of
the newly inserted rows and the AFTER trigger would read the
long raw out into a temporary variable (upto 32k) and insert it
into the other table.  See

http://osi.oracle.com/~tkyte/Mutate/index.html
for the details.  Your particular implementation, if the long
raws are 32k or less, would look like this:

tkyte@ORA734.WORLD> create table images
  2  ( image_id int PRIMARY KEY,
  3    image_filepath int,
  4    image_filename varchar2(12),
  5    image_filetype varchar2(10),
  6    image_data long raw
  7  );

Table created.

tkyte@ORA734.WORLD> create table test_images
  2  ( image_id int,
  3    image_filepath int,
  4    image_filename varchar2(12),
  5    image_filetype varchar2(10),
  6    image_data long raw
  7  );

Table created.

tkyte@ORA734.WORLD>
tkyte@ORA734.WORLD>
tkyte@ORA734.WORLD>
tkyte@ORA734.WORLD> create or replace package state_pkg
  2  as
  3      type numArray is table of number
  4            index by binary_integer;
  5
  5      modified  numArray;
  6      empty     numArray;
  7  end;
  8  /

Package created.

tkyte@ORA734.WORLD>
tkyte@ORA734.WORLD> create or replace trigger images_BIU
  2  before insert or update on images
  3  begin
  4      state_pkg.modified := state_pkg.empty;
  5  end;
  6  /

Trigger created.

tkyte@ORA734.WORLD>
tkyte@ORA734.WORLD> create or replace trigger images_AIUfer
  2  after insert or update on images
  3  for each row
  4  begin
  5      state_pkg.modified(state_pkg.modified.count+1) :=
  6                     :new.image_id;
  7  end;
  8  /

Trigger created.

tkyte@ORA734.WORLD>
tkyte@ORA734.WORLD> create or replace trigger images_AIU
  2  after insert or update on images
  3  begin
  4      for i in 1 .. state_pkg.modified.count
  5      loop
  6          for x in ( select *
  7                       from images
  8                      where image_id =
  9                              state_pkg.modified(i) )
 10          loop
 11              insert into test_images
 12              ( image_id, image_filepath,
 13                image_filename,
 14                image_filetype, image_data )
 15              values
 16              ( x.image_id, x.image_filepath,
 17                x.image_filename,
 18                x.image_filetype, x.image_data );
 19          end loop;
 20      end loop;
 21      state_pkg.modified := state_pkg.empty;
 22  exception
 23      when others then
 24          state_pkg.modified := state_pkg.empty;
 25          raise;
 26  end;
 27  /

Trigger created.

Now, to test this out, we will insert a 10k raw and see if it
gets copied correctly:

tkyte@ORA734.WORLD> insert into images values
  2  ( 1, 1, 'x', 'y', hextoraw( rpad( 'A', 20000, 'A') ) );

1 row created.

tkyte@ORA734.WORLD>
tkyte@ORA734.WORLD> set serveroutput on
tkyte@ORA734.WORLD> declare
  2      x    images%rowtype;
  3      y    images%rowtype;
  4  begin
  5
  5      select * into x from images;
  6      select * into y from test_images;
  7
  7      dbms_output.put_line( 'length(x) = ' ||
  8                             length( x.image_data ) );
  9      dbms_output.put_line( 'length(y) = ' ||
 10                             length( y.image_data ) );
 11
 11      if ( x.image_data = y.image_data ) then
 12          dbms_output.put_line( 'Are equal' );
 13      else
 14          dbms_output.put_line( 'Are NOT equal' );
 15      end if;
 16  end;
 17  /
length(x) = 2000
length(y) = 2000
Are equal

PL/SQL procedure successfully completed.

sure enough -- this works.  Again, this will only work upto
32k at which point it will no longer work as the largest PLSQL
variable is 32k in size.  At that point, given that you are
using Oracle7.3.4, your choices are very limited -- PLSQL is out
of the question.  The best answer at that point is really to use
Oracle8 and use the BLOB datatype which does not have this
restriction -- the entire blob can be manipulated using plsql or
any language for that matter.

May 19, 2000 V Siva -- Thanks for the question regarding
      "estimate Initial Extent size of a table", version 8.0.4

      You Asked
Hi,

I've a general question: how to determinr the size of the
initial extent for a table.

I've to create a table having some 200 columns, and approx.
record size is 2K. This table initially will have very large
number of rows around 100,000 and later the growth rate is very
less. In this case what will be the initial extent and next
extent sizes?

Thanks
Siva

      and we said...
I myself prefer to use uniformly sized extents for all objects.
That is -- I do not size discrete objects "perfectly", I do not
spend time trying to figure out the initial extent should be
137.2 megabytes and the next should be 13meg with a pctincrease
of 50%.  Rather, I lump objects into classes of sizes.  Small
objects (lookup tables and such) go into a tablespace where all
objects use 64k extents.  Slightly larger objects might go into
a tablespace that uses 256 or 512k extents.  Medium sized
objects go into a tablespace with 1meg extents.  Truely large
objects go into appropriately sized tablespaces.

The goal here is to keep all extent sizes homogenous within a
tablespace -- in tablespace T1 all extents are Xmeg,
regardless of the object.  In tablespace T2, all extents are
Ymeg, regardless of the object.  The removes any possibility of
fragmentation (it just cannot happen if all extents are the same
size -- its impossible to have fragmentation).  You never have
to worry about coalescing free space or anything like that.

There is a myth that some people believe in -- it is the myth
that you should attempt to size objects such that all data fits
in the initial extent and that having more then a handful of
extents is bad.  This is quite simply not true.  It is
perfectly OK to have dozens or even low hundreds of extents for
objects.  Going overboard into the thousands, while possible,
isn't recommended.  With locally managed tablespaces in Oracle8i
release 8.1, they (tables with more then hundreds of extents)
are more feasible.

So, if I have a table with about a 2k record size and 100k
records initially we are talking about a 200meg table that grows
slowly over time.  I would need a better definition of slowly
but lets say you add 5meg of data per month (2,500 records per
month @2k per record).  Every year thats about 60meg of data.  I
might consider a 50meg extent size for this object.  Initially
it would consume 4 or 5 extents and add about 1 extent per year.

Review &
      Followup

      Rating:
      5
  July 25, 2001
Reviewer:  Tianhua
       from USA

      Rating:
      4
  November 04, 2001
Reviewer:  Mahendra
      Jadav  from INDIA

May 19, 2000 Dinesh -- Thanks for the question regarding
      "Deletion of duplicate rows from all tables in a database..", version 8.0

      You Asked
Hi Tom ,

   I know the query which is used to delete the duplicate rows
with in a table . but my question is that possible to delete all
the existing duplicate rows from all table with in the database.

for ex

if table t contains two duplicate value..

10 dinesh
10 dinesh
20 ran
20 ran

and another table let t1 contains some other duplicate rows like
.

11
11
22
22

is that possible to delete all the duplicate rows in all the
tables with in a database in a single query .

hope u will send me the reply ..
Dinesh

      and we said...
The short answer is yes.

The long answer is while you can do this, performance would not
be so good and you would have to write a bit of code in the
server to enable this.

A delete statement can only work on 1 table or view at a time
(as far as processing a delete action -- the delete may
reference many tables but only 1 table or view will be deleted
from).

So, we cannot do this against the tables -- we can do this
against a view on the tables.  We will have to supply some logic
to do it. An example is below.  It should be noted that the
performance of this implementation is questionable.  It would
definitely be more efficient to execute the individual deletes.
I do not recommend this approach.

ask_tom@OSI1.WORLD> create table t1 ( id int, string
varchar2(25) );

Table created.

ask_tom@OSI1.WORLD> create table t2 ( id int );
Table created.

ask_tom@OSI1.WORLD> insert into t1 values ( 10, 'dinesh' );
ask_tom@OSI1.WORLD> insert into t1 values ( 10, 'dinesh' );
ask_tom@OSI1.WORLD> insert into t1 values ( 20, 'ran' );
ask_tom@OSI1.WORLD> insert into t1 values ( 20, 'ran' );
ask_tom@OSI1.WORLD> insert into t1 values ( 21, 'xxx' );
ask_tom@OSI1.WORLD> insert into t2 values ( 11 );
ask_tom@OSI1.WORLD> insert into t2 values ( 11 );
ask_tom@OSI1.WORLD> insert into t2 values ( 22 );
ask_tom@OSI1.WORLD> insert into t2 values ( 22 );
ask_tom@OSI1.WORLD> insert into t2 values ( 23 );

ask_tom@OSI1.WORLD> create or replace view t1_t2
  2  as
  3  select id, string, 'T1' tname from t1
  4  union all
  5  select id, null,   'T2' tname from t2
  6  /

View created.

ask_tom@OSI1.WORLD> delete from t1_t2
  2   where (id,nvl(string,rpad('*',26,'*')),tname)
  3          in ( select id,nvl(string,rpad('*',26,'*')),tname
  4                     from t1_t2
  5                    group by id,string,tname
  6                   having count(*) > 1 )
  7  /
delete from t1_t2
            *
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

so, that shows the view will need some help.  here is the help:

ask_tom@OSI1.WORLD> create or replace trigger t1_t2_trigger
  2  instead of delete on t1_t2
  3  begin
  4          if ( :old.tname = 'T1' ) then
  5                  delete from t1 where id = :old.id;
  6          elsif ( :old.tname = 'T2' ) then
  7                  delete from t2 where id = :old.id;
  8          end if;
  9  end;
 10  /

Trigger created.

ask_tom@OSI1.WORLD> delete from t1_t2
  2   where (id,nvl(string,rpad('*',26,'*')),tname)
  3          in ( select id,nvl(string,rpad('*',26,'*')),tname
  4                     from t1_t2
  5                    group by id,string,tname
  6                   having count(*) > 1 )
  7  /

8 rows deleted.

ask_tom@OSI1.WORLD> select * from t1;

        ID STRING
---------- -------------------------
        21 xxx

ask_tom@OSI1.WORLD> select * from t2;

        ID
----------
        23

ask_tom@OSI1.WORLD>

May 19, 2000 Margaret -- Thanks for the question regarding
      "Frame Drivers", version 2.1.0.9.3

      You Asked
Is there a place that can explain using frame drivers in Webdb
better
than the documentation or the Webdb Bible? I would like to
create
a form where they pick which place they want a reservation for
in the top and the bottom portion would be the actual
reservation
form. I feel a bit confused and was told to use a frame driver
Thanks!

      and we said...
The documentation you are looking for can be found at:

http://technet.oracle.com/docs/products/webdb/doc_index.htm
Specifically, the document entitled "Creating and Managing
Components - Field-Level Help".

Based on your description above, a WebDB frame driver is just
what you need to use.  Basically a frame driver allows the
developer to in frame 'A' display the list of values to
inputs into frame 'B'.  Frame B can can a webdb report, chart,
form.  Any object that will take in the input from frame A.  So
it can be use, and was designed for, exactly what you are
looking for.

May 19, 2000 E.J. -- Thanks for the question regarding "Why
      doesn't Oracle support joins in updates, are there plans to in the
      future?", version 7.3.4.2

      You Asked
I realize this isn't a technical question but I've always found
it very annoying that Oracle doesn't support joins on updates.
I know what facilities Oracle has in place that work in a
similar manner but they are no-where near as easy to work with.

For instance, the following query is good (and easy to write) in
Sybase, SQL Server, Access (For goodness sake, if access has
it..) and others:

update tablea set cola = b.cola * c.colc
from tablea, tablea a2, tableb b, tablec c
where tablea.name = a2.name and tablea.rowid <> a2.rowid and
  b.cold = tablea.cold and c.cold = tablea.cold;

Now the same sql in Oracle:

update tablea a1 set a1.cola = (select b.colb * c.colc
  from tablea a2, tableb b, tablec c where a2.name = a1.name and
  a2.id <> a1.id and b.cold = a1.cold and c.cold = a1.cold)
where
  -- So we don't have to update every column:
  a1.id not in (select a2.id from tablea a2, tableb b, tablec c
  where a2.name = a1.name and b.cold = a1.cold and
  c.cold = a1.cold)

Obviously the first format is much easier to read and
understand.  What are Oracle's plans for this and why haven't
they implemented this already?  EVERY developer I've talked to
wants this quite badly.

If you're not the right person to ask about something like this
please let me know.

Thanks,
E.J. Wilburn

      and we said...
But we do support updates on joins.

Consider this example:

tkyte@ORA734.WORLD> create table t1
  2  ( x int, t1_data int );

Table created.

tkyte@ORA734.WORLD>
tkyte@ORA734.WORLD> create table t2
  2  ( x int primary key, t2_data int );

Table created.

tkyte@ORA734.WORLD> insert into t1 values ( 1, 1 );
tkyte@ORA734.WORLD> insert into t1 values ( 2, 2 );

tkyte@ORA734.WORLD> insert into t2 values ( 1, 100 );

tkyte@ORA734.WORLD> select * from t1;

         X    T1_DATA
---------- ----------
         1          1
         2          2

tkyte@ORA734.WORLD> update ( select t1_data, t2_data
  2             from t1, t2
  3            where t1.x = t2.x )
  4     set t1_data = t2_data
  5  /

1 row updated.

tkyte@ORA734.WORLD> select * from t1;

         X    T1_DATA
---------- ----------
         1        100
         2          2

Here I am using the data in T2 to update T1 with.  The primary
key above is in bold because it is important.  We impose a rule
on you that the table holding the data that you will update FROM
must be joined to by a primary key or unique constraint set of
columns.

The reason behind this is that we must ensure that each row in
T1 is joined to at most 1 row in T2.  Consider what would
happen if T2(x) was not unique and we had rows:

X         T2_DATA
-------   ----------
1         100
1         101

After I ran the update above (if we could) what value would you
expect in T1_DATA?  We set T1_DATA to be whatever was in T2_DATA
but the value of T2_DATA when X=1 is ambigous.  I could run this
update one time and end up with a value of 100 and run the same
exact update with the same exact data and then end up with 101.
Each answer is 'valid' -- but the results are not determinate.
So, we have the primary key/unqiue constraint requirement.

So, it can be done...

May 19, 2000 E.J. -- Thanks for the question regarding
      "Ordering by max of multiple columns with preferences", version 7.3.4.2

      You Asked
Basically I have the following data:

ID      Val1   Val2  Val3
1         1     6     9
2         3     4     8
3         9     3     2
4         4     9     1

I want to order by the highest value giving preference in this
order when there are equal values:

 Val1
 Val2
 Val3

So the data at the top should be ordered like:

ID      Val1  Val2  Val3
3         9     3     2
4         4     9     1
1         1     6     9
2         3     4     8

Thanks.

      and we said...
Sounds like you want to order by the greatest of val1, val2,
val3 and then by those columns.  It would be then:

ask_tom@OSI1.WORLD> create table t ( id int,
                              val1 int, val2 int, val3 int );
Table created.

ask_tom@OSI1.WORLD> insert into t values (1,1,6,9);
ask_tom@OSI1.WORLD> insert into t values (2,3,4,8);
ask_tom@OSI1.WORLD> insert into t values (3,9,3,2);
ask_tom@OSI1.WORLD> insert into t values (4,4,9,1);
ask_tom@OSI1.WORLD> select *
                      from t
                     order by greatest( val1,val2,val3) desc,
                             val1 desc, val2 desc, val3 desc
  2  /

        ID       VAL1       VAL2       VAL3
---------- ---------- ---------- ----------
         3          9          3          2
         4          4          9          1
         1          1          6          9
         2          3          4          8

May 19, 2000 Patrick -- Thanks for the question regarding
      "Mutating Tables (cont'd)", version Oracle 8.1.?

      You Asked
Hi Tom,

Two tables, one a hierarchy of categories, the other one mapping
products and categories:

CAT_INDEXES
-----------------------------------
CAT_ID      CAT_NAME      PARENT_ID

and

CAT_INDEXES_INT
-----------------------------------
PROD_ID      CAT_ID

For every insert in CAT_INDEXES_ID, I want my trigger to grab
the CAT_ID, look up its PARENT_ID in CAT_INDEXES, insert a new
row in CAT_INDEXES_INT with the PROD_ID and the parent's CAT_ID,
and recurse (ie keep inserting rows) until there's no PARENT_ID
(ie we're at the top of the categories tree).

I'm hitting a wall with the mutating table error message.

Thanks for any insights!!...

-Patrick-

      and we said...
Thats harder then your average mutating table as you need to not
only avoid the mutating table but avoid recursively processing
your own inserts done from within the trigger.  We can do this
and it might look like the following example.

The trick here is to maintain a boolean that will tell us when
we are in the trigger already.  If we are -- and the trigger
fires again -- that must be us recursively firing it.  We'll
ignore it then, we don't need to recursively fire at that time.
Other then that -- its a standard "mutating trigger" avoidance.
See

http://osi.oracle.com/~tkyte/Mutate/index.html
for the details on how to avoid them and why they happen...

ops$tkyte@8i> create table cat_indexes
  2  ( cat_id     int,
  3    cat_name   varchar2(25),
  4    parent_id  int references cat_indexes(cat_id),
  5    constraint cat_indexes_pk
  6               primary key(cat_id)
  7  );

Table created.

ops$tkyte@8i>
ops$tkyte@8i> create table cat_indexes_int
  2  ( prod_id     int,
  3    cat_id      int references cat_indexes(cat_id),
  4    constraint  cat_indexes_int_pk
  5                primary key ( prod_id, cat_id )
  6  );

Table created.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> create or replace package state_pkg
  2  as
  3      type numArray is table of number
  4                   index by binary_integer;
  5
  6      newCat_ids  numArray;
  7      newprod_ids numArray;
  8      empty       numArray;
  9
 10      intrigger boolean default FALSE;
 11  end;
 12  /

Package created.

ops$tkyte@8i>
ops$tkyte@8i> create or replace trigger cat_indexes_int_bi
  2  before insert on cat_indexes_int
  3  begin
  4      if ( not state_pkg.inTrigger )
  5      then
  6          state_pkg.newCat_ids  := state_pkg.empty;
  7          state_pkg.newProd_ids := state_pkg.empty;
  8      end if;
  9  end;
 10  /

Trigger created.

ops$tkyte@8i>
ops$tkyte@8i> create or replace trigger cat_indexes_int_aifer
  2  after insert on cat_indexes_int
  3  for each row
  4  declare
  5      l_cnt number;
  6  begin
  7      if ( not state_pkg.inTrigger )
  8      then
  9          l_cnt := state_pkg.newCat_ids.count+1;
 10          state_pkg.newCat_ids(l_cnt) := :new.cat_id;
 11          state_pkg.newProd_ids(l_cnt) := :new.prod_id;
 12      end if;
 13  end;
 14  /

Trigger created.

ops$tkyte@8i>
ops$tkyte@8i> create or replace trigger cat_indexes_int_ai
  2  after insert on cat_indexes_int
  3  begin
  4      if ( not state_pkg.inTrigger )
  5      then
  6          begin
  7              state_pkg.inTrigger := TRUE;
  8
  9              for i in 1 .. state_pkg.newCat_ids.count loop
 10                  insert into cat_indexes_int(prod_id,cat_id)
 11                  select state_pkg.newProd_ids(i), cat_id
 12                    from cat_indexes
 13                   start with cat_id =
 14                         ( select parent_id
 15                             from cat_indexes
 16                            where cat_id =
 17                                   state_pkg.newCat_ids(i) )
 18                 connect by prior parent_id = cat_id;
 19              end loop;
 20
 21              state_pkg.inTrigger := FALSE;
 22          exception
 23              when others then
 24                  state_pkg.inTrigger := FALSE;
 25                  RAISE;
 26          end;
 27      end if;
 28  end;
 29  /

Trigger created.

ops$tkyte@8i>
ops$tkyte@8i> insert into cat_indexes ( cat_id, parent_id )
  2  values ( 1, null );

1 row created.

ops$tkyte@8i>
ops$tkyte@8i> begin
  2      for i in 2 .. 10 loop
  3          insert into cat_indexes (cat_id, parent_id)
  4                           values ( i, i-1 );
  5      end loop;
  6  end;
  7  /

PL/SQL procedure successfully completed.

ops$tkyte@8i>
ops$tkyte@8i> insert into cat_indexes_int ( prod_id, cat_id )
  2  values ( 55, 5 );

1 row created.

ops$tkyte@8i>
ops$tkyte@8i> insert into cat_indexes_int ( prod_id, cat_id )
  2  values ( 56, 3 );

1 row created.

ops$tkyte@8i>
ops$tkyte@8i> insert into cat_indexes_int ( prod_id, cat_id )
  2  values ( 57, 10 );

1 row created.

ops$tkyte@8i>
ops$tkyte@8i> break on prod_id skip 1
ops$tkyte@8i> select *
  2    from cat_indexes_int
  3   order by prod_id, cat_id;

   PROD_ID     CAT_ID
---------- ----------
        55          1
                    2
                    3
                    4
                    5

        56          1
                    2
                    3

        57          1
                    2
                    3
                    4
                    5
                    6
                    7
                    8
                    9
                   10

18 rows selected.


Subject | Article | Last Updated (East coast time)
Comments on Tables | article only | May 21, 2000 09:18 am
Oracle Parallel Server's Vs. Replication Server's | article only | May 21, 2000 10:12 am
BFILE | article only | May 21, 2000 02:16 pm
Client install | article only | May 22, 2000 07:55 am
Index Utilisation | article only | May 22, 2000 10:18 am
Problem with your recommendation for "Export to a file named after the date" | article only | May 22, 2000 12:23 pm
JDBC and DECODE | article only | May 22, 2000 04:42 pm
How to move my pro*c to point to another oracle instance | article only | May 23, 2000 04:02 pm
Analyzing catalog tables ? | article only | May 23, 2000 04:20 pm
Functional Indexes on Date Attributes | article only | May 23, 2000 04:27 pm
sql unload utility | article only | May 24, 2000 07:54 am
Database Monitoring and Trend | article only | May 24, 2000 08:01 am
Functions | article only | May 25, 2000 08:33 am
Oracle Database Server Utility UTL_FILE | article only | May 25, 2000 09:27 am
JDBC Driver for Linux | article only | May 25, 2000 10:11 am
Error during starting DATABASE. | article only | May 25, 2000 03:59 pm
JDBC access for Procedures with table type as i/p parameter | article only | May 25, 2000 04:51 pm
No. of rows in tables -- explaination of NUM_ROWS in ALL_TABLES | article only | May 26, 2000 07:54 am
How to load datas into a table in which a field is a type of varray by SQL*LOADER? | article only | May 26, 2000 08:11 am
sql query for referential cursor | article only | May 26, 2000 09:00 am
unzippnig error | article only | May 26, 2000 01:23 pm
Returning the first row of an ordered resultset in Oracle 7.3.4.2 | article only | May 26, 2000 02:32 pm
row(s) 1 - 22 of 22
May 21, 2000 Omar -- Thanks for the question regarding "Comments on Tables", version 8.0.5
You Asked
Please Sir , I need to Know how can I get and the comments on
tables or columns from the data dict.

with respect
and we said...
This information is kept in the dictionary views:

o <USER|ALL|DBA>_TAB_COMMENTS for tables.
o <USER|ALL|DBA>_COL_COMMENTS for columns.

This example shows how to put a comment on a table or column and
then retrieve that information.  I'm using the USER_ views since
the owner of the table is the same as the currently logged in
user.  If the tables exist in another schema, you would use the
ALL_ views and add "where owner = THAT_SCHEMA" to the predicate
as well.  DBA's, who can see all objects, may use the DBA_
views.

ops$tkyte@8i> create table t ( x int );
Table created.

ops$tkyte@8i> comment on table t
  2  is 'This is table T';
Comment created.

ops$tkyte@8i> comment on column t.x
  2  is 'This is column X of table T';
Comment created.

ops$tkyte@8i> desc user_tab_comments
 Name                    Null?    Type
 ----------------------- -------- ----------------
 TABLE_NAME              NOT NULL VARCHAR2(30)
 TABLE_TYPE                       VARCHAR2(11)
 COMMENTS                         VARCHAR2(4000)

ops$tkyte@8i> desc user_col_comments
 Name                    Null?    Type
 ----------------------- -------- ----------------
 TABLE_NAME              NOT NULL VARCHAR2(30)
 COLUMN_NAME             NOT NULL VARCHAR2(30)
 COMMENTS                         VARCHAR2(4000)

ops$tkyte@8i> colum comments format a50 word_wrap
ops$tkyte@8i> select comments
  2    from user_tab_comments
  3   where table_name = 'T';

COMMENTS
--------------------------------------------------
This is table T

ops$tkyte@8i> select comments
  2    from user_col_comments
  3   where table_name = 'T'
  4     and column_name = 'X';

COMMENTS
--------------------------------------------------
This is column X of table T
May 21, 2000 Yogesh -- Thanks for the question regarding "Oracle Parallel Server's Vs. Replication Server's", version Oracle 8i v8.1.5
You Asked
Please let me know about the difference between the Oracle
Parallel Server Option & Oracle Replication Server.
Which one is most suited for Online Application?
If any such application is been deployed by any of your client,
please send me the e-mail and the available details about the
deployment.
and we said...
Thats somewhat like comparing apples and oranges as Oracle
Parallel Server is a feature for high availability and
scalability while Replication is a feature for
distributing/copying data across multiple databases.  They are
used for different purposes, one would need to know more about
your goals (eg: is your goal availability, maximize performance
on a wan, redundancy, etc?)

The May-June 2000 edition of Oracle magazine has an article that
contrasts Oracle Parallel Server and Replication (as well as
other techniques) in the context of availability.  You can read
this online at:
http://www.oracle.com/oramag/oracle/00-May/o30tom.html
May 21, 2000 Clara Isabel -- Thanks for the question regarding "BFILE", version OAP 4.0.7
You Asked
How  can I show a bfile (e.g. images) on the web ?

Thanks
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:232814159006
It shows how using a BLOB but using a bfile will be virtually
identical.  You'll read a chunk of the bfile and htp.prn it.
May 22, 2000 Sanjay -- Thanks for the question regarding "Client install", version Oracle 8.i
You Asked
Currently we are using oracle 7.3 and developer 2000 version 1.6
and developer 6.0

We would want to migrate to oracle 8.i. In such a case i would
have to install the SQL*NET for 8.i. On doing so my exisitng
developer do not connect to the 8.i database. DO i have to
re-install the developer 2000 at the client side again, Or can i
remove the SQL of developer 2000 and re-install the new version.
and we said...
You would not have to install Net8.1 on the client for this --
Developer 1.6 usings sqlnet 2.3 and Developer 6.0 uses Net8.0.
Either of these clients can connect to an Oracle8i instance "as
is".  The clients need not be at the same release level as the
database.

You do not have to reinstall anything on the client.  You will
have to set up their tnsnames.ora file to allow them to see the
new instance but that should be all.  You should not have to do
anything on the client at all in this case.
May 22, 2000 Bob -- Thanks for the question regarding "Index Utilisation", version 7.3.4.5.0
You Asked
Hi There

Is there anyway I can find out the utilisation of indexes on a
table.
We are experiencing performance problems and I believe that the
problem may be over indexing.

Any help would be appreciated

Cheers
Bob
and we said...
The only way I know to do this (index utilization) at this level
is to place each index into its own tablespace.  This can be
done efficiently by:

SQL> alter index <index_name> rebuild tablespace <tablespace>;

We can then enable TIMED_STATISTICS -- an init.ora paramter or
by

system@ORA734.WORLD> alter system set timed_statistics=true;
System altered.

and run the UTLBSTAT script
($ORACLE_HOME/rdbms/admin/utlbstat.sql).  We would let the
system run for a day or so, attempting to exercise each
component of the system.  After that, we would run the UTLESTAT
script (note: both of these scripts should be run as INTERNAL
using SVRMGRL).  This report will show us many things, in
particular -- it will show us reads and writes by tablespace and
time spent doing that.  Since each index is now in its own
tablespace -- you can monitor how and if they are be utilized.

If you believe that overindexing is the cause of the performance
issue (should just affect inserts/updates/deletes) the
UTLBSTAT/ESTAT reports will help you verify that.  Additionally,
they will provide a wealth of information above and beyond that
to help you diagnose performance related issues.

Additionally, if you want to look at the performance
characteristics of a specific application, not the system as a
whole, you should read:
http://technet.oracle.com/doc/server.815/a67775/ch14_str.htm#1018
and learn all about SQL_TRACE, TIMED_STATISTICS and TKPROF.
Excellent tools you already have to perform quite detailed
analysis of an applications performance.
May 22, 2000 Pete -- Thanks for the question regarding "Problem with your recommendation for "Export to a file named after the date"", version 7.3.2.2.0
You Asked
Tom,
Question number 34
"Export to a file named after the date"  I have tried to make
this happen many times using many different techniques.  I was
relieved when I saw your tip, thinking that finally I found the
answer.  Also, the statement in your article "use SQL*Plus as
our general purpose scripting tool" makes a lot of sense and
hopefully I can get this to work.  However, I am having
difficulty geting your example to work.  I will give you your
exact example and my results and then what I was actually trying
to do and the results.

Your example:
column today new_val dt

select to_char(sysdate, 'ddmmyyyy' ) today from dual;

host exp userid=system/manager file=exp_testfab_&dt..exp

exit

Results:
SQL> @set_exp_test.sql

TODAY

-----------------------------------------------------------------
----------
22052000

Command not success.
Input truncated to 4 characters

What I was trying to do was set an environment variable for NT
so that I could reference and use it in my scripts.  This is my
example:

column today new_val dt

select to_char(sysdate, 'ddmmyyyy' ) today from dual;

host set DATETIME=&dt.

host echo %DATETIME%

My Results are:
SQL> @set_nt_variable.sql

22052000

Command not success.
Command not success.
Input truncated to 4 characters

NOTE that I can "host" commands when the &dt is not part of
them.
ie.

host dir     -- works okay

SQL> host echo %local%
test.fab
Command not success.
SQL> host echo %DATETIME%  (I had set DATETIME to xxx outside of
script)
xxx
Command not success.
SQL>

Can you explain why your example will not work in my
situation????  Thanks.

P.S. This forum is great and I belive we can learn a lot from
this.
and we said...
The example actually does in fact work -- its just that each
host sets up its own command processor.  When you:

column today new_val dt

select to_char(sysdate, 'ddmmyyyy' ) today from dual;

host set DATETIME=&dt.

host echo %DATETIME%

the first host actually did set DATETIME in the environment, its
just that by the time you got to the SECOND host command -- the
environment you set up was already gone.

So, how to do this.  It can be done, its just trickier then it
looks (DOS, what a great OS ;)

Here is how (iteratively with common sense failures in between
to show why what appears should work doesn't ):

SQL> column today new_val dt
SQL>
SQL> select to_char(sysdate, 'ddmmyyyy' ) today from dual;

TODAY
--------
22052000

SQL>
SQL> set define ^

We want to run more then one command on a command line.  In
order to do this in NT/DOS we use &&.  We have to make it so
SQLPlus doesn't try to substitute in something so we change the
define character

The following should set an environment variable and then echo
it

SQL> host cmd /C "set DATETIME=^dt. && echo %DATETIME%"
%DATETIME%

But it does not -- why -- because CMD evaluated the %DATETIME%
before the string was evaluated.  We can see the set actually
works -- but the echo, since it was evaluated BEFORE the set --
does not:

SQL> host cmd /C "set DATETIME=^dt. && set"
ALLUSERSPROFILE=C:\Documents and Settings\All Users
APPDATA=C:\Documents and Settings\Thomas Kyte\Application Data
CLASSPATH=c:\program files\cdkj;c:\program
files\cdkj\MSSDK\classes;C:\oracle\orb\classes\yoj.jar;C:\oracle\
orb\classes\share.zip
CommonProgramFiles=C:\Program Files\Common Files
COMPUTERNAME=TKYTE-DEL
ComSpec=C:\WINNT\system32\cmd.exe
DATETIME=22052000
EXINIT=set autoindent wm=4 ignorecase nomesg errorbells
shiftwidth=4 tabstop=4 wrapmargin=4
HOMEDRIVE=C:
HOMEPATH=\
LOGONSERVER=\\TKYTE-DEL
NUMBER_OF_PROCESSORS=1
OS=Windows_NT
Os2LibPath=C:\WINNT\system32\os2\dll;
Path=C:\oracle\bin;C:\Program
Files\Oracle\jre\1.1.7\bin;c:\SFU\common\;C:\ORANT\bin;C:\WINNT\s
ystem32;C:\WINNT;C:\WINNT\System32\
Wbem;"C:\Program Files\VIM-3.29";C:\oracle\orb\bin;c:\msdev\bin
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 6 Model 6 Stepping 10,
GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=060a
ProgramFiles=C:\Program Files
PROMPT=$P$G
SFUDIR=c:\SFU\
SystemDrive=C:
SystemRoot=C:\WINNT
TEMP=C:\DOCUME~1\THOMAS~1\LOCALS~1\Temp
TMP=C:\DOCUME~1\THOMAS~1\LOCALS~1\Temp
USERDOMAIN=TKYTE-DEL
USERNAME=Thomas Kyte
USERPROFILE=C:\Documents and Settings\Thomas Kyte
windir=C:\WINNT

So, that shows it works, the datetime is in the environment.
So, digging further we find the magic solution:

SQL> host cmd /V:ON /C "set DATETIME=^dt. && echo !DATETIME!"
22052000

SQL> set define &

Of course, if you use /V:ON we can have deferred variable
substitution by using ! instead of %.....

So, don't use more then 1 host, separate the commands by &&, use
the !, not %, and use the /V:ON cmd switch....
May 22, 2000 Allen -- Thanks for the question regarding "JDBC and DECODE", version 8.1.6
You Asked
Can you use decode within a SQL statement passed
 through JDBC?  I saw that the driver does not support all
 scalar functions, but in the SQL Reference decode is listed as
 an expression.

Any help you can provide would be greatly appreciated.
and we said...
It is only if you use the {fn FUNCTION_NAME(parameters) }
calling convention that you need to worry about this.  For
example, instead of using the fn keyword in embedded SQL92
syntax:

Statement stmt = conn.createStatement ();
stmt.executeUpdate(
       "UPDATE emp SET ename = {fn CONCAT(’My’, ’Name’)}");

Use Oracle SQL syntax:

stmt.executeUpdate(
       "UPDATE emp SET ename = CONCAT(’My’, ’Name’)");

In this fashion, there are no unsupported scalar routines.
May 23, 2000 Sheetal -- Thanks for the question regarding "How to move my pro*c to point to another oracle instance", version 7.3.4.5
You Asked
Hi Tom,

I have an Pro*c program which points to a instance with the
uid/pwd specified in the proc.mk file. Now how do I make it
point to another database instance ? Do I have to recompile ?

Any help is appreciated.

Thanks
Sheetal
and we said...
You do not have to run the Proc*c application against the same
database it was precompiled against.

You simply parameterize the EXEC SQL CONNECT statement with a
host variable and at run time you may place any username,
password, and connect string in you wish.

In short, you really don't have to do anything to accomplish
what you want -- other then change the value in the host
variables you are using in your EXEC SQL CONNECT statement.
May 23, 2000 Sam -- Thanks for the question regarding "Analyzing catalog tables ?", version 8.1.5
You Asked
Should the tables owned by 'SYS' be analyzed ?
    Will this improve performance when the dictionary tables
are acccessed (external SQLs, internal access or both) ?
    Do  recursive SQLs use the cost-based optimizer ?
Thanks.
SL
and we said...
Currently, SYS tables should not be analyzed.

It will hurt performance in general.  The data dictionary
queries are written with either the rule based optimizer in mind
or they are hinted (and the addition of statistics will make the
hints not work -- the hints will not always be followed with
statistics in place and the plans could go the wrong way).

Recursive SQL will use the CBO -- many of the queries are hinted
but they are expecting no statistics (hence the query plans are
very stable).
May 23, 2000 Christopher -- Thanks for the question regarding "Functional Indexes on Date Attributes", version 8.1.5
You Asked
I've been trying to cajole the cost-based optimizer into using
an index hint to use a functional index on
TRUNC(Detail_Post_Date)
which is a date attribute. I can't get it to use the index
unless I first create it as:
TO_CHAR(TRUNC(Detail_Post_Date))
which of course loses the date arithmetic which we need in the
query. Any ideas on getting function-based indexes to work with
dates?

Thanks!

P.S. I've opened a TAR on this, 12986564.600
and we said...
Hey, I know that issue -- I filed it myself.  It is fixed in
Oracle8i release 2 (8.1.6).  The work around currently is to use
a small plsql function "my_trunc" for example that simply
returns the trunc of the date.  In 8.1.6 you can use TRUNC on
the date. This affected builtin (but not user written) functions
that returned DATES.

Hdr: 902521 8.1.5 RDBMS 8.1.5 QRY OPTIMIZER PRODID-5 PORTID-453
9

Abstract: FUNCTION BASED INDEX ON TRUNC(DATECOLUMN) IS NEVER
USED

*** TKYTE 06/02/99 10:20 am ***
If I create an index on a column as follows:
SQL> create index emp_idx1 on emp( trunc(hiredate) );
.
the optimizer will never use that index.  If I write a plsql
function, my_trunc( p_date in date ) return date that simply
returns the trunc(p_date), the optimizer immediately will use
that function.  for some reason, TRUNC is not a candidate for
function based indexes (although other functions such as substr
are).
.
Full test case showing that trunc(datecolumn) does not work and
that my_trunc(datecolunmn) does is in...
May 24, 2000 Juergen -- Thanks for the question regarding "sql unload utility", version 8.0.5
You Asked
Hello Tom,

i find this utility very useful but i am not able to extrat the
files from unloader_tar.gz. Please sent me this files per mail
for Nt. Thanks in advance.

best regards

Jürgen
and we said...
Some browsers unfortunately rename the file.  The correct file
name is:

unloader.tar.gz

(2 dots).  This file is a tarred, gzip file -- when the browser
renames it to unloader_tar.gz, winzip thinks it is just gzipped
and doesn't understand there is a tar file in there.

On Unix, you could:

$ gunzip unload_tar.gz | tar xvf -

On NT, you must

C:\> rename unloader_tar.gz unloader.tar.gz
C:\> unloader.tar.gz

to uncompress it.
May 24, 2000 Noohu -- Thanks for the question regarding "Database Monitoring and Trend", version 8i
You Asked
Hi,

I was wondering if there are any scripts or tools that will
allow us track the various database health statistics
periodically (say daily) which shall be used to monitor the
database trend in terms of space usage and performance. I guess
it will be useful to estimate the table growth and the various
factors that get affected by the growth of the database. It will
also be useful in documentation and performance tuning of the
database.

Any comment will be greatly appreciated!

Thanks in advance.

Noohu.
and we said...
Well, there are a lot of tools to do this.

The documentation you are looking for is simply the Server
Tuning Manual.  This is online at technet and for Oracle8i can
be found at:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76992/toc.htm
The tools you will want to use are

o utlbstat/estat.  Very simple utilities run from a command
prompt in svrmgrl.  You would run utlbstat at the beginning of a
date, utlestat at the end of the day (these are found in
$ORACLE_HOME/rdbms/admin).  This creates a very simple
report.txt file with many system level statistics.  It will show
you what your major wait events are, how your IO is spread out
across files (or not) and so on.

o SQL_TRACE and TKPROF.  These are explained in some detail
in the above referenced document.  They are excellent for tuning
applications/stored procedures.

o OEM tuning packs. See
http://www.oracle.com/take_control/index.html?tuning.html
for details on that
May 25, 2000 Vinnie -- Thanks for the question regarding "Functions", version 8.1.5
You Asked
I have the following function:
PROMPT Creating Function 'SIG_UPD_FUNCTION'
CREATE OR REPLACE FUNCTION SIG_UPD_FUNCTION
 (P_SENSOR_NAME IN VARCHAR2
 ,P_SENSOR_SIG IN VARCHAR2
 )
 RETURN VARCHAR2
 IS
-- PL/SQL Specification
-- PL/SQL Specification
v_tot_count     sensor_signature.tot_count%TYPE default 0;
  v_sig_name    sensor_signature.sig_name%type;
  v_errtext     VARCHAR2(100);
  v_errcode     NUMBER;
  v_priority                NUMBER;
  l_sensor_name sensor_signature.sensor_name%TYPE
:=UPPER(p_sensor_name);
-- PL/SQL Block
BEGIN
         SELECT sig_name, tot_count
         INTO v_sig_name, v_tot_count
         FROM sensor_signature
         WHERE sensor_name = l_sensor_name
         AND sensor_sig_name = p_sensor_sig;
-- End of update, Return aide_signature to EVENT_UPD --
RETURN v_sig_name;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
        v_sig_name := '';
        RETURN v_sig_name;
END sig_upd_function;
/

Will v_sig_name be returned even if the select returns nothing?
and we said...
v_sig_name will be returned in 2 cases:

o the select works and finds exactly 1 row in the table.

o the select fails due to either NOT finding a row or finding
more then one row.

If some other error occurs (eg: the select needed to sort data
and you ran out of temp space), the function will propagate an
error to the caller -- nothing would be returned at that point.

Note that v_sig_name := ''; is in effect the same as v_sig_name
:= NULL; and since all variables are defined as NULL to begin
with is not really necessary.
May 25, 2000 Seetharaman -- Thanks for the question regarding "Oracle Database Server Utility UTL_FILE", version 8.0.5
You Asked
Dear Mr. Tom,

  Greetings!.

  In my NT Server, I want to generate files onto a Mapped
network drive.  You have already mailed me telling it's
impossible on NTOS.  But how to accomplish that task?.. Is there
any oracle tool to generate files and transfer it to any of the
mapped drives automatically thro' stored procedure or function?

Thanks in advance

Seetharaman Srinivasan
and we said...
I did not say it was impossible -- I said:

...
In NT, the database starts in its environment -- these disks you
"mount" when you log in are your network drives (g and i).  The
are not part of the Oracle environment.  You'll need to set it
up under NT so that G: and I: are part of the ORACLE servers
environment -- not just the guy logged into at some point in
time.
...

So, the question is how to do that.  This is support note
45172.1 on the subject:

Overview
========

From release 7.3 file input/output capabilities were added to
PL/SQL on the server. This is achieved through the supplied
package UTL_FILE

The following text covers how to setup directories for access by
the UTL_FILE package on windows NT 3.51 and 4.0.

Directory Names
===============

For UTL_FILE's procedures to access server directories the
directories to be accessed must be specified in the init.ora
file, for example :

UTL_FILE_DIR=E:\LOGDIR

Quotes and a trailing \ are not necessary.

1) Long filenames or directory names with mixed case
----------------------------------------------------

For this to work the directory specified for use in the UTL_FILE
procedures must exactly match (including case) that specified in
UTL_FILE_DIR. Although the UTL_FILE_DIR init.ora parameter does
not have to exactly match the actual directories case.

e.g. UTL_FILE_DIR=E:\LogDirectory
     UTL_FILE.FOPEN('E:\LogDirectory','logfile.log','w');

2) Directories with space characters
------------------------------------

For this to work the directory must be delimited by double
quotes in the init.ora parameter file.

e.g. UTL_FILE_DIR="E:\LOG DIR".

3) Making multiple directories available
----------------------------------------

To specify multiple directories have a separate UTL_FILE_DIR
line for each directory, but make sure these are on consecutive
lines otherwise only the last directory will be accessible.
Alternatively separate each directory with a space on a single
UTL_FILE_DIR line.

Directory Permissions
=====================

Directories on FAT partitions
-----------------------------

FAT does not support file or directory permissions.

Directories on NTFS partitions
------------------------------

When an oracle instance is created the services that support it
are setup to Log On As the SYSTEM (or operating system) account.
For UTL_FILE's procedures to access directories that do not have
access granted to everyone they must have "Change" privileges
granted to the SYSTEM account. If the OracleServiceXXXX service
has been altered to log on as another account, it is this
account that must be given access to the directories.

Accessing Network Directories
=============================

Netware Networked Directories
-----------------------------

For this to work ensure that the account that started the Oracle
instance has a mapped network drive connected using a fully
qualified username/password with the same drive letter and path
as is specified by UTL_FILE_DIR.

NT Networked Directories
------------------------

When an oracle instance is created the services that support it
are setup to "Log On As" the SYSTEM (or operating system)
account, this account has very few privileges and no access to
NT Domains. To access another NT machine the OracleServiceXXXX
must be setup to logon to the appropriate NT Domain as a user
who has access to the required location for UTL_FILE.

To change the default logon for the Oracle services, go to :

  -> Control Panel
     -> Services
        -> OracleServiceXXXX (where XXXX is the instance name)
           -> Startup
              -> Log On As

Choose the "This Account" radio button, then complete the
appropriate domain login information. Once the services have
been setup as a user with the appropriate privileges the are two
options for setting UTL_FILE_DIR :

a. Mapped Drive : To use a mapped drive, the user that the
service starts as must have setup a drive to match UTL_FILE_DIR
and be logged onto the server when UTL_FILE is in use.

b. Universal Naming Convention : UNC is preferable to Mapped
Drives because it does not require anyone to be logged on and
UTL_FILE_DIR should be set to a name in the form \\<machine
name>\<share name>\<path>.
Review & Followup
Rating: 5
July 04, 2001
Reviewer: Afonso from Joinville - SC - Brazil

Rating: 5
Finally the answer January 03, 2002
Reviewer: Richard Wainwright from London UK.
After much searching it seems that my problem with building the dictionary for
logminer was due to not getting a perfect match between the utl_file_dir
parameter and the dictionary_location value used by utl_file.

Fantastic resource from the mundane to the arcane
Thanks

Rating: 5
Finally September 11, 2002
Reviewer: Joe Suchy from Milwaukee, WI
Most of the other responses to UTL_FILE questions always breezed over the
UTL_FILE_DIR part.  No one else mentioned the need for exact matches, including
case.  Thanks for a perfect explanation.

Rating: 5
Excellent October 08, 2002
Reviewer: Bala Nemani from USA
I could not get this kind of response when working with Oracle Support directly.
Very helpful

Rating: 5
Great info August 10, 2003
Reviewer: Sikandar Hayat from Pindi Bhattian - Pakistan

Rating: 3
thanks for your explain September 27, 2003
Reviewer: haihong li from BeiJing .China
It's very useful.

May 25, 2000 Reji -- Thanks for the question regarding "JDBC Driver for Linux", version 8.1.5 & 8.1.6
You Asked
Tom:
    Where can I find JDBC drivers for Linux.  I am specifically
    looking for JDBC driver for LINUX with jdk1.2.

    TIA
and we said...
The JDBC thin drivers are available online at
http://technet.oracle.com/software/tech/java/sqlj_jdbc/software_index.htm
they are platform independent.  You can goto
http://technet.oracle.com/
and order the Linux software as well if you want the "thick" oci
drivers.
May 25, 2000 Amit -- Thanks for the question regarding "Error during starting DATABASE.", version 8.1.6
You Asked
Problem during new database creation or starting existing
database by using Oracle Enterprise Edition 8.1.6 on Sun Solaris
2.7.

Hereby i am attching the error..

SVRMGR> connect internal
Connected.
SVRMGR> startup
ORA-27146: post/wait initialization failed
and we said...
It sounds like you have not configured enough semaphores/shared
memory and other system level parameters.  This error will occur
when you have not configured sufficient system resources.

The solaris installation guide has a chapter:

2 Pre-Installation
  UNIX System configuration

It is available online at
http://technet.oracle.com/
if you do not have a copy.  It will tell you the necessary
settings for your /etc/system file.  You must reboot with "boot
-r" after making these kernel changes.
May 25, 2000 Daljeet -- Thanks for the question regarding "JDBC access for Procedures with table type as i/p parameter", version 8.1.5
You Asked
I have to access the following proc from java:

CREATE OR REPLACE PACKAGE TESTME IS
TYPE TEMPTRACKTABLE IS TABLE OF VARCHAR2(30);
PROCEDURE RETRIEVEANARRAY(MY IN TEMPTRACKTABLE);
END;

CREATE OR REPLACE PACKAGE BODY TESTME IS
PROCEDURE RETRIEVEANARRAY(MY IN TEMPTRACKTABLE) IS
BEGIN
    DBMS_OUTPUT.PUT_LINE(MY(1));
END;
END;

Please explain the input output parameters passing with JDBC for
table or array type.

Thanks a million
Daljeet
and we said...
The short answer is -- you cannot bind to plsql TABLES, RECORDS
or BOOLEANs from JDBC.  See
http://technet.oracle.com/doc/java.815/a64685/oraext9.htm#1000993
for the details.  The longer answer is there are 2 ways to work
around this.

the first way would have you bind a simple delimited string from
java and parse it into the table (and if need be put it back
into the string) in plsql.  That is, instead of executing a
block of plsql like:

begin
   testme.retrievearray( :java_bind_variable );
end;

you would have a block of code like:

begin
  testme.retrievearray( STR2ARRAY(:java_string) );
end;

The following exmaple, done in sqlplus, shows how to code a
block you would embed in your java client that can call a plsql
routine that takes a PLSQL table type as an IN/OUT parameter.
You could make the functions I have in the block (str2array,
array2st) be standalone functions in the database (to avoid
having to put them in the block) or not -- up to you:

ops$tkyte@dev8i> create or replace package my_pkg
  2  as
  3      type Array is table of number index by binary_integer;
  4
  5      procedure array_rev( p_array in out array );
  6  end;
  7  /
Package created.

ops$tkyte@dev8i> create or replace package body my_pkg
  2  as
  3
  4  procedure array_rev( p_array in out array )
  5  is
  6      l_tmp    array;
  7  begin
  8      for i in 1 .. p_array.count loop
  9          l_tmp( p_array.count-i+1 ) := p_array(i);
 10      end loop;
 11      p_array := l_tmp;
 12  end;
 13
 14  end;
 15  /
Package body created.

Thats the package we want to invoke from java.  java cannot
bind to the plsql table type.  we'll let it bind a string
instead

ops$tkyte@dev8i> set autoprint on
ops$tkyte@dev8i> variable a varchar2(255)
ops$tkyte@dev8i> exec :a := '1,2,3,4,5,6,7'
PL/SQL procedure successfully completed.

That is our demo list of values we want to send in and get
back out...

A
--------------------
1,2,3,4,5,6,7

ops$tkyte@dev8i> declare
  2      l_tmp    my_pkg.array;
  3      function str2array( p_str in varchar2 )
  4      return my_pkg.array
  5      as
  6          l_str    long default p_str || ',';
  7          l_tmp    my_pkg.array;
  8      begin
  9          loop
 10              exit when l_str is null;
 11              l_tmp(l_tmp.count+1) :=
 12                   substr( l_str, 1, instr(l_str,',')-1 );
 13              l_str := substr( l_str, instr(l_str,',')+1);
 14          end loop;
 15          return l_tmp;
 16      end;
 17      function array2str( p_tbl in my_pkg.array )
 18      return varchar2
 19      is
 20          l_str     long;
 21          l_sep     varchar2(1);
 22      begin
 23          for i in 1 .. p_tbl.count loop
 24              l_str := l_str || l_sep || p_tbl(i);
 25              l_sep := ',';
 26          end loop;
 27          return l_str;
 28      end;
 29  begin
 30      l_tmp := str2array( :a );
 31      my_pkg.array_rev( l_tmp );
 32      :a := array2str( l_tmp );
 33  end;
 34  /

PL/SQL procedure successfully completed.

A
--------------------
7,6,5,4,3,2,1

That is the block of code we need to put in our java
application.  We could make it a stored procedure of course, or
break out str2array and array2str to make it smaller.

The second option is much like the first but instead of using
strings, we would use OBJECT types.  Java can bind to nested
table and varray types.  You would still have to create a small
interface layer to convert the nested table into the
corresponding plsql table but you would not have to string up
the array elements.
Review & Followup
Rating: 2
VARRAY/NESTED Tables as IN/OUT Parameter through JDBC April 26, 2001
Reviewer: Avinash C Dixit from UK
You have quite well explained about how to wrap PL/SQL tables through JDBC. But
the question is how to pass the VARRAY or Nested Table as IN/OUT parameter
through JDBC.

JDBC can bind both VARRAY & NESTED Tables.

Rating: 4
August 20, 2001
Reviewer: Bellatrix from Austria

Rating: 4
answer to previous question September 04, 2002
Reviewer: vinci
Create your types in the database (not in PL/SQL).
Ex. create type x as varray(5) of number;
    create type y as table of number;

Use this as the in/out parameter of ur procedure.
Ex. create procecure xx(var1 IN y ) as
    begin
           for i in y.count
           loop
             update t set col1=y(i);
            end loop..etc etc
   end;

From java u can pass a normal integer array into the proc for this example.

May 26, 2000 V Siva -- Thanks for the question regarding "No. of rows in tables -- explaination of NUM_ROWS in ALL_TABLES", version 7.3.2.3.0
You Asked
Hi tom,

When I use the column Num_Rows of ALL_TABLES column, it gives a diiferent value,
than when i select count(*) from the table. Why? What the column "NUM_ROWS" in
ALL_TABLES table indicate?

Thanks & Regards,
Siva
and we said...
The num_rows column in the <user|all|dba>_TABLES view is the (possibly
estimated) number of rows in a table as of the time of the last analyze.  This
column is used by the optimizer to judge how big a table is.  It does not have
to be exact for this purpose, just close.  Here is an example:

ask_tom@OSI1.WORLD> set null NULL

ask_tom@OSI1.WORLD> create table t ( x int, y varchar2(4000) );
Table created.

ask_tom@OSI1.WORLD> insert into t
  2  select object_id, rpad('*',mod(object_id,3999)+1,'*')
  3    from all_objects
  4  /
10464 rows created.

ask_tom@OSI1.WORLD> select num_rows
  2    from user_tables
  3   where table_name = 'T'
  4  /

  NUM_ROWS
----------
NULL

Num_Rows initially starts NULL.  It has no value.  It will not have one until
we analyze the table

ask_tom@OSI1.WORLD> select count(*)
  2    from T
  3  /

  COUNT(*)
----------
     10464

The table does in fact have rows....

ask_tom@OSI1.WORLD> analyze table t estimate statistics sample 1 percent
  2  /

Table analyzed.

ask_tom@OSI1.WORLD> select num_rows
  2    from user_tables
  3   where table_name = 'T'
  4  /

  NUM_ROWS
----------
     10435

Just to show that an analyze does not have to be precise.  An ESTIMATE will be
just that -- a ballpark figure.  It'll be good enough for the optimizer to
use.

ask_tom@OSI1.WORLD> analyze table t compute statistics
  2  /
Table analyzed.

Now, lets be more precise...

ask_tom@OSI1.WORLD> select num_rows
  2    from user_tables
  3   where table_name = 'T'
  4  /

  NUM_ROWS
----------
     10464

Thats the correct answer -- for now.  As soon as we add/remove rows from this
table, this answer will begin to get stale.
May 26, 2000 minnie -- Thanks for the question regarding "How to load datas into a table in which a field is a type of varray by SQL*LOADER?", version Oracle 8i 8.1.5
You Asked
I want to load datas into a table, this table has a field likes
this

create type my_type is varray(10) of number(12,2);

create table my_table
(
   my_name

);
and we said...
I'll refer you to ULCASE10.ctl and ULCASE10.sql found in your
$ORACLE_HOME/rdbms/demo directory.  A smapper example is
included here with some comments.

The ULCASE10.sql script creates the target schema.  The purpose
of the example is to show 2 things

o how to load object refs easily into the database.
o how to load varray's.

Basically, varray's will be encoded into the sqlldr datafile as
follows:

o a field will be included in the datafile.  This field will
contain the number of array elements to expect in the datafile.
This field will not be loaded but will be used by sqlldr to
figure out how many array elements are coming in the file.

o a (set of) field(s) representing the elements of the array.

Here is a simple small example, refer to ulcase10.ctl for a more
complex one.

ask_tom@OSI1.WORLD> create type myArrayType
  2  as varray(10) of number(12,2)
  3  /
Type created.

ask_tom@OSI1.WORLD> create table t
  2  ( x int primary key, y myArrayType )
  3  /
Table created.

That is the schema we want to load into.  Now, here is a
sample control/data file we can use to load it with.

LOAD DATA
INFILE *
INTO TABLE T
replace
fields terminated by ","
(
  x                   char,
  y_cnt               FILLER    char,
  y                   varray count (y_cnt)
  (
    y    char
  )
)

BEGINDATA
1,2,3,4
2,10,1,2,3,4,5,6,7,8,9,10
3,5,5,4,3,2,1

The important thing to note here is the inclusion in the
datafile of the array count.  The line:

1,2,3,4

for example has:

1 -- mapped to X, the primary key.
2 -- mapped to y_cnt, the count of array elements
3,4 -- mapped to y, the array elements themselves

After running sqlldr, we find:

ask_tom@OSI1.WORLD> select * from t;

         X Y
---------- ------------------------------
         1 MYARRAYTYPE(3.00, 4.00)
         2 MYARRAYTYPE(1.00, 2.00, 3.00,
           4.00, 5.00, 6.00, 7.00, 8.00,
           9.00, 10.00)

         3 MYARRAYTYPE(5.00, 4.00, 3.00,
           2.00, 1.00)

Which is exactly what we wanted..
May 26, 2000 Rajashekar -- Thanks for the question regarding "sql query for referential cursor", version 8.0.4.0.0
You Asked
Dear Tom,

I have the following query to return a referential cursor in the

procedure.

SELECT DISTINCT
a.Req_To_Buy_Or_Sell,a.listing_ID,a.listing_date,1,b.subcategory,

a.item,a.total_quantity,c.unit,a.unit_price,d.currency,c.unit
FROM
                          t_listing a,m_subcategory b,m_unit
c,m_currency d WHERE
                          a.user_id=in_user_id AND
                          b.subcategory_id=a.subcategory_id AND
                          c.unit_id = a.total_qty_unit_id AND
                          d.currency_id =
a.unitprice_currency_id AND
                          c.unit_id = a.unitprice_unit_id

Now I want to add the following parameters in the select list
from the following table
TABLE NAME :T_RESPONSE
    RESPONSE_ID                 INTEGER                not null,
    RESPONSE_DATE               DATE                   null    ,
    LISTING_ID                  INTEGER                null    ,
    RESPONSE_NO                INTEGER                null    ,
    RESPONDENT_ID               INTEGER                null    ,
    RECIPIENT_ID                INTEGER                null    ,
    RESPONDENT_NEW_FLAG            NUMBER(1)              null
 ,
    RECIPIENT_NEW_FLAG             NUMBER(1)              null
 ,

FOR THE LISTING ID EACH SELECTED IN THE T_LISTING TABLE I WANT
TO COUNT
THE no. of rows in the above table distinct of respondent id
which
is a parameter in the select list

and similarly i want to count the no. of respondent_new_flag = 1

from the above table for the each listing id selected in the
t_listing table which is another parameter in the select list.

I want to add the above parameters to the select statement can i

do that if yes how do i do that. I want a single sql statement
since
i am using ref. cursor which is an OUT parameter from my
procedure.

Awaiting for your reply,

Regards
Raj
and we said...
If I understand correctly -- after you get the distinct info
from above -- you want to add to it

o the number of distinct responses linked to it by listing_id
o the count of the number of linked records with new_flag = 1

If so, the most straightforward way would be to:

select x.*, y.distinct_response_id, y.new_flag_cnt
from
(
SELECT DISTINCT a.Req_To_Buy_Or_Sell,
                a.listing_ID,a.listing_date,
                1 some_number,
                b.subcategory,
                a.item,
                a.total_quantity,
                c.unit c_unit1,
                a.unit_price,
                d.currency,
                c.unit c_unit2
   FROM t_listing a, m_subcategory b, m_unit c, m_currency d
  WHERE a.user_id=UID
    AND b.subcategory_id=a.subcategory_id
    AND c.unit_id = a.total_qty_unit_id
    AND d.currency_id = a.unitprice_currency_id
    AND c.unit_id = a.unitprice_unit_id
) X,
( select listing_id ,
         count( distinct response_id ) distinct_response_id,
         sum(decode(RESPONDENT_NEW_FLAG,1,1,0)) new_flag_cnt
   from T_RESPONSE
   where listing_id in ( select listing_id from t_listing
                          where user_id = UID )
   group by listing_id ) Y
where x.listing_id = y.listing_id (+)
/

The inline view Y simply tallies up the count of distinct
response_id's and sum's the number of rows with new_flag=1 for
each listing_id (the IN restricts the set we generate to a set
of LISTING_IDS we might encounter).  We then OUTER join to this
inline view in the event there are listing_ids with no rows in
T_RESPONSE.  If there is always a row in T_RESPONSE, we can drop
the (+) outer join.

If you find the performance of that to not be very good, what
might work as a substitute would be something like:

create or replace
function distinct_response_id( p_listing_id in number )
return number
as
    l_cnt    number;
begin
    select count( distinct response_id ) into l_cnt
      from t_response
     where listing_id = p_listing_id;

    return l_cnt;
end;
/

create or replace
function new_flag_cnt( p_listing_id in number )
return number
as
    l_cnt    number;
begin
    select sum(decode(RESPONDENT_NEW_FLAG,1,1,0)) into l_cnt
      from t_response
     where listing_id = p_listing_id;

    return l_cnt;
end;
/

select x.*,
       distinct_response_id(x.listing_id),
       new_flag_cnt(x.listing_id)
from
(
SELECT DISTINCT a.Req_To_Buy_Or_Sell,
                a.listing_ID,a.listing_date,
                1 some_number,
                b.subcategory,
                a.item,
                a.total_quantity,
                c.unit c_unit1,
                a.unit_price,
                d.currency,
                c.unit c_unit2
   FROM t_listing a, m_subcategory b, m_unit c, m_currency d
  WHERE a.user_id=UID
    AND b.subcategory_id=a.subcategory_id
    AND c.unit_id = a.total_qty_unit_id
    AND d.currency_id = a.unitprice_currency_id
    AND c.unit_id = a.unitprice_unit_id
) X
/

Which is pretty much the same except that we only count the
distinct responses/sum the flags for rows we actually fetch, it
may (or may not) perform better  -- depends on what you are
doing....
May 26, 2000 Mohammad -- Thanks for the question regarding "unzippnig error", version 8
You Asked
Hi
I have downloaded unloader.tar.gz (10,240 bytes).
But I cann't open it with Winzip 7.0 That is I get Cannot open
file error message.
TIA
and we said...
Ok, here is the story on that.

MS IE seems to believe that a .tar.gz file is "something
special".  the tar.gz file on my system is really:

-rw-r--r--   1 tkyte        1134 Jul 30  1999 unloader.tar.gz

but MSIE always makes it a 10,240 byte file of garbage when it
gets it down (in addition to renaming it to the oh so
inconvienent unloader_tar.gz).....

So, in order to appease their software, I've changed the
download page to have both a ZIP and a tar.gz file.  So if you
goto
http://osi.oracle.com/~tkyte/flat/index.html
and reload that page, you can get the zip file which should be

-rw-r--r--   1 tkyte        2635 May 26 13:18 unloader.zip
May 26, 2000 E.J. -- Thanks for the question regarding "Returning the first row of an ordered resultset in Oracle 7.3.4.2", version 7.3.4.2
You Asked
In Oracle 8.0.x and earlier you can't order subselects/views so
how can I return the first row of an ordered resultset without
using a temp table or cursor?  Here's the basic query:

select * from table order by cola, colb;

Adding the 'where rownum = 1' obviously doesn't work since it
orders it after the resultset is returned.

Thanks,
E.J. Wilburn
and we said...
What will usually work is "group by" but you must be aware of
many things:

o group by does not have to sort.  In 7.3 it almost always does
but as the versions go on, it does not.  Partitioning, Index
Organized tables, better optimizer, and so on make this the
case.

o group by does a binary sort, if you are using NLS this might
result in data being ordered differently then if you use an
order by.

It might look like this:

select *
  from ( select c1, c2, c3, cola, colb
           from T
          group by cola, colb, c1, c2, c3 )
  where rownum = 1;

If in fact, cola+colb is unique, you can:

select *
  from ( select min(c1), min(c2), min(c3), cola, colb
           from T
          group by cola, colb )
  where rownum = 1;

for example:

  1  select *
  2    from ( select ename, min(empno), min(deptno)
  3                from emp
  4            group by ename )
  5*  where rownum = 1
ask_tom@OSI1.WORLD> /

ENAME      MIN(EMPNO) MIN(DEPTNO)
---------- ---------- -----------
ADAMS            7876          20

1 row selected.

So, just to make sure I've caveated this -- make sure to test
this on your data if you use a group by (and to convert it when
you goto 8i).  Here is an example of a group by that does not
sort the way you expect:
SQL> create table emp as select * from scott.emp where rownum <=
5;
Table created.

SQL> create index emp_idx on emp(job,ename);
Index created.

SQL> select ename, job from emp where ename >chr(0) and job
>chr(0)
  2  group by ename, job ;

ENAME      JOB
---------- ---------
smith      CLERK
jones      MANAGER
allen      SALESMAN
martin     SALESMAN
ward       SALESMAN

Since group by ename, job is the same as group by job, ename --
it just used the index to do the work here and blew off the sort
-- so beware.

Another option that always works would be:

ask_tom@OSI1.WORLD> select ename, empno, deptno
  2    from emp a
  3   where ename = ( select min(ename)
  4                     from emp )
  5     and deptno = ( select min(deptno)
  6                      from emp b
  7                     where b.ename = a.ename )
  8     and rownum = 1
  9  /

ENAME           EMPNO     DEPTNO
---------- ---------- ----------
ADAMS            7876         20

1 row selected.

Where ename represents COLA and deptno represents COLB.  We find
the smallest (or largest) ename and for that ename we find the
smallest deptno for that ename.  We find the first row having
that smallest ename, deptno.


Subject | Article | Last Updated (East coast time)
GPFs with Oracle Installer | article only | May 27, 2000 07:11 am
CANNOT COMPILE STORED PROCEDURE WITH DBMS_PIPE | article only | May 27, 2000 01:38 pm
Functional index | article only | May 28, 2000 10:29 am
Trigger a procedure when sysdate expires -- how to run a procedure at a given future point in time. | article only | May 28, 2000 10:45 am
Animated GIFS don't animate in Develepor 2000 Forms 5.0 | article only | May 28, 2000 11:06 am
Implementing Standby database on Oracle 8.0.5 | article only | May 29, 2000 09:13 am
Dropped Tables -- how can i get them back. | article only | May 29, 2000 09:20 am
how to pass javascript variable value to pl/sql variable | article only | May 30, 2000 10:23 am
Failover/Scalability/Redundancy strategy | article only | May 30, 2000 10:46 am
Array | article only | May 30, 2000 01:40 pm
The 'long and short' of tables | article only | May 30, 2000 07:41 pm
Field Encryption | article only | May 31, 2000 09:20 am
Deleting Duplicate Rows from a table | article only | May 31, 2000 12:56 pm
Monitoring jobs | article only | May 31, 2000 04:45 pm
Dynamic Performance Views -- IO by segment | article only | Jun 01, 2000 09:19 am
How to purge a subset of data without generating the redo entries? | article only | Jun 01, 2000 09:34 am
dynamically executing a function with input and output parameters | article only | Jun 01, 2000 10:38 am
SQL-Loader loading a ever increasing log file | article only | Jun 01, 2000 10:45 am
Uploading a file from OAS | article only | Jun 01, 2000 10:57 am
References between two different database's tables | article only | Jun 01, 2000 02:03 pm
Extents sizing strategy | article only | Jun 01, 2000 02:37 pm
Oracle Parallel Server -- New 8.1.6 Basic High Availability Configuration | article only | Jun 01, 2000 03:06 pm
Migratioin to 8i on digital unix from 7.3.2 | article only | Jun 01, 2000 03:12 pm
Database Links and Test Databases | article only | Jun 01, 2000 03:58 pm
Date function -- convert DDDYY into a date | article only | Jun 02, 2000 07:33 am
alter column definition | article only | Jun 02, 2000 07:53 am
How to build a query with two counts | article only | Jun 02, 2000 09:11 am
plsql -- is there a byte size limit? | article only | Jun 02, 2000 09:33 am
Archiving Redologs - who/what does the archiving | article only | Jun 02, 2000 09:56 am
Query Tuning -- what guides can I read. | article only | Jun 02, 2000 12:32 pm
Retriving Data dynamically | article only | Jun 02, 2000 01:18 pm
row(s) 1 - 31 of 31
May 27, 2000 Shabbir -- Thanks for the question regarding "GPFs with Oracle Installer", version 7.3.2/8.0.3/8.0.4/8.0.5
You Asked
Have been facing a lot of problems with Oracle installer, be it
even if I am installing a different version(lower or higher), or
I am adding products of the same version. I keep on getting
GPFs.

Every time, I require a clean m/c which is sometimes a very
tedious job. This is on Windows NT/95/98

Any workarounds/solutions for this?

Regards,
Shabbir
and we said...
Given the versions of the database you have listed, you might be
hitting this:
http://metalink.oracle.com/
Win32 Oracle Installer Y2K Fix
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Versions Affected
~~~~~~~~~~~~~~~~~
  Product & Oracle versions affected
  Oracle Installer for Win32 v3.3.1.1.0 and lower

 This Oracle Installer version has been certified to work with
Oracle  Server and Oracle Clients 7.3.4, 8.0.4, and 8.0.5.

Platforms Affected
~~~~~~~~~~~~~~~~~~
  Exclusive to Win32 (Windows NT / Windows 95 / Windows 98)

Description
~~~~~~~~~~~
  The RGS product registration file contained a 2-digit
  timestamp.

Likelihood of Occurrence
~~~~~~~~~~~~~~~~~~~~~~~~
  100% certainty after Dec 31st, 1999.

Possible Symptoms
~~~~~~~~~~~~~~~~~
  Protection Exception (GPF)
  Access Violation

Workaround
~~~~~~~~~~
  Set the system clock back to 1999, perform the install,
  and reset the system clock back to 2000.

Patches
~~~~~~~

  Download the

  Y2K Compliant Oracle Installer for Win32 (ver.3.3.1.1.0C) from
MetaLink.

  Login to MetaLink at
http://www.oracle.com/support/elec_sup/
  In MetaLink V1 select the Downlaod button to access patches.
  In MetaLink V2 select the Patches button.

    1.  Select Oracle Installer for the Product and Windows NT
for the
Platform.
    2.  Click Go.
    3.  Download the readme and patch.

References
~~~~~~~~~~
  BUG 826393 / BUG 826397

This alert was updated 30-Nov-1999 with a new patch set id.

This alert is a Year 2000 Readiness Disclosure, and is provided
pursuant to the Year 2000 Information and Readiness Disclosure
Act.
_____________________________________
Oracle WorldWide Customer Support
May 27, 2000 Andy -- Thanks for the question regarding "CANNOT COMPILE STORED PROCEDURE WITH DBMS_PIPE", version version 8.1.6
You Asked
I cannot compile the stored procedure with DBMS_PIPE. I got the
error message PLS-00201. I have checked the account have granted
the role execute_catalog_role. But, I can use DBMS_PIPE in
SQL*Plus. After I have granted execute to public or user, I can
compile the stored procedure.
and we said...
see
http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
May 28, 2000 Ratnadeep -- Thanks for the question regarding
      "Functional index", version 8.1.5

      You Asked
According to the oracle documentation of 8.1.5 we can create
functional index like create index idx01 on emp (upper(ename)).

I could create the index , but never could access it. Does it
work really ?

Please let me know.

Thanks,

Ratnadeep Bose

      and we said...
See

http://osi.oracle.com/~tkyte/article1/index.html
for a complete tutorial I've written on this subject. It'll show
you whats required, what works and what doesn't.

May 28, 2000 Chen -- Thanks for the question regarding
      "Trigger a procedure when sysdate expires -- how to run a procedure at a
      given future point in time.", version version 8.1.5

      You Asked
Dear sir,
I am now using Oracle Database8.1.5 and Oracle Web Application
Server3.02 to develope a business website.
There is a PL/SQL procedure which needs to be auto-excuted when
sysdate expires a Date Type variable.I don't know how to trigger
this procedure.

Thank you very much!
John Chen

      and we said...
This is what DBMS_JOBs is for.  For the full documentation on
this, see

http://technet.oracle.com/doc/server.815/a68001/dbms_job.htm#999107
In short, what you will do is -- given that you want a job (a
stored procedure) to run on a given date/time, you would
execute:

declare
  l_job_id  number;
begin
  dbms_job.submit( job       => l_job_id,
                   what      => 'begin some_procedure; end;',
                   next_date => THE_DATE_YOU_WANT_IT_TO_RUN );
end;
/

May 28, 2000 Waseem -- Thanks for the question regarding
      "Animated GIFS don't animate in Develepor 2000 Forms 5.0", version Release
      2.1

      You Asked
In Develepor 2000 Forms 5.0 an image item accepts the images in
GIF format. But why don't an animated GIF animates in the image
item when same GIF image animates quite well in
explorer,netscape or in any other image viewer.

If Forms 5.0 don't supports the animated GIFs, is there any
other way to make the GIF file to animate?

I don't want to use the timer event to animate a picture because
I have no skill to build my own beautiful and eye-catching
animated images.

      and we said...
Version 89a GIF files support transparent images (also referred
as interlaced images).  Animated GIF files are comprised of
stacked images.  These image types are not supported by the
read_image_file built-in.

Support for this format is not provided with the current code
set.

Currently, I believe your only option would be to use a timer
with an iconic button.

May 29, 2000 Sriram -- Thanks for the question regarding
      "Implementing Standby database on Oracle 8.0.5", version Oracle 8.0.5

      You Asked
I need steps to implement standby database for prod db. We have
 two sun servers with solaris 2.6. Already loaded Oracle 8.0.5
Enterpirse edition. The o/s is configured similarly on two
servers.

Thanks

Sriram

      and we said...
The steps for doing that are documented in the Backup and
Recovery guide.  They are available online at:

http://technet.oracle.com/doc/server.804/a58396/ch12.htm#2421
that points directly to the documentation for this feature on
8.0

May 29, 2000 Fahim -- Thanks for the question regarding
      "Dropped Tables -- how can i get them back.", version 7.2

      You Asked
How do I get the dropped tables back while I have done commit or
not done commit yet.

      and we said...
All DDL does an implicit commit immediately PRIOR to the
operation and immediately AFTER the operation.

Once the DDL has completed -- it is impossible to simply "roll
back" and retrieve the data. If you drop a table and the command
completes -- the table is gone.

Your only options are to recover from backups or from some
export that took place before the data was dropped.  With
Oracle8 and up, you can perform a tablespace point in time
recovery to recover the tablespace that held the dropped table
to a point in time prior to the drop command being executed.

In all releases, you could always restore the database to
another machine and do a point in time recovery to a point in
time prior to the drop and then export the table and import it
into the real database.  These both assume of course you are
running in archive log mode.

May 30, 2000 Anuj -- Thanks for the question regarding "how to
      pass javascript variable value to pl/sql variable", version 4

      You Asked
Hi,
 i am facing a problem in oracle web application server. i am
creating pl sql cart. and using web packages like HTP,owa_sec.
etc well i want to know how can i pass a java script variable
holding some value to pl/sql
for example
let us say we have a
create or reeplace procedure anujname
as
begin
htp.p('<script language=javascript>')
htp.p('var mgrname= "Anuj";');
htp</script>');

Now i want to run a sql qery to form the procedure to to find
out how many employee are under "Anuj" which is hold in a
variable mgrname as metioned above.

please send me some solution if u have or have any idea to do
about . i was able to pass the sql variable to javascript
variable but vice versa is not possible

thanks and regards
Anuj Chauhan

      and we said...
Well, you must remember that javascript runs on the browser and
its PLSQL that is writing the javascript.  PLSQL isn't "passing
a variable" to javascript - PLSQL is writing some javascript
with a specific variable value.

I think you may be interested in a solution we had to dependent
drop down lists.  It was desired that when a list value changed
on the client browser, another list was updated with values
based on that (very similar to your desire to have javascript
pass plsql a variable).

see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:234614318676
for that solution.  We use 2 framesets to make this happen --
one hidden page calls plsql via a URL when needed to get the
related data.  Small demo online as well.

May 30, 2000 Reji -- Thanks for the question regarding
      "Failover/Scalability/Redundancy strategy", version 8.1.5 and 8.1.6

      You Asked
Tom:
     I have two ORACLE DBs ( 8.1.6 ) - I don't have to keep both
     DBs online for serving customers but if the active db has
     some problem or if it goes down I would like to make the
     backup db online within a very short time-frame ( I would
     say less than 15-30 minutes.  I have looked at the parallel
     server approach and I think that will be an expensive and
     complicated soln for us.  What will be your recommendation
     for this situation.

     Would you also provide me a step by step instructions for

     a matster to master replication env?  - I would like to
     test this scheme to findout how much overhead is there
     with this approach.

     TIA
     Reji

      and we said...
For an overview of some of the alternatives, see

http://www.oracle.com/oramag/oracle/00-May/o30tom.html
I would consider the new Primary/Secondary node configuration
available in 8.1.6 (see:

http://technet.oracle.com/doc/oracle8i_816/paraserv.816/a76934/chap5.htm#1023930
for info on that) a feature designed to take the complexity out
of OPS.  Its definitely something to consider and downtime (if
any) would be measured in seconds, not minutes.

Also consider standby databases (see

http://technet.oracle.com/doc/oracle8i_816/server.816/a76995/toc.htm
) as a viable method of having a failover.

As for step by step's for replication, I'll make 2 suggestions

o take a course on it, there is alot to consider with respect to
replication.

o if you cannot do that, contract to someone who has.  It is a
non-trivial technology.

The documentation covers it all as well.

May 30, 2000 Catalin -- Thanks for the question regarding
      "Array", version 6.0.5.0.2

      You Asked
Hello,

1.I want create a array like this: myArray[20,3] ( in Developer
2000 ) ,and I don't how.
2.   How I can create a dinamic array ?
Thanks
Catalin Dinu

      and we said...
We cannot directly do a NxM array, we can do a single dimension
array and an array of records (which is very much like a 2
dimensional array).  It would look like this:

PACKAGE my_pkg IS
  type myArray is table of emp%rowtype index by binary_integer;
END;

You would create that in the "Program Units" component of the
navigator.  Now, you can code plsql blocks that look like:

declare
   x   my_pkg.myArray;
begin
   x(1).ename := 'Bob';
   x(1).empno := 124;
   ....
end;
/

All plsql tables (arrays) are unconstrained with indices from
-2^31 to 2^31.  They are sparse arrays (you do not have to use
1, 2, 3 -- you could use 100, 200, 300 if you wanted).

Not sure what you mean by dynamically create an array.  If you
need an array at run time and you do not know how many columns
it might have -- you should look at RECORD_GROUPS.  They are
good for this as well.
May 30,
      2000 s. -- Thanks for the question
      regarding "The 'long and short' of tables", version 8.1.5

      You Asked
table scans (short tables)

                    Long (or conversely short)
                    tables can be defined by
                    optimizer hints coming down
                    into the row source access layer
                    of Oracle. The table must have
                    the CACHE option set.
What are short tables ?
Can you elaborate on this part of the documentation (O8
Reference) ?
If there are lots of long table scan, what are the implications?
Bad performance of queries ?

Thanks
SL

      and we said...
A "short" table is defined here as one with a high water mark
lower than:

4 blocks or 2% of the db block buffer cache for normal tables

OR

less then CACHE_SIZE_THRESHOLD for 'cache' tables in v7.x
(buffer pools in 8.x eliminate the need for this parameter. It
is intended that you would use buffer pools to cache individual
objects and control the size they consume in the cache in that
fashion)

In 8i, if you alter table cache -- it'll be considered a small
table regardless of the HWM.

Lots of long table scans does not imply bad performance
necessarily -- a 10 block table with no indexes (a lookup table
perhaps, frequently used) will make this number jump up -- at
virtually no cost.

Its a statistic that can be used in conjunction with other facts
you and you alone know about your database to make some
judgements as to how well its performing.  Full table scans are
not necessarily a "bad" thing.

May 31, 2000 Ivan -- Thanks for the question regarding "Field
      Encryption", version 8.1.6

      You Asked
How do I go about encrypting a particular field in a table?,
e.g a field that stores application passwords.

      and we said...
see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:95412348059
Even in 8.1.6, I recommend hashing the password -- not
encrypting it -- if possible.  infinitely more secure if you can
do that...
May 31, 2000 Shaun -- Thanks for the question regarding
      "Deleting Duplicate Rows from a table", version 8.0.5

      You Asked
I have a table which is comprised of the following:

ACCT_ID   CUST_ID    LOAD_DATE
-------   -------    ---------
1234       ABCD      20000101
1234       DEFG      20000201
5678       STDF      20000201
5678       TRFD      20000101
9111       ADFG      20000201
9112       ASDX      20000201

I need to delete the oldest record based upon ACCT_ID.
I need to delete ACCT_ID=1234, CUST_ID=ABCD because its
LOAD_DATE=20000101 which is older than ACCT_ID=1234,
CUST_ID=DEFG
Similarly I need to delete ACCT_ID=5678, CUST_ID=TRFD.

I need to do this for approx 20,000 records from a table which
contains 800,000 records.

      and we said...
Your question is a little ambigous.  You talk of deleting
duplicate rows but also say "I need to delete the oldest record
based upon ACCT_ID".

Duplicate record deletion would get rid of 0, 1 or more rows for
the same key -- keeping the "newest" load_date.

Deleting the oldest record by acct_id would always delete 1
record per unique acct_id.

Both are demonstrated here....

ops$tkyte@8i> select * from t;

   ACCT_ID CUST_ID                    LOAD_DATE
---------- ------------------------- ----------
      1234 ABCD                        20000101
      1234 DEFG                        20000201
      5678 STDF                        20000201
      5678 TRFD                        20000101
      9111 ADFG                        20000201
      9112 ASDX                        20000201

6 rows selected.

there is our test data...

ops$tkyte@8i> delete from t
  2   where load_date <> ( select max(load_date)
  3                          from t b
  4                         where b.acct_id = t.acct_id )
  5  /

2 rows deleted.

This delete goes after ACCT_ID's that have more then 1
occurence and delete ALL but the "newest" -- the MAX.  We get
the max(load_date) for a given acct_id and unless you have that
load_date -- you are deleted.  This will delete 0, 1 or more
rows per acct_id.

There should be an index on (acct_id,load_date)

ops$tkyte@8i> select * from t;

   ACCT_ID CUST_ID                    LOAD_DATE
---------- ------------------------- ----------
      1234 DEFG                        20000201
      5678 STDF                        20000201
      9111 ADFG                        20000201
      9112 ASDX                        20000201

ops$tkyte@8i> rollback;
Rollback complete.

Now we can try again.  This time, we pick the OLDEST record
for an ACCT_ID and delete it -- regardless of the number of
records with that ACCT_ID

ops$tkyte@8i> delete from t
  2    where load_date = ( select min(load_date)
  3                          from t b
  4                         where b.acct_id = t.acct_id )
  5  /

4 rows deleted.

ops$tkyte@8i>
ops$tkyte@8i> select * from t;

   ACCT_ID CUST_ID                    LOAD_DATE
---------- ------------------------- ----------
      1234 DEFG                        20000201
      5678 STDF                        20000201

Review &
      Followup

      Rating:
      5
Hi  March 12, 2003
Reviewer:
      Praveen  from Bangalore
Tom,

You are so simple....

warm regards

Praveen

      Rating:
      5
  September 15, 2003
Reviewer:  Ricky
      Dionisio  from San Antonio, TX USA
simple indeed.

Thanks,

May 31, 2000 Rob -- Thanks for the question regarding
      "Monitoring jobs", version 7.3.4

      You Asked
How can I tell what a job is actually doing? I'm looking for
signs of life from a SQL statement I submitted.
There don't appear to be any locks holding me up -- I'm on a new
virtually unused server (Solaris 2.7).
This server is to replace the current production one, so I
essentially copied the old set up. There are a couple of
changes to the INIT.ORA, mostly for directory differences:
compatible was 7.3.2.3.0, now 7.3.4.5.0; enqueue resources
was 16000, now 32000 (I just ran "diff" on them).
I believe I've established that there are no locks, but I can't
tell what the job IS doing.
I've tried looking at all the V$ dynamic views I can find; where
do I find a full list? The one book I'm looking
at says to select from X$KQFVI -- but it doesn't seem to exist.

You assistance would be much appreciated.

Thanks

Rob

      and we said...
To see what, if any, jobs are currently executing -- use this
view:

ops$tkyte@8i> desc dba_jobs_running
 Name                          Null?    Type
 ----------------------------- -------- --------------------
 SID                                    NUMBER
 JOB                                    NUMBER
 FAILURES                               NUMBER
 LAST_DATE                              DATE
 LAST_SEC                               VARCHAR2(8)
 THIS_DATE                              DATE
 THIS_SEC                               VARCHAR2(8)
 INSTANCE                               NUMBER

To see what, if any, sql the job is executing currently, you can
use a sqlplus script such as:

------ begin of showsql.sql --------------------------

column status format a10
set feedback off
set serveroutput on

select username, sid, serial#, process, status
from v$session
where username is not null
/

column username format a20
column sql_text format a55 word_wrapped

set serveroutput on size 1000000
declare
    x number;
begin
    for x in
    ( select username||'('||sid||','||serial#||
                ') ospid = ' ||  process ||
                ' program = ' || program username,
             to_char(LOGON_TIME,' Day HH24:MI') logon_time,
             to_char(sysdate,' Day HH24:MI') current_time,
             sql_address, LAST_CALL_ET
        from v$session
       where status = 'ACTIVE'
         and rawtohex(sql_address) <> '00'
         and username is not null order by last_call_et )
    loop
        for y in ( select max(decode(piece,0,sql_text,null)) ||
                          max(decode(piece,1,sql_text,null)) ||
                          max(decode(piece,2,sql_text,null)) ||
                          max(decode(piece,3,sql_text,null))
                               sql_text
                     from v$sqltext_with_newlines
                    where address = x.sql_address
                      and piece < 4)
        loop
            if ( y.sql_text not like '%listener.get_cmd%' and
                 y.sql_text not like '%RAWTOHEX(SQL_ADDRESS)%')
            then
                dbms_output.put_line( '--------------------' );
                dbms_output.put_line( x.username );
                dbms_output.put_line( x.logon_time || ' ' ||
                                      x.current_time||
                                      ' last et = ' ||
                                      x.LAST_CALL_ET);
                dbms_output.put_line(
                          substr( y.sql_text, 1, 250 ) );
            end if;
        end loop;
    end loop;
end;
/

column username format a15 word_wrapped
column module format a15 word_wrapped
column action format a15 word_wrapped
column client_info format a30 word_wrapped

select username||'('||sid||','||serial#||')' username,
       module,
       action,
       client_info
from v$session
where module||action||client_info is not null;

------------------------ eof --------------------------

it shows you

- who is logged on
- if they are active, what sql they are doing
- how long they've been doing it (last_call_et)

You might consider using the DBMS_APPLICATION_INFO package to
set the action, client_info, and module columns of v$session as
well -- that way, when you run showsql -- it'll show you the
values of these columns as well -- very useful for diagnosing
where a program is currently at.

Review &
      Followup

      Rating:
      4
  April 17, 2001
Reviewer:  B.G.L.
       from San Jose, C.R.

June 01, 2000 Rob -- Thanks for the question regarding "Dynamic
      Performance Views -- IO by segment", version 7.3.4

      You Asked
Is there a way to see I/O access to specific segments thru
dynamic performance views?

Thanks

      and we said...
Not to segments.  We track IO by tablespace.  Since a tablespace
may have many segments in it, all IO across these segments would
be reported.

In order to get IOs by segment, you would have to place each
segment in its own tablespace.
June
      01, 2000 Reji -- Thanks for the
      question regarding "How to purge a subset of data without generating the
      redo entries?", version 8.1.5 and 8.1.6

      You Asked
Tom:
    Is there a way that I can delete a subset of data from
    a table without generating the redo entries?

   TIA
   Reji

      and we said...
No, it is the primary purpose of the database -- to be able to
do things transactionally, to be able to recover from a failure.

Now, if the table was partitioned...
and you wanted to delete a subset of the data ...
and all of the data you wanted to delete was in a given
partition....
and the entire partition was to be deleted...

well -- that would be different.  We could get rid of that
partition without generating redo.

If the data you have to delete is a large subset of the table
(eg: the remaining data is "smallish or the same size as the
data to delete"), you could:

CREATE TABLE NEW_TABLE UNRECOVERABLE AS SELECT * FROM OLD_TABLE
<where clause to keep "good" rows>

drop table old_table;
rename new_table to old_table;
-- add indexes, grants, constraints in an unrecoverable fashion
as well...

June 01, 2000 Anshu -- Thanks for the question regarding
      "dynamically executing a function with input and output parameters",
      version Oracle 8.0.4

      You Asked
Dear Tom ,
         This problem is in continuation of my problem earlier
this day .
Actually what I wanted to say was that the function name and the
package name are in two different variables
and the parameters are also in different variables .
the package defination looks like this :-
*****************************************************
create or replace package test_function2_pkg
as

  function test_function2(ini_value out number,op_type in
varchar2) return number;
end test_function2_pkg;

********************************************************

and I want to execute this package function .I know I've to use
Dynamic sql but
I don't know where is the exact problem in the code segment
below .
That's for sure that the error is in ths code-segment itself
but don't know where !! All the variables are properly declared.
Kindly check out :-
****************************************************

     func_name1 := 'TEST_FUNCTION2';
     pkg_name1 := 'TEST_FUNCTION2_PKG';
     in_parameter := 'insert';

     v_cursorid := dbms_sql.open_cursor;
     sqlstmt:='BEGIN :ret_val :=
'||pkg_name1||'.'||func_name1||'('||ini_value||','||in_parameter|
|');
     dbms_sql.parse(v_cursorid , sqlstmt , dbms_sql.native);
     dbms_sql.bind_variable(v_cursorid,':ret_val',ret_value,50);

     v_dummy := dbms_sql.execute(v_cursorid);

     dbms_sql.variable_value(v_cursorid,':ret_value',ret_value);

     dbms_sql.close_cursor(v_cursorid);
*************************************************************

the error I'm getting is :-
********************************************************
PLS-00103: Encountered the symbol "INSERT" when expecting one of
the following:
( - + mod not null others <an identifier>
<a double-quoted delimited-identifier> <a bind variable> avg
count current exists max min prior sql stddev sum variance
cast <a string literal with character set specification>
<a number> <a single-quoted SQL string>
The symbol "null was inserted before "INSERT" to continue.
ORA-06512: at "SYS.DBMS_SYS_SQL", line 491
ORA-06512: at "SYS.DBMS_SQL", line 32
ORA-06512: at line 52
*************************************************

line number 32  is a commented line !!!!
line no 52 is the dbms_sql.parse statement .
there is no line such as 491 ! 'coz the code itself is of around
60 lines .

I hope that U can sort it out .
Thanx for the previous reply
Regards
Anshu

      and we said...
You need to use bind variables for the inputs and outputs.
Right now it is because you are glueing in character string
constants to the statement so the block of plsql you generated
looks like:

BEGIN
  :ret_val := test_function2_pkg.test_function2( ,insert );
end;

which is not a valid block of code.  Here is a fully functional
example based on your example above:

ops$tkyte@dev8i> create or replace package test_function2_pkg
  2  as
  3     function test_function2( ini_value out number,
  4                              op_type in varchar2 )
  5     return number;
  6  end test_function2_pkg;
  7  /

Package created.

ops$tkyte@dev8i>
ops$tkyte@dev8i> create or replace package body
test_function2_pkg
  2  as
  3     function test_function2( ini_value out number,
  4                              op_type in varchar2 )
  5     return number
  6     as
  7     begin
  8        dbms_output.put_line( 'In parameter was "' ||
  9                               op_type || '"' );
 10        ini_value := 55;
 11        return 123;
 12     end;
 13
 14  end test_function2_pkg;
 15  /

Package body created.

ops$tkyte@dev8i>
ops$tkyte@dev8i> declare
  2     func_name1   varchar2(25) := 'test_function2';
  3     pkg_name1    varchar2(25) := 'test_function2_pkg';
  4     in_parameter varchar2(25) := 'insert';
  5     l_theCursor     integer default dbms_sql.open_cursor;
  6     l_rowsprocessed number  default 0;
  7     l_ret_val     varchar2(4000);
  8     l_op_type     varchar2(4000);
  9
 10  begin
 11      dbms_sql.parse(l_theCursor,
 12                    'begin
 13                       :ret_val := ' ||
 14                           pkg_name1 || '.' || func_name1 ||
 15                       '( ini_value => :x1, op_type => :x2 );
 16                     end;',
 17                     dbms_sql.native );
 18
 19      dbms_sql.bind_variable( l_theCursor, ':x1',
 20                              l_op_type,    4000 );
 21      dbms_sql.bind_variable( l_theCursor, ':x2',
 22                              in_parameter, 25 );
 23      dbms_sql.bind_variable( l_theCursor, ':ret_val',
 24                              l_ret_val   , 4000 );
 25
 26      l_rowsprocessed := dbms_sql.execute(l_theCursor);
 27
 28      dbms_sql.variable_value( l_theCursor,
 29                              ':ret_val', l_ret_val );
 30      dbms_sql.variable_value( l_theCursor,
 31                              ':x1', l_op_type );
 32
 33     dbms_output.put_line( 'Return value ' || l_ret_val );
 34     dbms_output.put_line('Out parameter value '||l_op_type);
 35  end;
 36  /
In parameter was "insert"
Return value 123
Out parameter value 55

PL/SQL procedure successfully completed.

June 01, 2000 Matt -- Thanks for the question regarding
      "SQL-Loader loading a ever increasing log file", version 8.1.6

      You Asked
Hi,

Is it possible to load into oracle 8.1.6 a log file
in a cvs file format, that is gaining in quantity all
the time ?

The file is a log file containing the following fields

data_time, item1, item2, item3, item4

Each item may have a char of '-', '/', '@', '[' and ']'

The date_time keeps the values unique ie

12-May-00

and when added to the database an id number is associated
to each record.

If you can help it would be great.

Regards

Matt

      and we said...
In the past what I've done (i was loading log files from a
webserver) is (this is unix)

- start with an empty log in a SOURCE directory (active log) and
an empty log in a LOAD/TMP directory (what we will actually
load)

- set an environment variable x such as:
  set x = `cat LOAD/logfile | wc -l`

  that puts into x the number of lines in the last log file
  we loaded.  when we start -- this is zero.  As we go on,
  it will not be zero.

- now, copy SOURCE/logfile LOAD/logfile

- sqlldr ... skip=$x .... data=LOAD/logfile

Now, the next time this process runs, it'll count the number of
records in the logfile from the last time we loaded and it'll
skip those (they've been loaded already).

Just remember, if you reset the SOURCE/logfile you need to reset
the LOAD/logfile.
June 01, 2000
      Joel -- Thanks for the question regarding
      "Uploading a file from OAS", version 4.0.7.0

      You Asked
Tom,

I need to upload a file into a blob field.

We are running Oracle 8.0.5 database on Solaris.

I can't use the  OWAREPL cartridge that you have made available
(for various reasons).  The primary reason is that our dba can't

get it up and running.  I'm not sure how this is suppposed to
be set up.  The cartridge never starts up. I have gone over this
with a fine tooth comb, carefully following all the instructions
you gave for setting it up with no success.

At this point, I have a procedure that gets the image from the
table and returns it to the browser for display (thanks to a
reply you provide in one of the newsgroups, which pointed me in
the right direction).

I also can insert into the OWS_CONTENT table using the built-ins

of OAS.  But I can't display the images in the OWS_CONTENT
table,
mainly because I really don't understand the structure of the
OWS_ tables and their (apparent) relationship to the OWA_CONTENT
package.

So, essentially, I have 2 half solutions, which unfortunately
don't make a whole.

I need to create a procedure that will take the file (an image),
via browser, and insert it into my image table,
which has the following structure:

img_id  varchar2(100)
img_content  blob

All the examples I have seen for inserting files into
LOBs use BFILEs which implies that the files are on the server
(right???).  The reality for me is that the files will come from
various client machines.

Maybe, with a better understanding of how I would get the images
from OWS_CONTENT to the browser, I wouldn't need a separate
table
to store all these files??

I am totally lost.  Any ideas???

Thanks again for your help.

Joel

      and we said...
This is support note <Note:77573.1> that should get you going
with the native OAS upload and download facility.

PURPOSE
=======

This document explains how to upload and download images from
the database using Oracle Application Server 4.x.

SCOPE & APPLICATION
===================

The information in this document is intended for users who want
to upload images or files and store them into the database for
future downloads.

Oracle Application Server lets you upload image files and other
files into your database. These files can be downloaded to your
browser through content services provided by the PL/SQL toolkit.
When you upload the files into database it stores the file in
websys.owa_content table. Other details like the file name are
stored in websys.ows_object table. For simple upload and
download of files, you do not have to access these tables
directly.

Ensure that when you install the PL/SQL toolkit all the
owa_content packages are installed without any errors. If you
have any doubts, there is no harm in reinstalling the PL/SQL
toolkit and reconfirming.

Follow these steps to upload and download images or files into
the database:

1.  Create a directory called static. The path for this
directory can be
    D:\static

2.  Cut and copy the following html text into a file called
upload.htm.

    <html>
    <head>
    <title>This form is used for uploading files into
database</title>
    Choose the file you want to upload into your database
    </head>
    <body>
    <p>
    <FORM
    enctype="multipart/form-data"
    action="/file/websys.write_info"
    method="POST">
    <p>File to upload:
    <INPUT type="file" name="file"><br>
    <p>
    <INPUT type="submit">
    </body>
    </html>

3.  Add the following entry in the listener directory
configuration.

        File-System Directory   Flag       Virtual Directory

        D:\static\              NR         /static/

    Click on Apply.

4.  In OAS create a DAD, an application, and a cartridge. For
information on how to create an application and a cartridge,
refer to the tutorial in online documentation. Let the virtual
path be /file.

5.  Cut and copy the following text into a file called
write_info.sql:

    create or replace procedure write_info (file in varchar2) as
     begin
        htp.htmlopen;
        htp.headopen;
        htp.title('File Uploaded');
        htp.headclose;
        htp.bodyopen;
        htp.header(1, 'Upload Status');
        htp.print('Uploaded ' || file || ' successfully');
        htp.bodyclose;
        htp.htmlclose;
     end;
    /

6.  Cut and copy the following text into a file called
down_form.sql:

    create or replace PROCEDURE down_form IS
    list_val varchar2(100);
       BEGIN
         htp.htmlOpen;
         htp.headOpen;
         htp.title('Adding New Employee');
         htp.headClose;
         htp.bodyOpen;
         htp.centerOpen;
         htp.header(1,'This Form Can be Used To Download Files
from database');
         htp.para;
         htp.img(curl=> '/ows-img/ows.gif');
         htp.centerClose;
         htp.para;

htp.formOpen(owa_util.get_owa_service_path||'websys.down');
         htp.para;
         htp.p('File Name ');
         htp.formSelectOpen('file_val','Select the file you want
to download ');
       Declare
         CURSOR load_list_cur IS
         select name from ows_object;
       begin
       OPEN load_list_cur;
       LOOP
          FETCH load_list_cur into list_val;
             EXIT WHEN load_list_cur%NOTFOUND;
             htp.formSelectOption(list_val);
             htp.nl;
       END LOOP;
       close load_list_cur;
       end;
       htp.formSelectClose;
       htp.para;
       htp.para;
       htp.formSubmit;
       htp.formReset;
       htp.formClose;
       htp.bodyClose;
       htp.htmlClose;
       END down_form;
       /

7.  Cut and copy the following text into a file called down.sql:

    create or replace PROCEDURE down(file_val VARCHAR2) IS
       l_ext VARCHAR2(100) := NULL;
       l_mime_type   VARCHAR2(100) := NULL;
       BEGIN
       l_ext := substr(file_val, instr(file_val, '.', -1));
       IF UPPER(l_ext) = 'PDF' THEN
          l_mime_type := 'application/acrobat';
       ELSIF UPPER(l_ext) = 'GIF' THEN
          l_mime_type := 'image/gif';
       END IF;
       IF l_mime_type IS NOT NULL THEN
          owa_util.mime_header(l_mime_type);
       END IF;
          htp.download_file(file_val);
       END down;
       /

8.  Now log into SQL*Plus:
    userid  : websys
    password: manager

    compile the 3 sql files which you created using the
following command
    @write_info.sql
    @down_form.sql
    @down.sql

    Grant ows_standard_role to the DAD_USER by executing the
following command.

    grant role ows_statndard_role to <DAD USER>
    grant execute on websys.owa_conentent to <DAD USER>
    grant execute on webys.ows_cs to <DAD USER>

    Grant execute privileges of all the procedures you created
to the DAD USER by
    using the following commands.

    grant execute on write_info to <DAD USER>
    grant execute on down_form to <DAD USER>
    grant execute on down to <DAD USER>

9.  Reload your WebServer.

10. From your browser access the following URL:

http://HostName.DomainName:Port/static/upload.htm
    Select the file you want to upload. Click on Submit. You
should get a message file uploaded successfully. At this point
the file its uploaded into websys.owa_contetnt table and the
other information is stored in websys.ows_object table. You can
verify the upload by doing a select query.

11. From your browser access the following URL:

http://HostName.DomainName:Port/file/websys.down_form

    This lists all the files you have uploaded until now. Select
the file you want to download. Click on Submit. You would see
that the depending on the file you downloaded, it would show you
the contents. If it is an image file, then the image would
display on your browser.

Note: The following patches are needed for OAS 4.0.8.1 running
on Windows NT, to upload or download files to your database.
Reference <Note:1083522.6>.

Contact Oracle Support and request patches for the following
bugs:

<Bug:1059171>
<Bug:1146585>
<Bug:1006761>

Review &
      Followup

      Rating:
      2
Nikunj  July 05, 2001
Reviewer:
      Nikunj  from India
hi tom,

i have Oracle Application Server Release  4.0.8.1.0 - Enterprise Edition &
Oracle 8.1.6 EE.

thanks. but i need it in seprate table.

i have table as below

form_data table

sub_date date;
custcode  number(10);
form_sub  blob;

now i need one procedure which show an client user for upload your form in this
he select his word/excel file & click on submit, we insert that data into
form_data table. (store in database)

now at our end we want to download that form into our directory.(we retrive from
database)

regards,
nikunj.

June 01, 2000 Reji -- Thanks for the question regarding
      "References between two different database's tables", version 8.1.5 &
      8.1.6

      You Asked
Tom:
     I have two different Oracle DBs.  I wanted to link
     one table from DB1 to another table in DB2.  How do
     I specify the references - When I create the tables
     I want to specify the REFERENCES in the table definition.

     When I do join, I think I have to create a db link and
     I can use that to link the tables.

     Currently I have both tables in the same db but I have
     to split the DB for several reasons but I have to link
     few tables.

     Please advise.

     TIA
     Reji

      and we said...
Declaritive integrity using the REFERENCEs keyword cannot be
accomplished with physically segregated databases.  You can only
reference a table that is in the same physical database.

You could use triggers and roll your own, however, at that point
the two databases become so dependent on each other that it
really makes more sense to consolidate -- rather then split
apart.

Another possible alternative would be to use replication --
either read only replication or bi-directional replication, on
the table you need to reference (the one with the primary key).
The database with the child table could reference this copy of
the real data.  This would allow both databases to work
independent of each other (in the event one is not available,
the other can continue) and would increase performance all
around (no distributed joins).

Consider using read only snapshots on some of this reference
data.
June 01, 2000 Amit -- Thanks for the question regarding
      "Extents sizing strategy", version 8.0.6

      You Asked
Hi Tom.

In the past I have always tried to reduce the number of
extents in databases to minimum.

In one of your answers, you supplied a link to this article:
"Sizing extents for Performance" (
http://www.kevinloney.com/free/extperf.doc
.
The article recommends and shows benefits of having uniformly
sized extents,
assuming database files are on striped media, and setting
db_multi_block_read_count
correctly.

I am considering implementing a method for simplifying space
management
for an OLTP system.

The method has the following rules for segments (except
temporary, rollback segments):

1- All segments which will are known to be "small" (for example
it is known
   they will never be larger than 32M) will be put on one
tablespace.

2- All the other segments will be created on a different
tablespace, with
   the following properties: INITIAL 64M NEXT 64M PCTINCREASE 0
.

3- All datafiles will be sized 2G .

Questions:

1- Say there are large hash clusters on the "large" tablespace,
with hundreds
   or even thousands of extents, each 64M; When accessing a row
in a table
   on a hash cluster, Oracle has to determine on which block
(which extent) the
   hash address points to. For this to happen, in the worst case
it will need
   to traverse the clusters' extent list to locate the address.
Is this impact
   trivial enough to be ignored ? (it is not mentioned in the
article).

2- Is there any rule of thumb to determine
   what is an "exaggerated" amount of extents (hundreds /
thousands /... ) ?
   or an "exaggerated" rate of extent allocations per segment
per time period ?

Thanks,
Amit.

      and we said...
1)  It does not traverse the clusters extent list but rather
looks at a fixed size hash table (sized by you at table create
time).

<quote source=concepts guide>

Allocation of Space for a Hash Cluster

As with other types of segments, the allocation of extents
during the creation of a hash cluster is controlled by the
INITIAL, NEXT, and MINEXTENTS parameters of the STORAGE clause.
However, with hash clusters, an initial portion of space,
called the hash table, is allocated at creation so that all hash
keys of the cluster can be mapped, with the total space equal to
SIZE * HASHKEYS. Therefore, initial allocation of space for a
hash cluster is also dependent on the values of SIZE and
HASHKEYS. The larger of (SIZE*HASHKEYS) and that specified by
the STORAGE clause (INITIAL, NEXT, and so on) is used
....
</quote>

So, its really a hash into this hash table -- not into the
extent map of the table itself.

2) I would myself attempt to avoid if possible thousands of
extents but hundreds -- thats something to consider. You should
read up on locally managed tablespace (see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:240014552942
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:228413960506
for some background) and uniform sizing.  Its great.
June 01, 2000 Madhu -- Thanks for the question regarding
      "Oracle Parallel Server -- New 8.1.6 Basic High Availability
      Configuration", version 8.1.6

      You Asked
In your article Oracle Availability Options  you mentioned
..."... (Oracle8i Release 8.1.6 has a special two-node-cluster
mode of OPS. If you use this mode, 100 percent of the
performance issues are nonissues. Both nodes are used to read
data, but only one node is used to write data. The second node
takes over for the first node in the event of a failure and
starts writing as well.) "

Is this same as the ORACLE PARALLEL FAILSAFE ? (which is
currently available only on HP clusters)

Where do we get specific details of this special 2 node
implementation ? Any PDF files or technical white papers ?

      and we said...
This is known as "Basic High Availability Configuration" or
"Primary and Secondary Instances".  See

http://technet.oracle.com/doc/oracle8i_816/paraserv.816/a76968/pshavdtl.htm#10876
and

http://technet.oracle.com/doc/oracle8i_816/paraserv.816/a76934/chap5.htm#1023930
for more info.  It is not the Failsafe offering.  The failsafe I
am aware of is Oracle Fail Safe.  It makes it easy to deploy
highly available solutions on Microsoft Windows NT clusters.
Oracle Fail Safe 2.1.3 (and earlier releases) help you to
configure highly available single-instance (Oracle7 and Oracle8)
databases.  Its on NT, not HP, clusters tho.

See the links above for info on this new feature.
June 01, 2000 tejal -- Thanks for the question regarding
      "Migratioin to 8i on digital unix from 7.3.2", version 7.3.2

      You Asked
Tom,
My organization is planning to migrate from the present version
to 8i.So i need some tips regarding the migration as well as
possible problems that might occur at that stage.If possible
suggest me some imp documentation reg that.
Thanks
Tejal

      and we said...
Well, the document that comes to mind would be the Oracle
Migration guide.

You can migrate the database (an in place migration -- no
export/import) or export import it.

See

http://technet.oracle.com/doc/oracle8i_816/server.816/a76957/toc.htm
It outlines what to expect and goes into detail as to how to do
it...
June 01, 2000 Dennis -- Thanks for the question regarding
      "Database Links and Test Databases", version 7.3 & 8i

      You Asked
Any advice on setting up test environments?  Any articles out
there I can look at?  We recently set up a more stable test
environment with one machine per Oracle version and I am looking
for advice.  Potential pitfalls?

For now, we simply maintain our test databases by appying cold
backups when necessary.  Can I change a SID's when recreating an
instance in the test environment. One problem I have is creating
database links between the test and production servers when
necessary.

Thanks.

      and we said...
I am not aware of any white papers on this subject.

I don't see any pitfalls with 1 version / machine.  I run many
releases on the same machine, running 1 version / machine would
be ideal.

Applying the cold backup is a great way to copy an instance (if
you have the flexibility of doing that cold backup).  A hot
backup + restore would do it as well.

If you have problems creating links between test and production
-- its most likely due to GLOBAL NAMES.  You don't need to chang
the sid to fix this, just "alter database rename global_name to
new_name"

Here is how to change a database name and sid of an instance:

PURPOSE
  This entry describes how to find and change the "db_name" for
a database, or the ORACLE_SID for an instance, without
recreating the database.

To find the current DB_NAME and ORACLE_SID:
===========================================

Query the views v$database and v$thread.

    V$DATABASE gives DB_NAME
    V$THREAD gives ORACLE_SID

If ORACLE_SID = DB_SID and db_name = DBNAME:

To find the current value of ORACLE_SID:

    SVRMGR> select instance from v$thread;

    INSTANCE
    ----------------
    DB_SID

To find the current value of DB_NAME:

    SVRMGR> select name from v$database;

    NAME
    ---------
    DBNAME

Modifying a database to run under a new ORACLE_SID:
===================================================

1.  Shutdown the instance

2.  Backup all control, redo, and data files.

3.  Go through the .profile, .cshrc, .login, oratab,
tnsnames.ora,  (for SQL*Net version 2), and redefine the
ORACLE_SID environment  variable to a new value.

    For example, search through disks and do a grep ORACLE_SID *

4.  Change locations to the "dbs" directory

       % cd $ORACLE_HOME/dbs

    and rename the following files:

    o   init<sid>.ora  (or use pfile to point to the init
        file.)
    o   control file(s). This is optional if you do not rename
        any of the controlfiles, and the control_files parameter

        is used.

        The "control_files" parameter is set in the
        "init<SID>.ora" file or in a file it references with the

        ifile parameter.  Make sure that the control_files
        parameter does not point to old
        file names, if you have renamed them.
    o   "crdb<sid>.sql" & "crdb2<sid>.sql",  This is optional.
        These are only used at database creation.

5.  Change locations to the "rdbms/admin" directory

       % cd $ORACLE_HOME/rdbms/admin

    and rename the file:

    o   startup<sid>.sql.  This is optional.  On some platforms,
 this file may be in the "$ORACLE_HOME/rdbms/install" directory.
Make sure that the contents of this file do not reference old
init<SID>.ora files that have been renamed.  This file
simplifies the "startup exclusive" process to start your
database.

6.  To rename the database files and redo log files if need be.

7.  Change the ORACLE_SID environment variable to the new value.

8.  Check in the "$ORACLE_HOME/dbs" directory to see if the
password      file has been enabled.  If enabled, the file
"orapw<OLD_SID>" will  exist and a new password file for the new
SID must be created (renaming the old file will not work).  If
"orapw<OLD_SID>" does not     exist, skip to step 9.  To create
a new password file, issue  the following command as oracle
owner:

       orapwd file=orapw<NEWSID> password=?? entries=<number of
users to be granted permission to start the database instance>

9.  Start up the database and verify that it works.  Once you
have done  this, shutdown the database and take a final backup
of all control,  redo, and data files.

10. When the instance is started, the control file is updated
with the  current ORACLE_SID.

Changing the "db_name" for a Database:
======================================

1.  Login to Server Manager

        % svrmgrl
        SVRMGR> connect internal

2.  Type

        SVRMGR> alter system switch logfile;

    to force a checkpoint.

3.  Type

        SVRMGR> alter database backup controlfile to trace
resetlogs;

    This will create a trace file containing the "CREATE
CONTROLFILE" command to recreate the controlfile in its current
form.

4.  Shutdown the database and exit SVRMGR

        SVRMGR> shutdown

        SVRMGR> exit

    The database must be shutdown with SHUTDOWN NORMAL or
SHUTDOWN IMMEDIATE. It must not be shutdown abnormally using
SHUTDOWN ABORT.

5.  Change locations to the directory where your trace files are
located.  They are usually in the "$ORACLE_HOME/rdbms/log"
directory.  If  "user_dump_dest" is set in the "init<SID>.ora"
file, then go to the  directory listed in the "user_dump_dest"
variable.  The trace file will have the form "ora_NNNN.trc with
NNNN being a number.

6.  Get the "CREATE CONTROLFILE" command from the trace file and
put it in a  new file called something like "ccf.sql".

7.  Edit the "ccf.sql" file

    FROM: CREATE CONTROLFILE REUSE DATABASE "olddbname"
NORESETLOGS ...
      TO: CREATE CONTROLFILE set DATABASE "newdbname"  RESETLOGS
...

8.  Save and exit the "ccf.sql" file

9.  Rename the old control files for backup purposes and so that
they do
    not exist when creating the new ones.

10. Edit the "init<SID>.ora" file so that db_name="newdb_name" .

11. Login to Server Manager

        % svrmgrl
        SVRMGR> connect internal

12. Run the "ccf.sql" script

        SVRMGR> @ccf

    This will issue a startup nomount, and then recreate the
controlfile.

    If, at this point, you are prompted for an archived
redologfile, the database was not shutdown normally as specified
in step 4 and so, during recovery it is asking for the redo in
the current logfile. It may be possible to open the database
after applying the current logfile. BUT this is not guaranteed.
If, after applying the current logfile, the database will not
open then it is highly likely that the operation must be
restarted having shutdown the database normally.

    To apply the necessary redo, you need to check the online
logfiles and apply the one with the same sequence number as
reported in the message. This usually is the logfile with
status=CURRENT.

    To find a list of the online logfiles:

    SVRMGR> select group#, seq#, status from v$log;
    GROUP#     SEQUENCE#   STATUS
    ---------- ---------   ----------------
             1 123         CURRENT     <== this redo needs to be
applied
             2 124         INACTIVE
             3 125         INACTIVE
             4 126         INACTIVE
             5 127         INACTIVE
             6 128         INACTIVE
             7 129         INACTIVE

    7 rows selected.

    SVRMGR> select member
              from v$logfile
             where GROUP# = 1;

    Member
    ------------------------------------
    /u02/oradata/V815/redoV81501.log

    The last command in ccf.sql should be:

    SVRMGR> alter database open resetlogs;

13. Make sure the database is working.

14. Shutdown and backup the database.

June 02, 2000 Ananth -- Thanks for the question regarding "Date
      function -- convert DDDYY into a date", version 8.0.5.1

      You Asked
Is there a function which returns the date of the year if the
input to it
is the days of the year.

for eg:
if the input is 03100, the function should return 31-jan-2000
here teh first three characters is the day of te year , the last
two digits
is the year.
another example  05000 should return 19-feb-2000.

thanks for your help.

ananth

      and we said...
We can do this with a date format mask.  Simply:

select to_date('03199','DDDRR') from dual;

and

select to_date('05000','DDDRR') from dual;

June 02, 2000 ted -- Thanks for the question regarding "alter
      column definition", version 8.1.5

      You Asked
thomas,
I have a table with column c1 varchar2(5) default 'M' null.
how do i alter it so c1 would have definition of no default.
I tried alter table modify c1 default null or default '' and
found data_default in user_tab_columns contain value of literal
'null' and '' instead of null.

thanks in advance
ted chyn

      and we said...
It is a trick question.  You want to know how to remove a
default -- but you cannot.  All you can do is set the default
value be what would be placed there in the event there is no
default (NULL).

Also, you say "contain value of literal 'null' and '' instead of
null" which is technically not accurate.  The data_default
contains the word NULL not 'NULL' -- it does not have a literal,
it has the keyword NULL.   The data_default for a column is some
SQL Expression that will (in effect) be select'ed from DUAL at
runtime.  Consider this example:

ops$tkyte@8i> create table t
  2  ( a int,
  3    x int         default 1,
  4    y varchar2(5) default 'M',
  5    z date        default sysdate
  6  )
  7  /
Table created.

ops$tkyte@8i>
ops$tkyte@8i> select column_name, data_default
  2    from user_tab_columns
  3   where table_name = 'T';

COLUMN_NAME                    DATA_DEFAU
------------------------------ ----------
A
X                              1
Y                              'M'
Z                              sysdate

See how sysdate is in there -- we will "select sysdate from
dual" at runtime to supply a default for this column -- we won't
put the word SYSDATE into it

ops$tkyte@8i> insert into t (a) values (1);
1 row created.

ops$tkyte@8i> alter table t modify x default null;
Table altered.

ops$tkyte@8i> alter table t modify y default null;
Table altered.

ops$tkyte@8i> alter table t modify z default null;
Table altered.

ops$tkyte@8i> select column_name, data_default
  2    from user_tab_columns
  3   where table_name = 'T';

COLUMN_NAME                    DATA_DEFAU
------------------------------ ----------
A
X                              null
Y                              null
Z                              null

Now, each of the columns has a default still (cannot get rid
of it) and that default is now "select NULL from dual" -- which
is the same as not having a default.  It will not put the word
'NULL' into the value but rather the value NULL into it.

ops$tkyte@8i> insert into t (a) values (2);

1 row created.

ops$tkyte@8i>
ops$tkyte@8i> select * from t;

         A          X Y     Z
---------- ---------- ----- ---------
         1          1 M     02-JUN-00
         2

See -- they are all null...
Review &
      Followup

      Rating:
      5
  November 06, 2002
Reviewer:  A
      Reader  from UK
Fantastic explanation.

June 02, 2000 lalitha -- Thanks for the question regarding "How
      to build a query with two counts", version version 8.1.5

      You Asked
Hi Mr Tom,
I have a table with two columns number and date.I need a result
set from an sql query which returns three columns ,the first
column is the number
the second column is the count of that between a particular date
range  and
the third column is the count of that number again between
another date range.
For e.g if TEST table has two columns with numb and num_date and
values
 1 01-jan-00
 1 02-jan-00
 2 01-jan-00
 2 06-jan-00

then the result of an sql query should be

 numb  jan1-jan2  jan3-jan7
  1     2           0
  2     1           1

Thanks,
Lalitha

      and we said...
First, I'll show you the 8.1.6 syntax (just to see how much
easier this will be....) and then 2 alternative syntaxes for
8.1.5 (the last one works in all releases but is a little hard
to read)....

The table I used is:

SQL> create table t ( x int, y date );
Table created.

SQL> insert into t values ( 1,'01-jan-00' );
SQL> insert into t values ( 1,'02-jan-00' );
SQL> insert into t values ( 2,'01-jan-00' );
SQL> insert into t values ( 2,'06-jan-00' );

SQL> insert into t values ( 3,'31-dec-1999' );
SQL> insert into t values ( 3,'01-jan-00' );
SQL> insert into t values ( 3,'02-jan-00' );
SQL> insert into t values ( 3,'03-jan-00' );
SQL> insert into t values ( 3,'04-jan-00' );
SQL> insert into t values ( 3,'05-jan-00' );
SQL> insert into t values ( 3,'06-jan-00' );
SQL> insert into t values ( 3,'07-jan-00' );
SQL> insert into t values ( 3,'08-jan-00' );
SQL> insert into t values ( 3,'09-jan-00' );

I wanted all the boundary values to be present in the test --
dec 31'st is out of range as is 8 and 9 Jan.  Jan 2 and 3 are
boundary conditions as well...
SQL> select x,
  2         sum(case
  3             when y between '01-jan-00' and '02-jan-00'
  4               then 1
  5               else 0
  6             end ) jan1_jan2,
  7         sum(case
  8             when y between '03-jan-00' and '07-jan-00'
  9               then 1
 10               else 0
 11             end ) jan3_jan7
 12   from t
 13  group by x
 14  /

The new case statment in 8.1.6 makes doing this sort of logic
pretty easy...

         X  JAN1_JAN2  JAN3_JAN7
---------- ---------- ----------
         1          2          0
         2          1          1
         3          2          5

In 8.1.5, we can use the trick of "selecting a select" which
is almost as easy as the above and would look like this:

SQL> select x,
  2        ( select count(*)
  3            from t b
  4           where b.x = t.x
  5             and b.y between '01-jan-00'
  6                         and '02-jan-00' ) jan1_jan2,
  7        ( select count(*)
  8            from t b
  9           where b.x = t.x
 10             and b.y between '03-jan-00'
 11                         and '07-jan-00' ) jan3_jan7
 12   from (select distinct x
 13           from t ) t
 14  /

         X  JAN1_JAN2  JAN3_JAN7
---------- ---------- ----------
         1          2          0
         2          1          1
         3          2          5

The above, while it works, will definitely not be as efficient
as the CASE statement will be.  The above will have to create a
set of distinct X's and then for each one of them run 2
subqueries.  The case statement will do all of this with 1 scan
instead of 1 scan + N * 2 queries.  So, how can we do the case
statement today in 8.1.5 (and before...)

SQL> select x,
  2         sum( decode( sign( y-to_date('03-jan-00') ),
  3                 -1, decode( sign(y-to_date('01-jan-00')),
  4                     -1, 0, 1 ), 0 )) jan1_jan2,
  5         sum(decode( sign( y-to_date('08-jan-00') ),
  6                 -1, decode( sign(y-to_date('03-jan-00')),
  7                     -1, 0, 1 ), 0 )) jan3_jan7
  8    from t
  9   group by x
 10  /

Decode can do it -- its a little obscure but it works.  We
have to convert:
  if y between A and B into:

  if y < B
     if Y < A
         return 0
     else
         return 1
     end if;
  else
     return 0
  end if

Thats what that decode does.

         X  JAN1_JAN2  JAN3_JAN7
---------- ---------- ----------
         1          2          0
         2          1          1
         3          2          5

Review &
      Followup

      Rating: 4
select to
      produce spread of ranges in columns  April 27, 2001

Reviewer:  Keith Hollins  from Leatherhead, Surrey,
      England
I wanted to produce totals and counts of our invoices in ranges of amounts. I
was not aware of select from select or case statement.

A search of 'range' and 'decode' in the archives led me quickly to the answer.
(I was fed up of working out how to decode)

      Rating:
      5
  June 04, 2002
Reviewer:  Sridevi
      Moparthi  from St Louis, MO USA

June 02, 2000 gabriel -- Thanks for the question regarding
      "plsql -- is there a byte size limit?", version 8i

      You Asked
is there a byte size or line size limit to a source code?
I have a package that contains ~1800 lines.  This compiles and
works great.  Now, that I'm ready for production, I added
comments like:
/*

*================================================================

 *   Type        : Function
 *   Name        : QUARTER
 *   Params IN        : A string value of 'BEGINNING' or 'END'
 *   Returns        : Date
 *   Description    :
 *            As function is called a date values is returned.
 *            Basically, the function returns the begining or
 *            the ending date of any quarter.

*================================================================

 */

Now that I'm trying to compile, an error message appears saying
it detected and eof at line 1857.  In this line, there are
pieces of code yet to be compiled.

Any help would be great...gabriel

      and we said...
Various tools have limits but in general -- the size of plsql
code is limited by its complexity, not its over all size (its
the depth of the parse tree and number of nodes it generates,
not the size of the code that counts.

For example, I ran a script:

set echo off
set feedback off
set termout off

spool test2.sql

prompt create or replace package foo
prompt as
begin
   for i in 1 .. 2000 loop
        dbms_output.put_line( 'x'||i ||
          ' number default 999999999999999999999999999999' );
   end loop;
end;
/
prompt end; /**/
prompt /

spool off
host ls -l test2.sql

It generated a package with 2,000 lines of code and was:

-rw-r--r--   1 tkyte      102938 Jun  2 09:34 test2.sql

about 100k in size.  I submitted this script through SQLPlus and
it generated just fine.

In all probability -- you added an unclosed comment somewhere in
the code and it is the cause of the error.  Look backwards from
line 1857 for the previous comment and verify it is complete.

(i tested this with upto 5,000 lines of plsql code, 258,938
bytes.  It compiled as well.)

June 02, 2000 Michael -- Thanks for the question regarding
      "Archiving Redologs - who/what does the archiving", version 8.0.5

      You Asked
Tom,
   This is probablly a very stupid question but when running
 in ARCHIVELOGMODE who does the Archiving?  Oracle or the
Operating System.  The reason I ask is that under Operating
System and Transaction monitor I am currently using (VME and TPMS)
it is an Application VM which takes of that? and at the moment
I am still feeling my way in the Oracle world and this is
puzzling me!

Regards,
       Michael Horrocks

      and we said...
There is an Oracle process called ARCH that may perform this operation.  It
is optional.  You may opt to perform the archiving in some other manner if you
desire (but you must set this up).

See

http://technet.oracle.com/doc/server.804/a58227/ch_intro.htm#3447
for a description of the ARCH process.
June 02, 2000 Ravinder -- Thanks for the question regarding
      "Query Tuning -- what guides can I read.", version 8.1.5

      You Asked
Hi Tom,

If a query is taking a long time, how can we find out that which
particular index is slowing down the process.

Ravi

      and we said...
You want to learn about using EXPLAIN PLAN

http://technet.oracle.com/doc/server.815/a67775/ch13_exp.htm#822
and SQL_TRACE + TKPROF

http://technet.oracle.com/doc/server.815/a67775/ch14_str.htm#1018
they will help you diagnose what it is a query is doing.  From
there you can tune it.

June 02, 2000 Prakash -- Thanks for the question regarding
      "Retriving Data dynamically ", version 8.0

      You Asked
Hi,

Can you tell me How Can I change the data source name within a
Procedure . Without using DBMS_SQL package.

(i.e. I want to pass the table/Database link name  as an
argument and want to return the Pl/SQL table or REF CURSOR ) So
that i can dynamically retrive Data.

(This i want to implemented at Both Databasde package and
Application(Forms 5.0) level )

      and we said...
This is not possible until you have Oracle8i when you can code:

...
  open ref_cursor_variable for
     'select * from ' || p_tname;
...

prior to that, ref cursors cannot be dynamic in nature.
Review &
      Followup

      Rating:
      5
  August 01, 2002
Reviewer:
      A reader


Subject | Article | Last Updated (East coast time)
Oracle 8 EE on NT 4 - Reports Runtime Problem - MAX OPEN CURSORS | article only | Jun 03, 2000 01:00 pm
inserting text document in a long datatype field | article only | Jun 03, 2000 01:07 pm
SQL query | article only | Jun 03, 2000 01:32 pm
Regarding SQLERROR NUMBER and DML thro Views | article only | Jun 04, 2000 09:40 am
Error during executing a procedure for accessing directories that are permitted for PL/SQL file I/O. | article only | Jun 04, 2000 09:43 am
Unix script not working | article only | Jun 04, 2000 10:15 am
forms 5 | article only | Jun 04, 2000 10:46 am
Oracle 8 Object option and user define data types -- What to read | article only | Jun 04, 2000 12:58 pm
Queries processing for Remote Data by different tools; | article only | Jun 04, 2000 01:19 pm
How to detect and kill a long running job | article only | Jun 04, 2000 03:49 pm
evt_ and smp_ objects | article only | Jun 05, 2000 11:05 am
Oracle redo logs -- what is "cannot allocate log, archival required" | article only | Jun 05, 2000 01:14 pm
ORA-08002 error while select currval from a sequence | article only | Jun 06, 2000 09:33 am
Database is not mounting | article only | Jun 06, 2000 12:09 pm
change password for password file | article only | Jun 06, 2000 12:48 pm
order of records returned by an SQL statement | article only | Jun 06, 2000 04:31 pm
Date Type Variable -- how to get DATE componet and TIME component. | article only | Jun 07, 2000 08:27 am
How to control the output flow of records regarding a specific "Select" | article only | Jun 07, 2000 09:53 am
sql query use variable | article only | Jun 07, 2000 01:58 pm
Finding host name or connect string after database login. | article only | Jun 07, 2000 02:13 pm
Converting Oracle dates to a format understandable by SAS | article only | Jun 07, 2000 02:45 pm
SQL Loader | article only | Jun 07, 2000 04:17 pm
getting n rows from a query | article only | Jun 07, 2000 09:08 pm
Multiple Databases | article only | Jun 08, 2000 09:41 am
Schema Synchronization -- moving tables and changing storage characteristics | article only | Jun 08, 2000 10:00 am
Init file Parameter | article only | Jun 08, 2000 10:54 am
OPEN_CURSORS parameter | article only | Jun 08, 2000 02:41 pm
suppressing break actions when there's only one row in the group | article only | Jun 08, 2000 03:20 pm
Random Generation field width | article only | Jun 08, 2000 03:29 pm
redo log files | article only | Jun 08, 2000 03:59 pm
Database -- getting scripts to recreate. | article only | Jun 08, 2000 04:05 pm
Bitmapped indexes - how to do them in 7.3 | article only | Jun 09, 2000 12:56 pm
Using WebDb to report time summaries w/Oracle 8.1.6 | article only | Jun 09, 2000 02:12 pm
AQ & insert Question | article only | Jun 09, 2000 04:20 pm
row(s) 1 - 34 of 34
June 03, 2000 nagib -- Thanks for the question regarding "Oracle 8 EE on NT 4 - Reports Runtime Problem - MAX OPEN CURSORS", version 2.1
You Asked
Dear Tom

Generating reports 3.0 on O8EE on Nt4.  keeps giving me the
error:  no. of max open cursors exceeded.
I tried increasing the no. in the oracle init file to 50, 75,
100 with no help.    I have to close and restart the reports
background engine to recover.

Any hint please.

Thank You
Regards
Nagib
and we said...
I suggest increasing cursors to 500 or 1000.  This sets up a
fixed size array in the server and cursor space will be
allocated 64 at a time (so allowing for 1000 cursors -- which is
what I set all of my servers to -- will not hurt anything, it'll
not allocate all of the RAM for everyone, just the ones that
need it).

Reports, Forms, etc -- they all use a large number of cached
cursors. 50, the default is way to small for them.  500-1000
(recommend 1000), should correct this issue.

ps: don't over do it on the other hand.  too much of a good
thing can be bad.  Don't go over a thousand or so or the fixed
size array will start to consume too much memory.
June 03, 2000 jojo -- Thanks for the question regarding "inserting text document in a long datatype field", version version 7.3.4
You Asked
TOM:
     How do I insert text documents in a table with a long
datatype field. Can I use a PL/SQL command or a Stored procedure
to insert text documents in my Oracle Server 7.3.4 database.

rdgs,
Jojo
and we said...
If the text documents are 32k or less, you can write a stored
procedure that will use UTL_FILE to read an OS file into a PLSQL
long variable (limited to 32k) and then insert that into the
table.

It might look like this:

ops$tkyte@8i> create table t ( x long );

Table created.

ops$tkyte@8i>
ops$tkyte@8i> create or replace
  2  procedure load_file( p_dir in varchar2 ,
  3                       p_filename  in varchar2 )
  4  is
  5      l_input         utl_file.file_type;
  6          l_line          varchar2(2000);
  7      l_buffer        long;
  8  begin
  9      l_input := utl_file.fopen( p_dir, p_filename, 'r' );
 10
 11      loop
 12          begin
 13              utl_file.get_line( l_input, l_line );
 14          exception
 15              when no_data_found then exit;
 16          end;
 17                  l_buffer := l_buffer || l_line || chr(10);
 18          end loop;
 19
 20      utl_file.fclose( l_input );
 21
 22          insert into t values ( l_buffer );
 23  end;
 24  /

Procedure created.

ops$tkyte@8i>
ops$tkyte@8i> host cat /tmp/tkyte.dat
How now brown cow
the quick brow fox
Hello World

ops$tkyte@8i>
ops$tkyte@8i> exec load_file( '/tmp', 'tkyte.dat' )

PL/SQL procedure successfully completed.

ops$tkyte@8i>
ops$tkyte@8i> column x format a40
ops$tkyte@8i> select * from t;

X
----------------------------------------
How now brown cow
the quick brow fox
Hello World

Other then that, you must C, VB, Java or some other 3gl to
interact with the LONG type.

In Oracle8, release 8.0 and up, the CLOB type makes this
trivial.  Using a CLOB you can call dbms_lob.loadfromfile to
load upto 4gig into a TEXT field.  You also have full piecewise
read/write access to the clob from PLSQL using the dbms_lob
package.
June 03, 2000 Bhavendra -- Thanks for the question regarding "SQL query", version Oracle 8.0.4
You Asked
Hi tom,

Problem:

In my exiting table having following types of rows.

Feature_id    Effective_Date
1                 01-MAY-00
1                 01-JUN-00
1                 01-APR-00
2                 01-MAY-00
2                 01-APR-00
2                 01-JUN-00

Output required:

Feature_id    Effective_Date    Expiry_date
1                 01-MAY-00        31-MAY-00 (e.g.01-Jun-00-1)
1                 01-JUN-00         null
1                 01-APR-00        30-APR-00
2                 01-MAY-00        31-MAY-00
2                 01-APR-00        30-APR-00
2                 01-JUN-00         null

Expiry date : calculated one.
Condition: for Max(effective_date) there is no expiry_date on
the basis of feature_id.

Using SQL only.

Please help me, to get above result.

Thanks in advance,

Bhavendra
and we said...
Here are 2 ways to do this.  In Oracle8i, release 8.1, this will
be easy as what you really want to do is a select of a select.
In 8.1, this query will work great for you:

ops$tkyte@8i> select feature_id, effective_date,
  2         ( select min(effective_date-1)
  3             from t t2
  4            where t2.feature_id = t.feature_id
  5              and t2.effective_date > t.effective_date )
  6    from t
  7  /

FEATURE_ID EFFECTIVE (SELECTMI
---------- --------- ---------
         1 01-MAY-00 31-MAY-00
         1 01-JUN-00
         1 01-APR-00 30-APR-00
         2 01-MAY-00 31-MAY-00
         2 01-APR-00 30-APR-00
         2 01-JUN-00

6 rows selected.

Until then, one of these 2 solutions will work as well:

ops$tkyte@8.0> create table t ( feature_id int,
                                effective_date date );
Table created.

ops$tkyte@8.0> insert into t values ( 1,'01-MAY-00');
ops$tkyte@8.0> insert into t values ( 1,'01-JUN-00');
ops$tkyte@8.0> insert into t values ( 1,'01-APR-00');
ops$tkyte@8.0> insert into t values ( 2,'01-MAY-00');
ops$tkyte@8.0> insert into t values ( 2,'01-APR-00');
ops$tkyte@8.0> insert into t values ( 2,'01-JUN-00');

ops$tkyte@8.0> select t1.feature_id,
  2         t1.effective_date,
  3         decode( t2.effective_date,
  4                    t1.effective_date, null,
  5                    t2.effective_date-1) expiry_date
  6    from t t1, t t2
  7   where t1.feature_id = t2.feature_id
  8     and (t2.effective_date =
  9                  ( select min(effective_date)
 10                      from t t3
 11                     where t3.feature_id = t1.feature_id
 12                       and t3.effective_date >
 13                                     t1.effective_date )
 14          or ( not exists ( select effective_date
 15                              from t t3
 16                             where t3.feature_id =
 17                                         t1.feature_id
 18                               and t3.effective_date >
 19                                        t1.effective_date )
 20               and t1.effective_date = t2.effective_date
 21             )
 22         )
 23  /

FEATURE_ID EFFECTIVE EXPIRY_DA
---------- --------- ---------
         1 01-APR-00 30-APR-00
         1 01-MAY-00 31-MAY-00
         1 01-JUN-00
         2 01-APR-00 30-APR-00
         2 01-MAY-00 31-MAY-00
         2 01-JUN-00

6 rows selected.

The above query is fairly complex but does the trick.  It does
a self join on T with  itself.  So, we get every combination of
dates for each feature_id.  We only keep the rows such that:

   o the second effective_date is the smallest date LARGER
     then the first effective_date.  Thats the expiry_date
     for this row

   o there is NO second effective_date GREATER then this
     effective_date and the 2 effective_dates are the same
     (just need to keep one row -- we'll keep the row where
      we've joined to 'ourself')

We can also do this with a tiny bit of PLSQL code (the client
never has to know plsql is involved -- you can hide that in a
view even)...

ops$tkyte@8.0> create or replace
  2  function expiry_date( p_feature_id in number,
  3                        p_effective_date in date )
  4  return date
  5  is
  6      l_date    date;
  7  begin
  8      select min(effective_date-1)
  9        into l_date
 10        from t
 11       where feature_id = p_feature_id
 12         and effective_date > p_effective_date;
 13
 13      return l_date;
 14  end;
 15  /
Function created.

The above function simply does what the "select ... (select)
from T" will do in 8i for us.  The query is now:

ops$tkyte@8.0> select feature_id, effective_date,
  2         expiry_date(feature_id,effective_date)
  3  from t
  4  /

FEATURE_ID EFFECTIVE EXPIRY_DA
---------- --------- ---------
         1 01-MAY-00 31-MAY-00
         1 01-JUN-00
         1 01-APR-00 30-APR-00
         2 01-MAY-00 31-MAY-00
         2 01-APR-00 30-APR-00
         2 01-JUN-00

6 rows selected.

Which is much easy to code...  Try both and see what works
best in your case
June 04, 2000 gv -- Thanks for the question regarding "Regarding SQLERROR NUMBER and DML thro Views", version 8.0.5
You Asked
Q1:
    like SQLCODE and SQLERRM, how to find the line number which causes error
through PL/SQL programs?

Q2:
   I am NOT able to INSERT, UPDATE and DELETE through a view, if the
corresponding table has an object column(s). but i am able to do the same
through the table.
and we said...
If you catch an exception in PLSQL, you cannot find the line number that caused
the error -- that piece of information is lost.  The only way to get the exact
line number of the exception is to let the exception propagate out of plsql --
then the final error message will have the entire error stack.  You should only
have exception blocks where you expect an exception to occur and deal with it
(hence you would never need the line number as you were expecting an error to
occur, you would know where the error was coming from).  All errors you cannot
deal with would be propagated to the client.

Can you give an example of the issue with the Object Column?  I did the
following:

scott@ORA806.WORLD> create or replace type myType as object
  2  (       x int,
  3          y int
  4  )
  5  /

Type created.

scott@ORA806.WORLD>
scott@ORA806.WORLD>
scott@ORA806.WORLD> create table t
  2  ( a   int,
  3    b   myType
  4  )
  5  /

Table created.

scott@ORA806.WORLD>
scott@ORA806.WORLD> create or replace view tv
  2  as
  3  select * from t
  4  /

View created.

scott@ORA806.WORLD>
scott@ORA806.WORLD> insert into t
  2  values ( 1, myType( 0, 0 ) );

1 row created.

scott@ORA806.WORLD>
scott@ORA806.WORLD> insert into tv
  2  values ( 2, myType( 1, 1 ) );

1 row created.

scott@ORA806.WORLD>
scott@ORA806.WORLD> update t t
  2  set t.b = myType( 2, 2 )
  3  where a = 1
  4  /

1 row updated.

scott@ORA806.WORLD> update tv t
  2  set t.b = myType( 3, 3 )
  3  where a = 2
  4  /

1 row updated.

scott@ORA806.WORLD>
scott@ORA806.WORLD> delete from t t where t.b = myType( 2, 2 )
  2  /

1 row deleted.

scott@ORA806.WORLD> delete from tv t where t.b = myType( 3, 3 )
  2  /

1 row deleted.

scott@ORA806.WORLD>

Showing it is possible to insert/update/delete a view of a table with object
columns.
June 04, 2000 Amit -- Thanks for the question regarding "Error during executing a procedure for accessing directories that are permitted for PL/SQL file I/O.", version Oracle 8.0.5
You Asked
Error during executing a procedure for accessing directories
that are permitted for PL/SQL  file I/O.

I have modified the value of UTL_FILE_DIR in init.ora file as..
UTL_FILE_DIR= '\\lex1\exe'

mentioned directory is shared for all users(NT server).After
that i am getting error during executing following procedure..

CREATE OR REPLACE procedure openfile
is
l_for_writing             CONSTANT VARCHAR2(1)  := 'W';
extract_file_handle  UTL_FILE.FILE_TYPE;

begin
--     extract_file_handle :=
UTL_FILE.FOPEN('f:\batch\files','clac0120'||'.'||'.txt',l_for_wri
ting);
     extract_file_handle :=
UTL_FILE.FOPEN('\\lex1\exe','clac0120'||'.'||'.txt',l_for_writing
);
--     extract_file_handle :=
UTL_FILE.FOPEN('C:','CLAC0120.TXT',L_FOR_WRITING);

EXCEPTION
     WHEN UTL_FILE.INVALID_PATH
     THEN
         IF UTL_FILE.IS_OPEN(extract_file_handle)
         THEN
             UTL_FILE.FCLOSE(extract_file_handle);
         END IF;
     RAISE_APPLICATION_ERROR(-20000,'File location or name is
invalid.');
end ;
/

ERROR :ORA-20000 :File could not be opened as requested.

After that I have changed a value of UTL_FILE_DIR= '*' but
problem is still same.
and we said...
Please see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:241814624807
It describes the steps you must take to allow the Oracle
database to "see" networked drives.

When an oracle instance is created the services that support it
are setup to "Log On As" the SYSTEM (or operating system)
account, this account has very few privileges and no access to
NT Domains. To access another NT machine the OracleServiceXXXX
must be setup to logon to the appropriate NT Domain as a user
who has access to the required location for UTL_FILE.
June 04, 2000 Ben -- Thanks for the question regarding "Unix script not working ", version ORACLE 7.3.4
You Asked
Running the following script return the following error

Usage:  basename [ path [ suffix-pattern ] ]
Invalid null command
Missing }

LOG_ARCHIVE_DEST=/home/oracle/admin/test/arch
PRIMARYSITE=ares
set LastApplied = 'ls -l $LOG_ARCHIVE_DEST | tail -1'
@ LastApplied = 'basename $LastApplied:r|cut -c7-10'
@ NewestArchive = 'rsh $PRIMARYSITE cat
$LOG_ARCHIVE_DEST/latest.arc'
if ($NextToApply < $NewestArchive) then
foreach Archive
('echo $NextToApply $NewestArchive| \
awk '{for(i=$1;i<=$2;i++){printf("archive%04.log\n",i)' } }')
rsh $PRIMARYSITE dd if=$LOG_ARCHIVE_DEST/$Archive| \
rsh dd of=$LOG_ARCHIVE/$Archive
svrmgrl <connect internal
recovery standby database until cancel
auto
cancel
EOF
end
end
sleep 180
end

Here is my logic
DBMS_JOB.SUBMIT run the following query and output it to
flat file "Latest.arc"
select max(sequence#)from v$log where archived='YES';
eg (50)
The format in the archivelog directory will look like this
"arch000000050.dbf"The script was meant to format
"arch000000050.dbf"
to match entry in "Latest.arc" to determine the most recent
archived log in order to copy to standby .Do you have a better
way of doing this ?I will appreciate any script you might have
that does this.
Thanks
Ben
and we said...
You need to use `back tick`, not 'quotes' around basename.

What i've done in the past is to use a shell script + sqlplus to
figure out what archives exist and are fully written and
compress them (you want to copy them, i wanted to compress
them).

If you combine this so that you copy and then either MOVE or
COMPRESS them, you can use a script like this (note this script
is for 7.3, the names/columns of the v$ tables change in 8.x but
it would basically be the same):

#!/bin/csh -f

# Set up the environment, cron jobs don't have lots
# of environment variables...
setenv ORACLE_HOME /usr/oracle/oracle7
setenv ORACLE_SID  oracle7
set path=($path $ORACLE_HOME/bin /opt/gnu/bin)

# Goto where the archive files are archived to
cd /d01/arch

# Now generate a script that will 'select commands' out
# of the database.  In this case, my command looks like:
# gzip FILE; cp FILE.gz /another/disk
# That is, my command compresses the archive and copies it
# elsewhere.  Since I change the name of the archive when
# compressing it -- this script will not attempt to process
# this archive again.
# the query we generate will end up looking something like:
#
#  select archive_name from v$log_history
#   where archive_name in ( 'file', 'file', 'file' )
#     and sequence# not in
#        ( select sequence# from v$log where archived = 'NO' )
#
# where 'file', 'file', ... is picked from the files in the
# archive directory (that is why we need to rename or move them
# so we do not process them 2 times
#

echo set heading off > /tmp/$$.sql
echo set feedback off >> /tmp/$$.sql
echo set linesize 80 >> /tmp/$$.sql
echo column cmd format a70 >> /tmp/$$.sql
echo spool /tmp/$$.sh >> /tmp/$$.sql
echo select "'gzip ' || name || " >> /tmp/$$.sql
echo "'; cp ' ||archive_name||'.gz /d05/arch' cmd">>/tmp/$$.sql
echo 'from v$log_history' >> /tmp/$$.sql
echo 'where archive_name in(' >> /tmp/$$.sql
ls /d01/arch/*.log | sed "s/^/'/;s/"'$'"/',/" >> /tmp/$$.sql
echo 'NULL ) and sequence# not in ' >> /tmp/$$.sql
echo '( select sequence# from v$log where archived = '"'NO'"')'
>> /tmp/$$.sql
echo '/' >> /tmp/$$.sql
echo spool off >> /tmp/$$.sql
echo exit >> /tmp/$$.sql

# Now run the script we generated in sqlplus
# I like to use OPS$ (os authenticated accounts) for this
# sort of work to avoid having to put passwords in scripts
#
sqlplus / @/tmp/$$.sql

# All the sqlplus session did was generate yet another script
# to be run in the sh now.  We'll run it and then clean up
# This does the actual compress and copy...
#
sh /tmp/$$.sh
rm /tmp/$$.{sh,sql}

========================================================

You just need to modify the above to generate the command you
want to perform -- you should copy the files to the remote
system, perhaps apply them and then move the archive to another
directory (to avoid doing it all over again)
June 04, 2000 nagib -- Thanks for the question regarding "forms 5", version 2.1
You Asked
Dear Sir

How can I get info. about a file into a from running on Win
9X/NT
I need such attributes about files as :

Date Last Modified
Time   "      "
File Size.

Dev2k Win Util package in the demos does nott seem to have
the needed Win API calls.

Thank You
Regards
Nagib
and we said...
If it is a matter of being able to display this information to
the end user so they can pick a file based on that information
(eg: all you really need is the name of the file -- they
need the filensize/modification time to make a sensible choice),
the GET_FILE_NAME builtin can be used.  They can simply click on
"details" when this dialog comes up to see this additional
information (and sort by it and so on).

If you need this information in your program, some options you
have are:

o ORA_FFI, create your own binding to a C or VB dll you develop
to get this information.

o DDE

o OLE

o Active-X

o In a pinch, we can use HOST and TEXT_IO to do this as welll.
Lets say you need the details of a file c:\temp\x.sql... The
following block would get it for you:

DECLARE
    filename VARCHAR2(256) := 'x.sql';
    dirname  varchar2(256) := 'c:\temp\';
    in_file  Text_IO.File_Type;
    linebuf  VARCHAR2(80);
BEGIN
  host( 'cmd /c dir ' || dirname || filename ||
        ' > c:\temp\tmp.dat', NO_SCREEN );
  in_file := Text_IO.Fopen('c:\temp\tmp.dat', 'r');
  loop
      begin
          Text_IO.Get_Line(in_file,linebuf);
      exception
          when no_data_found then exit;
      end;
      if ( linebuf like '%' || filename ) then
              Message( linebuf );
      end if;
   end loop;
   text_io.fclose( in_file );
end;
June 04, 2000 Mehul -- Thanks for the question regarding "Oracle 8 Object option and user define data types -- What to read", version 8.0.5.1
You Asked
Are  there any white papers / presentations available explaining
the detailed usage of user defined data types with extensive
examples? Any help would be greatly appreciated!

Regards,
Mehul.
and we said...
User-Defined Datatypes
http://technet.oracle.com/doc/server.804/a58227/ch_ordb.htm#427515
User-Defined Datatypes - An Extended Example:
http://technet.oracle.com/doc/server.804/a58241/ch_adt.htm#437280
Object Views - An Extended Example:
http://technet.oracle.com/doc/server.804/a58241/ch_ov.htm#427515

Object Types
http://technet.oracle.com/doc/server.804/a58236/09_objs.htm#330
would all be good starts...
June 04, 2000 Prakash -- Thanks for the question regarding "Queries processing for Remote Data by different tools;", version 2.1
You Asked
Hi,
It's Prakash Again.
Thank You,
Can You Explain me How Queries for Remote datas (i.e. When it
involves Use Of Database Links ) are Processed By Different
Tools of Oracle (i.e SQL*PLUS, FORMS , GRAPH BUILDER, REPORTS )
and their Limitations in terms of returning Number of rows ;

One More thing,
In Graph Builder, We can Dynamically Specify the Datasource Name
using "&<Parameter Name>"  syntax for Query. Is it Possible in
any Other Tool.
and we said...
The tools do not process the "remote datas", it is always a
function of the server.  See
http://technet.oracle.com/doc/server.815/a67784/ds_ch1.htm#8215
for an overview of distributed query processing.

As for the dynamic datasource name -- if you are refering to the
tablename -- virtually every tool supports Dynamic sql and using
dynamic sql you can generate any query against any object at
runtime.
June 04, 2000 Calvin -- Thanks for the question regarding "How to detect and kill a long running job", version 7.3.4
You Asked
Hi Tom,

We need to write a script to detect a long running db job and
then erase the job to keep the performance up.
Should we perform this task on the UNIX or on the database?
If on the database, how do I write this script?

Thanks a lot,

CK
and we said...
Here is one method.  This is a sqlplus script that will generate
a list of sessions who have been executing a statement for 3
minutes or more (eg: a runaway query).

column cmd format a80
select 'alter system kill session ''' ||
        sid ||','||serial# ||
       ''' /* ' ||
        username ||
       ' ' ||
        trunc((sysdate-logon_time)*24) || ' hrs ' ||
        trunc(mod((sysdate-logon_time)*24*60,60)) ||
       ' mins */ ;' cmd
  from v$session
 where last_call_et > 180
   and username is not null
   and status <> 'KILLED'
/

It generates the appropriate "alter system kill session" command
to get rid of that session.

Also, consider using resource PROFILES to limit the amount of
resources a user may consume.  See
http://technet.oracle.com/doc/server73x/SQL73/ch4a.htm#toc093
for some info on that.
June 05, 2000 ade -- Thanks for the question regarding "evt_ and smp_ objects", version 7.3.4
You Asked
Can you tell me the main purposes of Oracle SMP_ and EVT_
tables,  and when they are created and used. Thanks

Ade
and we said...
These tables are used by Enterprise Manager, and comprise the
Enterprise Manager Repository. They are created by running the
smpcre.sql script in the repository owner's schema.
June 05, 2000 Rajesh -- Thanks for the question regarding "Oracle redo logs -- what is "cannot allocate log, archival required"", version ORACLE 8
You Asked
In ORacle 8 while Updating table which is having 49492 records
the following error is generated. 'Oracle instance orc1-cannot
allocate log, archival required'.
Please explain what is this error and how to solve?
and we said...
That warning occurs when a database is running in archive log
mode (for media recovery) and we need to reuse an online redo
log file (because you are filling them up quickly) and the one
we need to reused has not yet been archived safely to another
location.

This will be because either

o you did not enable automatic archiving with log_archive_start
but you have placed the database into archive log mode or...

o you are filling up archive logs so fast that ARCH cannot copy
them to the other location quickly enough (wait a minute and
it'll copy it and then work will proceed, we'll need to tune
arch but its a temporary situation) or...

o your archive destination is full and we cannot put any more
logs there.

See
http://technet.oracle.com/doc/server.804/a58397/ch23.htm#553
for information in archive log mode, archiving, turning it on
and off, enabling automatic archiving, tuning it and so on.
June 06, 2000 RAVINDAR -- Thanks for the question regarding "ORA-08002 error while select currval from a sequence", version 7.3.4
You Asked
I want to select the current value from a sequence.

When i do : select <seq.name>.currval from dual

ORA-08002 error is appearing.
sequence %s.CURRVAL is not yet defined in this session

How to avoid this..

If i do : select <>.nextval from dual,  then the value is
changed from the sequence.  After that the currval is working.
But if i disconnect that session and again connect to that
session i am facing the error.

Other ways (Workaround ..):

1)  i can take the value from dba_sequences (last_number-1).

2)  I tried to alter the sequence with nocache.  Eventhough
    it is not working..

Can u help me to solve this issue.

Awaiting for your valuable suggesstion.

Thanking you

With best regards
Ravindar S.
and we said...
Currval is by definition the value returned by your sessions last call to
nextval.  If your session has not called Nextval yet, Currval is undefined.

The value in dba_sequences will typically not suffice to find what the nextval
would be if you selected it as the last_number in dba_sequences jumps by the
cache size.  If you set the NOCACHE option (not recommended, it'll just make
things slow), then last_number will return what nextval would have returned had
you invoked it.

Since on an active system, whatever you get from dba_sequences is "stale" or out
of date almost as soon as you get it (others will be selecting nextval all of
the time) what I recommend is that you use either

  last_number
  last_number-cache_size+1

from dba_sequences.  Either is a good approximation of what the Nextval would be
(and all options to you are approximiations)...
Review & Followup
Rating: 5
Getting NextVal from Dynamic Performance View November 17, 2002
Reviewer: Pablo Rovedo from Argentina
Tom:

  You can get the nextval through the dynamic performance
  view sys.v$_sequences.

 Connecting with sys

 sys@ROP816> desc v$_sequences
 Name                                                  Null?    Type
 ----------------------------------------------------- --------
------------------------------
 SEQUENCE_OWNER                                                 VARCHAR2(64)
 SEQUENCE_NAME                                                  VARCHAR2(1000)
 OBJECT#                                                        NUMBER
 ACTIVE_FLAG                                                    VARCHAR2(1)
 REPLENISH_FLAG                                                 VARCHAR2(1)
 WRAP_FLAG                                                      VARCHAR2(1)
 NEXTVALUE                                                      NUMBER
 MIN_VALUE                                                      NUMBER
 MAX_VALUE                                                      NUMBER
 INCREMENT_BY                                                   NUMBER
 CYCLE_FLAG                                                     VARCHAR2(1)
 ORDER_FLAG                                                     VARCHAR2(1)
 CACHE_SIZE                                                     NUMBER
 HIGHWATER                                                      NUMBER
 BACKGROUND_INSTANCE_LOCK                                       VARCHAR2(1)
 INSTANCE_LOCK_FLAGS                                            NUMBER

sys@ROP816> create view v$sequences as select * from v$_sequences;

View created.

sys@ROP816> create public synonym v$sequences for sys.v$sequences;

Synonym created.

sys@ROP816> grant select on v$sequences to public;

Grant succeeded.

sys@ROP816>

and then connect with any user

rop@ROP816> create sequence s1_seq;

Sequence created.

rop@ROP816> select s1_seq.nextval from dual;

   NEXTVAL
----------
         1

rop@ROP816> select b.object_name,a.nextvalue
  2  from v$sequences a, user_objects b
  3  where a.object# = b.object_id and
  4        b.object_name = 'S1_SEQ'
  5  /

OBJECT_NAME           NEXTVALUE
-------------------- ----------
S1_SEQ                        2

rop@ROP816> select s1_seq.nextval from dual;

   NEXTVAL
----------
         2

rop@ROP816> select b.object_name,a.nextvalue
  2  from v$sequences a, user_objects b
  3  where a.object# = b.object_id and
  4        b.object_name = 'S1_SEQ'
  5  /

OBJECT_NAME           NEXTVALUE
-------------------- ----------
S1_SEQ                        3

rop@ROP816>

Regards
Pablo A. Rovedo

PD: I have read your book twice, is excellent!!!
    Are you writing a new one? any book regarding
    performance would by great

June 06, 2000 babu -- Thanks for the question regarding "Database is not mounting", version 7.0
You Asked
Hi
                       I am new to oracle .. recently i
installed oracle(7.0) in my unix server(UW2.0.1).

                    It was working fine. after that i tried to
create a tablespace .
                    create tablespace ts_111 data file
'/home/oracle/abc.dat'.
                    but that time it showed some error.  after
that database is not at all starting in my system.
                    while starting the database using dbstart
command, it is giving the error message.

                    $ dbstart

                    SQL*DBA: Release 7.0.16.4.0 - Production on
Tue Jun  6 15:21:39 2000

                    Copyright (c) Oracle Corporation 1979, 1992.
 All rights reserved.

                    ORACLE7 Server Release 7.0.16.4.0 -
Production
                    With the procedural and distributed options
                    PL/SQL Release 2.0.18.1.0 - Production

                    SQLDBA> Connected.
                    SQLDBA>  ORACLE instance started.
                    Database mounted.
                    ORA-01157: cannot identify data file 7 -
file not found
                    ORA-01110: data file 7:
'/home2/oracle/abc.dat'
                    Attempting to dismount
database........Database dismounted.
                    Attempting to shutdown
instance........ORACLE instance shut down.
                    SQLDBA>
                    SQL*DBA complete.

                    Database "nuo7" warm started.

                    ----------------
                    actually this data file
'home2/oracle/abc.dat' is not created in my system.
                    their may be some refernce in the control
files...

                    so how can i start database now. Somebody is
telling to create a new control file so that you
                    can use it.   There is no imp. datafiles in
my server. but i don't know how to proceed.

                    if anybody can help in a detailed way that
will be very helpful to me...
and we said...
I don't have a 7.0 instance to test with but here is a 7.1.6
database session I forced the same sort of issue with.  I create
a tablespace, shutdown, rm the datafile, startup and get the
error.  A startup nomount, alter database mount, alter database
datafile 'x' offline drop, alter database open and drop
tablespace will clean this up (it should -- its been a while
since I've had a v7.0 instance)

SVRMGR> create tablespace bad_tblspace
     2> datafile '/tmp/foo.dbf' size 1m;
Statement processed.

SVRMGR> shutdown;
Database closed.
Database dismounted.
ORACLE instance shut down.

SVRMGR> host rm /tmp/foo.dbf

SVRMGR> startup
ORACLE instance started.
Total System Global Area       5530204 bytes
Fixed Size                       48260 bytes
Variable Size                  3810776 bytes
Database Buffers               1638400 bytes
Redo Buffers                     32768 bytes
Database mounted.
ORA-01157: cannot identify data file 8 - file not found
ORA-01110: data file 8: '/tmp/foo.dbf'

SVRMGR> shutdown abort
ORACLE instance shut down.

SVRMGR> startup nomount
ORACLE instance started.
Total System Global Area       5530204 bytes
Fixed Size                       48260 bytes
Variable Size                  3810776 bytes
Database Buffers               1638400 bytes
Redo Buffers                     32768 bytes

SVRMGR> alter database mount;
Statement processed.

SVRMGR> alter database datafile '/tmp/foo.dbf' offline drop;
Statement processed.

SVRMGR> alter database open;
Statement processed.

SVRMGR> drop tablespace bad_tblspace including contents;
Statement processed.
SVRMGR>
Review & Followup
Rating: 5
May 13, 2002
Reviewer: Igor Khazanov

June 06, 2000 Jane -- Thanks for the question regarding "change password for password file", version oracle 8i
You Asked
Hi Tom,

I created a password file using ORAPWD. I want to change the
password. I think I should delete and recreate the password file
in order to do so. But when I read the Oracle server803 manual,
I found I could use ALTER USER command to change the password. I
got confused. The following is from server803 manual.

"PASSWORD This parameter sets the password for INTERNAL and SYS.
If you issue the ALTER USER command to change the password after
connecting to the database, both the password stored in the data
dictionary and the password stored in the password file are
updated. The INTERNAL user is supported for backwards
compatibility only. This parameter is mandatory. "

Would you tell me which way is correct?

Thank you very much.

Jane
and we said...
well, you should be able to do both.  if you recreate the
password file externally using orapwd, you should shutdown the
intance first and then run orapwd.

Rebuilding with orapwd is a sure way to do it.

ALTER USER SYS IDENTIFIED BY <newpassword>;

works just as well (to change the remote password for internal)
June 06, 2000 mark -- Thanks for the question regarding "order of records returned by an SQL statement", version 8.1.5.0.0
You Asked
I have always been under the impression that the order of the recordset returned
by an SQL statement, that does not use an order by statement, may not
necessarily be consistent from one execution to the next ( or at least you
should not count on it).

So the question is - Will the order of the recordset, returned by a SQL
statement, correspond to the order in which the records were inserted into the
database? Will the last value inserted be the last value returned in the
recordset?

thanks,

mark
and we said...
Your initial assumption, that the order of a result set is "random" or should be
considered so, is correct and the way to go.

records will not be returned in the order they are inserted.  Consider this tiny
example:

ops$tkyte@8i> drop table t;
Table dropped.

ops$tkyte@8i> create table t
  2  ( a int,
  3    x char(2000) default '*',
  4    y char(2000) default '*',
  5    z char(2000) default '*'
  6  );
Table created.

ops$tkyte@8i> insert into t (a) values ( 1 );
ops$tkyte@8i> insert into t (a) values ( 2 );
ops$tkyte@8i> insert into t (a) values ( 3 );
ops$tkyte@8i> commit;
Commit complete.

Ok, so we've inserted 1, 2, 3 in order...

ops$tkyte@8i> delete from t where a = 2;
1 row deleted.

ops$tkyte@8i> commit;
Commit complete.

We got rid of a row...

ops$tkyte@8i> insert into t (a) values (4);
1 row created.

ops$tkyte@8i> commit;
Commit complete.

We insert row '4' and then query em out:

ops$tkyte@8i> select a from t;

         A
----------
         1
         4
         3

Row 4 was put where row 2 used to be.  We reuse space over time, we put rows
where they best fit (you don't need an artificial test like I just used to get
this, it happens *all of the time* in real life.  We put stuff where it fits.
Row 100 might fit where row 90 did not...

Yet another example, not even as tricky... Just use a new feature that has an
effect on the storage (and there are lots of them -- partitioning, iot's...)

ops$tkyte@8i> drop table t;
Table dropped.

ops$tkyte@8i> create table t ( a int primary key )
  2  organization index
  3  /
Table created.

ops$tkyte@8i> insert into t values ( 4 );
ops$tkyte@8i> insert into t values ( 3 );
ops$tkyte@8i> insert into t values ( 2 );
ops$tkyte@8i> insert into t values ( 1 );

ops$tkyte@8i> select a from t;

         A
----------
         1
         2
         3
         4

IOT's force an order on the data -- by primary key.  Data comes out in the
order of the key by default -- not the order they went in....

there are others cases (dozens of them) as well.  If data needs to be sorted --
please sort it using ORDER BY....
June 07, 2000 chen -- Thanks for the question regarding "Date Type Variable -- how to get DATE componet and TIME component.", version Oracle 8.1.5
You Asked
Dear sir,
How to separate a datetype varaible into date and time?
My database is oracle8.1.5,my ows is oracle web application
server 3.0.2.

Thank you in advance!
John Chen
and we said...
To extract just the date component, you could:

select trunc(datecolumn) from T;

Trunc by default will removing the time component, you can trunc
dates to many different levels -- hours, days, weeks, months,
years and so on.

You could also just:

select to_char( datecolumn, 'dd-mon-yyyy' ) from t;

that is, use a date format to retrieve just the component of the
date you were interested in.

As for the time component, it'll be very similar.  For example:

select to_number(to_char(datecolumn,'sssss')) from T;

will return only the time component of the date as the number of
seconds since midnight.  Alternately, you may:

select to_number(to_char(datecolumn,'hh24')) hours,
       to_number(to_char(datecolumn,'mi'))   minutes,
       to_number(to_char(datecolumn,'ss'))   seconds
  from T;

to get the hours, minutes, seconds in the time component in
three fields.

There are many formats and functions you may apply to dates to
perform these operations, the above are just a few and the most
common.  For more see
http://technet.oracle.com/doc/server.815/a67779/function.htm#1028572
date functions and formats are documented there.
Review & Followup
Rating: 5
just what i needed April 22, 2003
Reviewer: A reader

June 07, 2000 hubert -- Thanks for the question regarding "How to control the output flow of records regarding a specific "Select"", version Oracle V-8.0.4
You Asked
My Problem:
I have an applet which queries a Database via a Java/Jdbc application.
These queries have a dynamic "Where" clause.
First of all, the Java/Jdbc application returns the records count
according to the predicate, and after that, the java application
sends the records according to a grouping factor, for example 50;
Example:
The Java/Jdbc application sends the first 50 records, then waits
for a "Next Record" command then sends the next 50 records and
so on.
My question:
What is the best way to resolve this problem taking the total number
of records into account which could be > 500000:
  - fetching the records within a resultSet and then send them
    to the applet according to the grouping factor ??
  - fetching the records and put them in a Java Vector and then
    send them to the applet ??

Any suggestions ???
Thanks
and we said...
Firstly, I would advise to not run a query that gets the count of the next
query.  It wastes lots of cpu cycles and is not necessarily going to be accurate
(what if someone inserts/updates/deletes the table?).  If you can (and you
almost always can) stop doing that -- you should.

You should just use a result set and set the "prefetch" (the amount we fetch for
you behind the covers) to be the same as your "grouping" factor.  For example:

        ((OracleStatement)stmt).setRowPrefetch(50);

That'll have us fetch 50 rows at a time -- you'll process 50 rows at a time and
the next time you ask for "50 more", we'll get 50 more in one call and buffer
them for you.
Review & Followup
Rating: 5
Two really good tips; don't count() and do set PreFetch April 05, 2001
Reviewer: Harrison Picot from Haymarket, VA USA
Learning this much has to count as a whole day's work!

June 07, 2000 Jimmy -- Thanks for the question regarding "sql query use variable", version version 8.05
You Asked
How to use a variable in a query?

I run a query get a result (ie:
  select month from tab_month

 I got a result  65

How could I insert this result into next sql statement: ie

  Alter table this_month drop partition $month

  In this statement $month should be 65.

  How could I assign this variable 65 into $month?

please help !
and we said...
In sqlplus this is done with the column command:

ops$tkyte@8i> column month new_value month
ops$tkyte@8i> REM directs us to put the last fetch of a column
ops$tkyte@8i> REM 'month' into a macro variable MONTH.

ops$tkyte@8i> select to_char(sysdate,'MM') month from dual;

MO
--
06

ops$tkyte@8i> select &month from dual;
old   1: select &month from dual
new   1: select 06 from dual

        06
----------
         6

ops$tkyte@8i>
June 07, 2000 malcolm -- Thanks for the question regarding "Finding host name or connect string after database login.", version Oracle 7 and/or 8
You Asked
From SQL*Plus, how can I determine the host to which I am
connected?

I commonly work on a set of distributed systems, which, combined
with different server versions and mainenance accounts, adds up
to about 200 different systems I might be working on, and many
of them look very similar.

I often wish I could reconfirm which system I am working on.

It is super easy to recheck the userid and the server version,
which helps, but I have yet to find a way (short of explicitly
re-connecting) to confirm what host system I am working on.

A way to find the original connect string would be best, but any
host identifying detail would be useful.

Many systems are running 7.3.4.1.0.  They are being switched,
slowly, to version 8.  Currently that seems to mean 8.1.6.0.0.
(I can use SQL*Plus 3.3.2.0.2, or  8.0.5.0.0, or could install
another I'm sure, if that makes any difference.)

Thanks for any infomation you could provide.
and we said...
I'm in the same boat (lots of databases, wanna know which one
I'm in).

I use a login.sql with SQLPlus.  I also make sure each and every
database has a unique global name (alter database rename
global_name to <some name>) or unique SID (i like the global
name myself).

In my login.sql i have:

....
column global_name new_value gname
set termout off
select lower(user) || '@' ||
decode(global_name, 'ORACLE8.WORLD', '8.0', 'ORA8I.WORLD',
'8i', 'ORA8IDEV.WORLD', 'dev8i', global_name ) global_name from
global_name;
set termout on
set sqlprompt '&gname> '
.....

That makes my sqlprompt look like:

ops$tkyte@DEV8I.WORLD>

So, now I have my username and database in the prompt.  I just
have to remember to use an @connect -- NOT connect when
connecting since the login.sql is run ONCE, not after every
connect.  My @connect is simply:

...
connect &1
@login
...

If you want to use the ORACLE_SID instead of the global database
name, just "select instance global_name from v$thread" in the
above.
Review & Followup
Rating: 4
Now I always know where I am. May 30, 2001
Reviewer: Johann Lodina from Germany
Thank you for this hint, it is exactly what I looked for.

Rating: 5
September 13, 2001
Reviewer: A reader

Rating: 5
It was a solution I really needed!! Thanks!! October 17, 2001
Reviewer: Shashank Sinha from Waukesha, WI USA
This site itself is pretty great, and the search engine is neat!!
This solution in particular was something that will save a lot of my hair...!!

Rating: 5
Instance and hostname on SQL*Plus login September 26, 2003
Reviewer: Angus McTavish aged 75 from Cumbria, England
Sometimes you might want more info than you can get from global_name, for
example the instance and the hostname for the database. Problem with that is
that the user may not have access to the v$ tables. I use a modified version of
your script which first gets the info from global_name and then tries to get
info from v$instance for example. If the user doesn't have access to v$instance
at least the global_name info will be displayed. If you simply use your script
(but replace global_name with v$instance), when you switch from a database where
you do have access to v$instance to one where you don't, the login will work but
you will display the login details from the first database. Know what I mean?

Here is an example of the modified script anyway:

column global_name new_value gname
set termout off
select lower(user) || '@' ||
decode(global_name, 'ORACLE8.WORLD', '8.0', 'ORA8I.WORLD',
'8i', 'ORA8IDEV.WORLD', 'dev8i', global_name ) global_name from global_name;
select lower(user) || ':'|| instance_name ||'@'|| host_name global_name from
v$instance;
set termout on
set sqlprompt '&gname> '

angus:TRFG@angustest> @connect angus/x@pan1
Connected.
angus:pan1@PANSYS01> @connect noddy/noddy@pan1
Connected.
noddy@PAN1.US.ORACLE.COM>

June 07, 2000 Greg -- Thanks for the question regarding "Converting Oracle dates to a format understandable by SAS", version 3.3.4.0.0
You Asked
Tom,

I am using the DBMS_OUTPUT.PUT_LINE function to write to a file.
 This file includes dates, and is to be processed by SAS, which
understands dates in the format...

    DDMonCCYY:HH:MM:SS
   (28Apr2000:10:05:00)

What function (or combination of functions) can perform this
conversion within PUT_LINE statement?

Thanks in advance.
and we said...
that would be:

dbms_output.put( to_char( datefield, 'DDMonYYYY:HH24:MI:SS' ) );

HH24 is the 24 hour clock (assuming thats what sas wants...)
June 07, 2000 Anu -- Thanks for the question regarding "SQL Loader", version Oracle 8i, replication server 1.6.0.0.0
You Asked
Can SQL Loader join two fields and store as one field in the
target table?
This a line in my input data file.

C|6302955242|90112|180021|0000354|2173455566

Item 4 indicates start time (format:HHMMSS)
Item 5 indicated elapsed time (format:MMMMMSS)

I want to add these two items and store the result as End time
in the Oracle table.

Thanks in advance!
and we said...
So, I have a table like this:

ops$tkyte@8i> create table t
  2  ( f1  varchar2(1),
  3    f2  int,
  4    f3  int,
  5    f4_5 int,
  6    f6  int
  7  )
  8  /

Table created.

And I use a .ctl file like this:

LOAD DATA
INFILE *
INTO TABLE T
REPLACE
FIELDS TERMINATED BY '|'
( f1       char,
  f2       char,
  f3       char,
  xf4       filler char,
  xf5       filler char,
  f6       char,
  f4_5     position(1:2000)
    "replace(substr(:f4_5,instr(:f4_5,'|',1,3)+1,14),'|','')"
)
BEGINDATA
C|6302955242|90112|180021|0000354|2173455566

and I get:

ops$tkyte@8i> set numformat 9999999999999
ops$tkyte@8i> select * from t;

F             F2             F3           F4_5             F6
- -------------- -------------- -------------- --------------
C     6302955242          90112  1800210000354     2173455566

ops$tkyte@8i>

Basically, we use a mixture of FILLERS (to map out fields 4 and
5) and SQL functions on a positionally mapped field.  the
Positionally mapped field is the entire line and we apply a
function that substrs out 14 bytes starting at the 3'rd pipe
(plus 1).  This 14 bytes includes one pipe we don't want, so we
replace that with nothing.  Thats what'll get inserted...
June 07, 2000 Aabhas -- Thanks for the question regarding "getting n rows from a query", version 8.0.4.0
You Asked
Hi Tom,
Summary of the problem:
I have to fetch rows x through y in a query and also order by a
field in the table.

I have already read article with subject "getting rows m through
n" but the solution that you have in it is applicable to that
particular version of oracle(8.1,8i). Is there a workaround I
could use in earlier versions?

Thanks
Aabhas
and we said...
Read
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:247014750272
before using this idea (there are 2 ideas here, one is
"risky"
-- the group by...

scott@8i> variable low number;
scott@8i> variable high number;
scott@8i>
scott@8i> exec :low := 5

PL/SQL procedure successfully completed.

scott@8i> exec :high := 10

PL/SQL procedure successfully completed.

scott@8i>
scott@8i> select ename
  2    from emp
  3   order by ename
  4  /

ENAME
----------
ADAMS
ALLEN
BLAKE
CLARK
FORD
JAMES
JONES
KING
MARTIN
MILLER
SCOTT
SMITH
TURNER
WARD

14 rows selected.

scott@8i>
scott@8i> select *
  2    from ( select a.*, rownum r
  3             from ( select ename, max(empno), max(deptno)
  4                      from emp
  5                     group by ename, rowid ) a
  6            where rownum <= :high )
  7   where r >= :low
  8  /

ENAME      MAX(EMPNO) MAX(DEPTNO)          R
---------- ---------- ----------- ----------
FORD             7902          20          5
JAMES            7900          30          6
JONES            7566          20          7
KING             7839          10          8
MARTIN           7654          30          9
MILLER           7934          10         10

6 rows selected.

Beware: group by does not have to sort!

Here is another way using object types:

scott@8i> create or replace type myScalarType as object
  2  ( ename varchar2(30),
  3    empno number,
  4    deptno number
  5  )
  6  /

Type created.

scott@8i>
scott@8i> create or replace type myTableType as
  2  table of myScalarType
  3  /

Type created.

scott@8i>
scott@8i> create or replace
  2  function get_data( p_low in number, p_high in number )
  3  return myTableType
  4  as
  5      l_data myTableType := myTableType();
  6      l_cnt  number default 0;
  7  begin
  8      for x in ( select ename, empno, deptno
  9                   from emp
 10                  order by ename )
 11      loop
 12          l_cnt := l_cnt + 1;
 13          if ( l_cnt >= p_low ) then
 14              l_data.extend;
 15              l_data(l_data.count) :=
 16                  myScalarType( x.ename, x.empno, x.deptno );
 17          end if;
 18          exit when ( l_cnt >= p_high );
 19      end loop;
 20      return l_data;
 21  end;
 22  /

Function created.

scott@8i>
scott@8i> select *
  2  from the ( select cast( get_data(5,10) as mytableType )
  3               from dual ) a
  4  /

ENAME                               EMPNO     DEPTNO
------------------------------ ---------- ----------
FORD                                 7902         20
JAMES                                7900         30
JONES                                7566         20
KING                                 7839         10
MARTIN                               7654         30
MILLER                               7934         10

6 rows selected.
June 08, 2000 Baljeet Kaur -- Thanks for the question regarding "Multiple Databases", version Oracle 8.0
You Asked
I would like to know how can I run and monitor more than one
database of Oracle on a single Oracle server installed on
Windows NT.
and we said...
Chapter 9 of the "getting started" document (available at
http://technet.oracle.com/docs/products/oracle8/doc_index.htm
) describes the methods to create a new database on Windows NT
using v8.0 software.

Oracle Enterprise Manager (OEM) would be used to monitor either
a single database or many databases.
June 08, 2000 George -- Thanks for the question regarding "Schema Synchronization -- moving tables and changing storage characteristics", version 8.0.5
You Asked
Tom
I would like to move a schema from one database to another. The
problem that the original one has storage closets and I cannot
export it without the  them.
What I am trying to say is that is there any way where I can
export the user with  the data and only with the initial extents

Thank you in advance

Best Regards
George Nikoloudis
and we said...
"storage closets"?  I assume you mean "storage clauses" ;)

I'm not sure what you mean by "is there any way where I can
export the user with the data and ONLY with the initial
extents"?

Is it that you want the data to be imported in the new database
with 1 extent?  If so, use COMPRESS=Y when you export.

Is it that yo want to use different storage characteristics all
togehter?  If so you can pre-create the tables in the target
database with "better" storage clauses and import with IGNORE=Y.
 If you do not have the schema to pre-create the objects, you
can EXP as normal and then do:

imp userid=u/p full=y show=y indexfile=precreate.sql

the file precreate.sql will look something like:

REM  CREATE TABLE "SCOTT"."BIG_TABLE" ("DROP_V_ADD" NUMBER(*,0),
REM  "CERTAIN_DATE" DATE) PCTFREE 10 PCTUSED 40 INITRANS 1
MAXTRANS 255
REM  LOGGING STORAGE(INITIAL 524288) TABLESPACE "UTILS" ;
REM  ... 3 rows
REM  CREATE TABLE "SCOTT"."BLOB_TEST" ("NAME" VARCHAR2(255),
"DATA" BLOB)
REM  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 LOGGING
STORAGE(INITIAL
REM  524288) TABLESPACE "UTILS" LOB ("DATA") STORE AS
(TABLESPACE "UTILS"
REM  ENABLE STORAGE IN ROW CHUNK 8192 PCTVERSION 10 NOCACHE
LOGGING
REM  STORAGE(INITIAL 524288)) ;
REM  ... 3 rows

....
that is, all of the CREATE TABLES will be there (along with
create indexes) only the create tables will be "REM'ed" out.
You just need edit this file, uncommenting the tables you wish
to fix and then create them in the target database with whatever
storage clause you like.  Then, imp with IGNORE=Y so that when
import tries to create the table (but finds it already exists)
it'll continue on and just load it for you.
June 08, 2000 Murtaza -- Thanks for the question regarding "Init file Parameter", version 8.0.5
You Asked
The initialization file parameter, optimizer_mode . What are
different values and their usage. What should be kept for a
heavy processing system

Thanks
and we said...
All initialization parameters are documented.  For 8.0 you can
goto
http://technet.oracle.com/doc/server.804/a58242/ch1.htm#36500
to read about them.

For this one, the values are:

o RULE - always use RBO (unless the query is hinted or accesses
         an object the RBO doesn't know about)

o CHOOSE - Use RBO if no stats are on any of the tables in a
           query.  Use CBO if any are analyzed (or there are
           hints or accessing an object the RBO cannot)

o FIRST_ROWS - Optimize with the CBO.  Try to get a plan that
               gets the first row of the result set the fastest

o ALL_ROWS  - Optimizer using CBO.  Try to get a plan that
              gets the last row of the result set the fastest.

As to which value you should use -- it would be up to you.
There is no "best" value for all (if there was, we would have
but one setting)...

In general, CHOOSE is appropriate.
June 08, 2000 Reji -- Thanks for the question regarding "OPEN_CURSORS parameter", version 8.1.6
You Asked
Tom:
    When you set the open_cursor parameter, what all you have
    to consider?  When Oracle create a cursor?  For example
    in pl/sql, you explicitly open a create a cursor and use it,
    if you have to, but when will Oracle implicitly create a
    cursor?   ex: In JDBC, when you execute a Statement, SQLJ
    when you create an iterator, I am just guessing here but
    would you please give me the situations where Oracle creates
    cursors?

    Is it possible two client sessions share the same cursor?

    Any help is really appreciated?

    TIA
    Reji
and we said...
You have to consider all cursors -- cursors you open, cursors
your application framework will open on your behalf, cursors the
database must open to perform recursive SQL.

For example, if you are in forms and have a default block and
nothing else and run that form, you'll find (before doing
ANYTHING) you have some cursors open.  Forms (your application
framework) has done some sql and cached the cursors on your
behalf.

As you do more work in forms (eg: query up a row, update a field
in the row) you'll see more and more cursors appear.  Some you
opened (by doing the query).  Others were opened on your behalf
(eg: forms locking the record for us when we updated the field).

You might also see some cursors come and go that reference SYS
tables.  These would be recursive queries and would happen when
the optimizer parses your query, needs to allocate space for
your query and so on.

You might also see other cursor come into play when triggers
fire, stored procedures run and so on.

It is not possible for 2 sessions to share the same exact cursor
but it is highly probable that 2 sessions will share the same
"shared_pool" entry for the underlying query (see SHARED SQL in
the concepts guide).  A cursor is in your space, the parse tree,
optimization, security and such is in a shared space.

It should be noted that OPEN_CURSORS simply allocates a fixed
number of slots but does not allocate memory for these slots for
a client (eg: it sets an array up to have 1,000 cursors for
example but does not allocate 1,000 cursors).  Rather, we will
allocate 64 cursor contexts at a time, as needed (so the first
cursor will allocate 64 contexts, the 65'th will get 64 more and
so on).   So, setting open-cursors to 1,000 or so it not harmful
(but don't go overboard and set it to 1,000,000 or something ;)
Review & Followup
Rating: 5
April 09, 2001
Reviewer: Pauline from U.S.A
You give the very clear concept explanation here.

June 08, 2000 jon -- Thanks for the question regarding "suppressing break actions when there's only one row in the group", version 3.3.4.0.0
You Asked
Please, do you know if there is a way to suppress 'on break'
actions (in this case 'compute sum of colx on coly') when there
is only a single row in the group? it makes a report look a mess
to have subtotals following single rows, especially when there
are lots of single row groups and only a few multiple row
groups.
and we said...
No, I'm afraid SQLPlus does not allow that degree of control.
You would need to use a more sophisticated reporting tool like
Reports or roll your own with DBMS_OUTPUT.PUT_LINE and PLSQL.

I know it won't help you now with version 7.3, but in Oracle8i,
release 8.1 -- the addition of new analytic functions make this
possible.  Consider this query against the standard EMP table:

scott@8i> insert into emp
  2  values
  3  ( 1234, 'TEST', 'CLERK', 5000,
  4    sysdate, 1000, 0, 40 );

1 row created.

scott@8i> column deptno format a4
scott@8i> break on deptno skip 1

scott@8i> select nvl( to_char(deptno), '**') deptno,
  2             nvl( job, '******' ) job,
  3             sum(sal), count(*),
  4             grouping(deptno) dept_grp,
  5             grouping(job) job_grp
  6    from emp
  7   group by rollup(deptno, job)
  8   having ( grouping(deptno)  = grouping(job) )
  9           or ( grouping(deptno) != grouping(job)
 10                    and
 11                    count(*) >  1)
 12  /

DEPT JOB         SUM(SAL)   COUNT(*)   DEPT_GRP    JOB_GRP
---- --------- ---------- ---------- ---------- ----------
10   CLERK           1300          1          0          0
     MANAGER         2450          1          0          0
     PRESIDENT       5000          1          0          0
     ******          8750          3          0          1

20   ANALYST         6000          2          0          0
     CLERK           1900          2          0          0
     MANAGER         2975          1          0          0
     ******         10875          5          0          1

30   CLERK            950          1          0          0
     MANAGER         2850          1          0          0
     SALESMAN        5600          4          0          0
     ******          9400          6          0          1

40   CLERK           1000          1          0          0

**   ******         30025         15          1          1

14 rows selected.

scott@8i>

Note the missing summary row for dept = 40 -- it has only 1
record in it

Here, we can use SQL to do our summing (totals) for us instead
of SQLPlus.  If we remove the HAVING clause from the above
query, we can see what I did to get just the stuff we needed:

scott@8i> select nvl( to_char(deptno), '**') deptno,
  2             nvl( job, '******' ) job,
  3             sum(sal), count(*),
  4             grouping(deptno) dept_grp,
  5             grouping(job) job_grp
  6    from emp
  7   group by rollup(deptno, job)
  8  /

DEPT JOB         SUM(SAL)   COUNT(*)   DEPT_GRP    JOB_GRP
---- --------- ---------- ---------- ---------- ----------
10   CLERK           1300          1          0          0
10   MANAGER         2450          1          0          0
10   PRESIDENT       5000          1          0          0
10   ******          8750          3          0          1
20   ANALYST         6000          2          0          0
20   CLERK           1900          2          0          0
20   MANAGER         2975          1          0          0
20   ******         10875          5          0          1
30   CLERK            950          1          0          0
30   MANAGER         2850          1          0          0
30   SALESMAN        5600          4          0          0
30   ******          9400          6          0          1
40   CLERK           1000          1          0          0
40   ******          1000          1          0          1
**   ******         30025         15          1          1

15 rows selected.

By adding in:

  8   having ( grouping(deptno)  = grouping(job) )
  9           or ( grouping(deptno) != grouping(job)
 10                    and
 11                    count(*) >  1)

We kept all rows where deptno and job where not summed over (if
both are 0, we have a detail row, if both are 1 we have the
total summation row)

OR

the rows were one or the other was summed over AND there was
more then one row contributing to the outcome...
June 08, 2000 Iceymole -- Thanks for the question regarding "Random Generation field width", version 7.3
You Asked
I have seen the package random for random number generation.
I have a field PIN number(8) which stores the random number,
what possible modification do I need to do to the existing
random package to get a maximum length of only 8.
Please reply soon.

I have found that 2^26(instead of 2^32), returns 8 digit,
but how can I find if it fails at any point of time.

Thanks in advance.
and we said...
I do not know which random package you are using with version
7.3 since dbms_random was not added to the database until
version 8.0.  In 8.1.6, it has additional functions allowing you
to specify a range of numbers (which would satisfy your needs).

In 7.3, you can consider the random package I have available at
http://osi.oracle.com/~tkyte/Misc/Random.html
There, you can call a function

   x := random.rand_max( 99999999 );

that will generate a random number between 1 and 99,999,999.
You can probably do the same with your existing package by
mod'ing the value you get back from it by 99,999,999 and adding
1 (thats what I do in rand_max myself)
Review & Followup
Rating: 2
It is useful March 15, 2001
Reviewer: yu.feng from japan

Rating: 4
April 18, 2001
Reviewer: Kimathi from Los Angeles, CA

June 08, 2000 razvan -- Thanks for the question regarding "redo log files", version 7.3.2
You Asked
Dear Tom,

Please can you explain me what does it mean that a "filled redo
group becomes inactive" ?
To be more precise i don't understand when a filled redo group
becomes inactive.
i believe that once a redo group become filled it becomes
automatically inactive and then after the checkpoint completes
at the log switch the LGWR may reuse that redo group.

Checkpoint is an event at which a DBWR start to
working..yes?....but CKPT process what does it?

thanks
razvan
and we said...
A filled redo log becomes inactive right after the checkpoint it
is "protecting" completes.  When we no longer need that log file
for crash recovery (because all of the blocks it is protecting
have been flushed to their datafiles) the log will become
inactive.

The logs can have status:

CURRENT     indicates this is the current redo log.  This
            implies that the redo log is active.  The redo
            log could be open or closed.

ACTIVE      indicate the log is active but is not the current
            log.  It is needed for crash recovery.  It may be
            in use for block  recovery.  It might or might not
            be archived.

INACTIVE    indicate the log is no longer needed for crash
            recovery.  It  may be in use for media recover. It
            might or might not be archived.

CKPT process helps DBWR by taking over the responsibility of
updating the datafile headers as checkpointing progresses.  It
just does part of the work DBWR could have done.  In current
releases of Oracle, CKPT is no longer optional and will be
started automatically.
June 08, 2000 Anil -- Thanks for the question regarding "Database -- getting scripts to recreate.", version 8
You Asked
Hello Sir,
   I am asking you a question for the first time.
   Does the database keep some scriptfile (schema definition)
of the existing schema which I can use to build a replica or
restore. If so how do I access it.
   I know that using export without exporting table data to a
dump file & opening it with wordpad I get the entire script I
want.
Do hope to get an answer from you.
With Regards,
Anil.
and we said...
The tool you are looking for is EXP as you have discovered.  It
contains all of the statements needed to recreate a schema in a
binary format (while you can open the dmp file in wordpad, it
contains binary control characters in it so be careful not to
save it from wordpad as that will render it useless).

You can extract most of the DDL from an exp using the command:

imp ... full=y indexfile=script.sql

That will generate an ascii text file with all of your create
table and create index statements.  This is not necessary as
just running:

imp ... full=y

on another database will recreate all of the objects for you.

There are various 3'rd party tools that can extract the schemas
and generate create scripts as well.
June 09, 2000 Niranjan -- Thanks for the question regarding "Bitmapped indexes - how to do them in 7.3", version Oracle 7.3.4
You Asked
How do i create a bitmapped indexes.
What is the syntax and when should it be used
How does oracle handle it.
Please explain with an example
and we said...
In version 7.3, they hid this nugget of information in the
server tuning manual.  For 7.3 that would be in:
http://technet.oracle.com/doc/server.734/a48506/access.htm#2218
that section includes:

Bitmap Indexing
This section describes:

o Benefits for Data Warehousing
o What Is a Bitmap Index?
o Cardinality
o Bitmap Index Example
o When to Use Bitmap Indexing
o How to Create a Bitmap Index
o Initialization Parameters for Bitmap Indexing
o Bitmap Indexes and EXPLAIN PLAN
o Using Bitmap Access Plans on Regular B-tree Indexes
o Bitmap Index Restrictions
June 09, 2000 Pat -- Thanks for the question regarding "Using WebDb to report time summaries w/Oracle 8.1.6", version 2.2
You Asked
This is with Oracle 8.1.6 (SE) and WebDB 2.2.

I've been scratching my head over something that I'm certain has
been solved several times before.  I have a table that has a
column of "times", that is, the real number of minutes that
something happened per day (ie 102.75 minutes). For example, if
I was a runner and tracking the number of minutes I ran in a
month, this table might look like:

Day  Minutes ran
---- -----------
1    45
2    98.31
3    37.92
4    102

and so on. Now, I need to generate a report which displays the
time in HH:MI format. I thought, no problem, in the SQL
statement for the WEBDB report just use this:

select STATDATE "Day",
TO_CHAR(TRUNC(RUNTIME/60),'09')||':'||TO_CHAR(MOD
(RUNTIME,60),'09') "Minutes ran"

which does work. However, I also need to generate column totals.
I have quite a few columns of this sort of info. I'd like the
column totals to be in a format that might be atypical for a
DATE field. Such as 213.73 hrs.

So, my questions are:
a) should I try to convert time? That is, I have successfully
tried:   to_char(to_date('01-JAN-1970','DD-MON-YYYY')+(RUNTIME/
(60*24) ),'HH24:MI') "Minutes ran"
  But WebDB's total result for this column is 0. I *really* need
accurate times in the totals. Do I need to 'Add advanced PL/SQL
code'? What I'd really like to show is a total format that's a
number of hours that can be larger than 24 ":" MM. For example,
someone might run 122:14 hours in a month.

b) should I abandon the convert to time approach and go back to
straight math, then write some crazy stored procedure to convert
everything back?

c) am I nutz for attempting such a thing in WebDB?

Many, many thanks for your helpful information and in advance
for this question!
and we said...
Well, this would be hard in any report tool since the thing you
want to sum, a "HH:MI" variable, isn't really summable.  What we
need to do is have the database compute the sum for us and we
apply a format to the details and the sum.

We can do this -- using the ROLLUP functions (there is a cube
function as well).

Consider this example:

ops$tkyte@8i> create table t ( day int, minutes number );
Table created.

ops$tkyte@8i> insert into t values ( 1, 45 );
ops$tkyte@8i> insert into t values ( 2, 98.31 );
ops$tkyte@8i> insert into t values ( 3, 37.92 );
ops$tkyte@8i> insert into t values ( 4, 102 );

ops$tkyte@8i> select nvl( to_char(day), 'TOTAL' ), sum(minutes)
  2    from t
  3   group by rollup(day)
  4  /

NVL(TO_CHAR(DAY),'TOTAL')                SUM(MINUTES)
---------------------------------------- ------------
1                                                  45
2                                               98.31
3                                               37.92
4                                                 102
TOTAL                                          283.23

So, the database can generate our totals and subtotals for us
(for another example of rollup, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:288416038228
)

Now, applying your formatting:

ops$tkyte@8i> select nvl( to_char(day), 'TOTAL' ),
  2
TO_CHAR(TRUNC(sum(minutes)/60),'fm09')||':'||TO_CHAR(MOD
  3            (sum(minutes),60),'fm09') "Minutes ran"
  4    from t
  5   group by rollup(day)
  6  /

NVL(TO_CHAR(DAY),'TOTAL')                Minutes
---------------------------------------- -------
1                                        00:45
2                                        01:38
3                                        00:38
4                                        01:42
TOTAL                                    04:43

And that is the query you'll build your webdb report on...

Answer to B) = NO
Answer to C) = NO
June 09, 2000 Vinnie -- Thanks for the question regarding "AQ & insert Question", version 8.1.5
You Asked
I have Oracle's AQ transmitting rows from one table to the
identical table at another location.
At times I may try & transmit the same row twice
giving a PK constraint error.
The actual insert is done in a trigger when the
message is recieved. What is the best way to handle this?
In the trigger Exception area? Should I perform
a select looking for the EVENT_ID first?  Should I just let the
error
occur & do nothing?

Thanks Again
and we said...
I would try the insert in the trigger and have an exception
block around it with a

  WHEN DUP_VAL_ON_INDEX then

handler to do the "right thing" when a dup was encountered.  So,
I would not do a select to see if its there, rather try the
insert and catch the error.

I cannot answer the question "should I just let the error occur
and do nothing?".  I don't know enough about what you are doing
to answer that fully -- that part is up to you ;)


Subject | Article | Last Updated (East coast time)
Regarding ORacle 8 Objects | article only | Jun 10, 2000 10:11 am
Applications based on stored-procedures and MultiThreaded Server | article only | Jun 10, 2000 11:32 am
Utl_file | article only | Jun 11, 2000 09:30 am
recovery -- how long do i need these archive redo log files for. | article only | Jun 11, 2000 03:20 pm
Function Based Indexes - feature not enabled. | article only | Jun 11, 2000 03:23 pm
STATSPACK | article only | Jun 12, 2000 07:51 am
form 5.0 query -- how to not login | article only | Jun 12, 2000 08:17 am
REF CURSOR and dynamic SQL | article only | Jun 12, 2000 09:53 am
Password Protection | article only | Jun 12, 2000 11:25 am
dynamically reference the type columns. | article only | Jun 12, 2000 01:26 pm
INIT.ORA - parameter definition -- where can I get a full list of them online | article only | Jun 12, 2000 01:38 pm
Standby Database | article only | Jun 12, 2000 04:15 pm
Column Histograms -- what are they about. | article only | Jun 12, 2000 04:30 pm
ORA-00106 Error with MTS Oracle configuration | article only | Jun 13, 2000 06:44 am
Get the days different in hh:mm:ss | article only | Jun 13, 2000 06:59 am
qn on tables and their count | article only | Jun 13, 2000 07:42 am
Job Queues - what are they. | article only | Jun 13, 2000 09:39 am
Append 'A' in UTL_FILE | article only | Jun 13, 2000 10:34 am
How to use varray type in where_clause of select statements? | article only | Jun 13, 2000 12:23 pm
Webdb Parameter Printing | article only | Jun 14, 2000 08:49 am
Performance, Update vs. Insert | article only | Jun 14, 2000 12:43 pm
Connection from client to oracle 7.3 without giving the database name | article only | Jun 14, 2000 02:04 pm
privileges to one procedure in a package | article only | Jun 15, 2000 08:48 am
Query Tuning -- question on top 10 buffer get percentage | article only | Jun 15, 2000 09:45 am
procedure,fn &packages -- whats the main difference between standalone procedures and packages | article only | Jun 15, 2000 10:13 am
foms and reoprts 6i -- what versions of Oracle does it work with | article only | Jun 15, 2000 10:28 am
granting rights on objects in others schema | article only | Jun 15, 2000 12:25 pm
OR set operatioon | article only | Jun 15, 2000 12:38 pm
Discrete Transaction | article only | Jun 15, 2000 01:02 pm
Need more details about Advantages of Database Procedure | article only | Jun 15, 2000 01:20 pm
Getting Value to a Unix Variable From Oracle Using Korn Shell Script | article only | Jun 16, 2000 10:00 am
Oracle Application Server (4.0.8.1) | article only | Jun 16, 2000 10:09 am
orapw file | article only | Jun 16, 2000 11:34 am
PL/SQL vs 3GL langage performance | article only | Jun 16, 2000 02:12 pm
Standby database -- what is it | article only | Jun 16, 2000 02:19 pm
Findind SQL Statements involved in Transaction | article only | Jun 16, 2000 02:47 pm
changing from 2k to 4k block size of an existing database | article only | Jun 16, 2000 03:20 pm
Cost value in Explain plan -- well, if I can't use that what do I use? | article only | Jun 16, 2000 06:14 pm
row(s) 1 - 38 of 38
June 10, 2000 Rajesh -- Thanks for the question regarding "Regarding ORacle 8 Objects", version ORACLE 8
You Asked
While creating the objects in Oracle 8, the SQL error 'Feature
is not enabled' is generating. But in  8i its creating with out
any new feature enabled. To work with objects in Oracle 8 what
feature is to be enabled?
and we said...
Rajesh -- you left the domain off of your email -- thats why
this took so long.

In Oracle8, objects where an extra cost option to the database.
You needed to have the Enterprise Edition and have purchased the
objects option in 8.0.  See
http://technet.oracle.com/doc/server.804/a58228/ch3.htm#5014
for clarification on what you get with standard/EE Oracle8.  So,
if you licensed the Objects Option and have EE, you can install
it from the original media.

In Oracle8i, objects are a base feature available to everyone
with standard or EE.  See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/ch4.htm#73594
for clarification on what you get with standard/EE Oracle8i.
June 10, 2000 Amit -- Thanks for the question regarding "Applications based on stored-procedures and MultiThreaded Server", version 8.0.5
You Asked
Hi Tom,

I am considering using MTS in a web application,
where NT web servers running ASP with OO4O work
against a central database.

While reading the book:

Oracle8 Advanced Tuning & Administration
by Eyal Aronoff, Kevin Loney, Noorali Sonawalla
Chapter 3: Memory and CPU tuning issues -

I encoutered the following text, and I quote:

"To avoid a performance penalty, do not use
MTS in applications that rely heavily
on stored procedures."

"In an MTS configuration, the shared SQL area is
used to store session-specific information
such as the context area and the sotr area.
Additionally, when there is competition for memory
usage within the shared SQL area, MTS can cause
expensive (from a performance perspective) memory
flushes to occur.
Increasing the size of the shared SQL area does
not resolve this problem or lessen the performance
impact. Instead, increasing the size of the shared
SQL area appears to increase the response time delay."

My questions:

1. A web application manipulates data with around 60
   stored-procedures; Is this too "intensive"
   for MTS ?

2. How can I tell whether using MTS will degrade
   performance instead of enhancing it ?

3. Do these issues exist in 8i ?

Thanks,
Amit.
and we said...
They need to update their book... What they say may have been
true in some respects for v7 of Oracle but in version 8, we
added the concept of a LARGE POOL:

<quote Oracle8.0 reference>
The parameter LARGE_POOL_SIZE lets you specify the size of the
large pool allocation heap. The default size is 0, and the
minimum size is 300K or LARGE_POOL_MIN_ALLOC, whichever is
larger. The value of the parameter can be specified in megabytes
or kilobytes. If specified, the large pool is used for session
memory if running with the multithreaded server. It is also used
for IO buffers during backup operations.
</quote>

The LARGE POOL is a  separate structure from the shared pool and
is designed to remove the issue to which they allude.  It
handles memory allocation in a different fashion then the shared
pool.

see
http://technet.oracle.com/doc/server.815/a67775/ch19_mem.htm#15039
for more information on this subject.

so the answers to 1 and 3 are NO.  the answer to #2 is
"benchmark" (its easy to turn MTS on and off).
June 11, 2000 Bhavendra -- Thanks for the question regarding "Utl_file", version 8.0.4
You Asked
Hi Tom,

Using utl_file package, I am generating text file. File is
successfully generated, but my problem is, I want to generate
that file on client machine not on server machine.
I have also specified in init.ora file utl_file_dir=*
This procedure  would be accessed by 300 concurrent users on
different geographical locations using centeralized database
concept.Whenever user execute this procedure through applcation
(API-ODBC)it will be generate THE FILE on server machine, if
specified folder is available on server machine else it will
gives the invalid operation because of utl_file package does not
recagonize the specified client folder.

I want to generate this file as per the locations (e.g.
c:\bhavendra\txt\mytext.txt)
Is there any limitation in utl_file package, so it will not
generated the txt file on specified folder on client machine.

Please kindly give me the feasible solution.

Thanks a lot kind co-operation

thanks and regards,

Bhavendra
and we said...
There is no chance of this with UTL_FILE.  UTL_FILE is running
physically on the server.  UTL_FILE can only see the disks that
the server can see (and if this is NT, it can only see the disks
the very un-priveleged system user we use can see -- very few
indeed).

In order to write to the client disk, the software must be
executing on the client.  You could use something like the
feature I demonstrated in
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:146412348066
with the My_Dbms_Output package.  Here, instead of
calling UTL_FILE.PUT_LINE in the plsql code, you would invoke
My_Dbms_Output.put_line.  After the plsql stored procedure
completed execution, the client would open a result set up --
fetch the rows, write them to the file on the client.

This would require minimal changes to the server software
(remove the fopen, fclose calls and change utl_file to
my_dbms_output elsewhere) and a little additional code on the
client (to open a result set, iterate over the rows in the
result set and writing them to a file).
June 11, 2000 razvan -- Thanks for the question regarding "recovery -- how long do i need these archive redo log files for.", version 7.3.2
You Asked
hello tom,

can you explain me if i adopte a archivelog mode for my database
the archived redo log occupied a lot of space with time.How can
i
face up with the wasted space because a backup of archived files
doesn't have sense because their represent too a backup of redo
log files with history.
How long can i stay with a lot of archived filled redo log if a
database doesnn't yet prezent a coruption?

can you explain me how can i manage a system tablespace
coruption?

thanks a lot
razvan
and we said...
Well, you only need to keep archive redo log files for as long
as you keep a backup of your database. (and I would hardly call
it "wasted" space if its the only thing that can save your
data!)

Hopefully, the archive isn't sitting on your disk -- its sitting
on a tape somewhere and maybe on disk as well.  The goal is to
get it copied off somewhere else (in the event the machine its
sitting on fails in a horrible way).

As for how long you should keep them...  Lets say you do hot or
cold backups and you do them every SATURDAY.  You keep the last
3 cold backups on tape and recycle the tapes so right now, today
on Sunday June 11'th you have:

o live copy of the datafile on disk
o a copy from June 4'th on tape A
o a copy from May 28'th on tape B
o a copy from May 21'st on tape C

You only need archive redo log from May 21'st on a tape
somewhere.  Any archive redo log you have from prior to May
21'st isn't applicable any more -- you have no datafiles around
that can possible need any of the archive generated prior to May
21'st.

So, the answer to your question lies in

o how frequently you do backups

o how many old backups you preserve in the event your last
backup was to a "bad" tape.

As for "how to manage system tablespace corruption" -- well,
hopefully it never does.  The best protection against failures
of this sort is a strong backup plan.  You should backup on a
recurring, scheduled basis and you should preserve a couple of
your last backups.  The reason for having more then 1 backup is
two fold

o you are never 100% sure that your tape will be readable again.
 You have a higher probability of being to read one of "three"
tapes then just one of one tape.  If you keep your last three
backups, you are almost certain to be able to get the datafiles
you need to recover...

o the corruption you are worried about might have been backed up
last week -- you just didn't know about it yet.  That is
entirely possible.  In the event the corruption you just
discovered was backed up last week, there is a good chance it
wasn't there the week before and a better one that 3 weeks ago
it wasn't there.  Hence, having >1 backup can really save you in
this case.

In order to get a really good handle on this, I recommend you
read a book just on recovery and backup.  There are a couple of
them out there (in addition to the Oracle supplied ones).

For Oracle7, I recommend
Oracle Backup & Recovery Handbook (Oracle Series)
by Rama Velpuri
June 11, 2000 Abhijit -- Thanks for the question regarding "Function Based Indexes - feature not enabled.", version Oracle 8.1.5 Personal Edition
You Asked
Tom,
I was reading your article on 'Function Based Indexes' and
wanted to try it out in Oracle 8.1.5 Personal Edition running on
Win 98.

Modified init.ora included the following lines -

query_rewrite_enabled=true
query_rewrite_integrity=trusted
Started up the database
Logged in as sys and executed
grant query rewrite to scott;
Logged in as scott/tiger

create temp_emp as select * from emp;
create index i1 on temp_emp(upper(ename)) ;
I get the following error message -
create index i1 on emp_temp(upper(ename))
*
ERROR at line 1:
ORA-00439: feature not enabled: Function-based indexes

Is it not supported in Oracle Personal Edition or am I missing
out anything ? Your help will be appreciated .
Thanks
Abhijit Bhattacharya
and we said...
sorry, function based indexes are not available with the
"standard" edition of Oracle, only the Enterprise Edition.  I
neglected to point that out in the paper.

See
http://technet.oracle.com/doc/server.815/a68020/ch4.htm#58509
for a list of the features/options available in each 'flavor' of
Oracle.
Review & Followup
Rating: 3
Function Based Indexes May 01, 2002
Reviewer: Shajan Joseph from Chennai, India

June 12, 2000 Jignesh -- Thanks for the question regarding "STATSPACK", version 8
You Asked
Hi Tom,

I would like to know from where i can download the pre-Oracle
8.1.6
version of Statspack. Will the download work for Oracle 7.3.4
too.

Hoping to hear from u as soon as possible.

Thanks and Regards,
Jignesh.
and we said...
See
http://www.oracle.com/oramag/oracle/00-Mar/o20tun.html
It has a link to download the pre-8.1.6 stats pack.  It is only
valid for Oracle8.0 and up.
June 12, 2000 Shrikanth -- Thanks for the question regarding "form 5.0 query -- how to not login", version d2k rel 2.1
You Asked
Hi this is Shrikanth

i would like to know one thing in forms 5.0 and that is,

how do i run a forms 5.0 form without connecting to the oracle
database.

ur reply will be highly appreciated.

thanx
shrikanth kannan
and we said...
Simply create an "empty" ON-LOGON trigger at the form level.
Just put the word

  null;

in the body of the ON-LOGON trigger and the form will no longer
log in.
June 12, 2000 Andres -- Thanks for the question regarding "REF CURSOR and dynamic SQL", version 8.1.5
You Asked
I want to use REF CURSOR as binded variable in dynamic SQL, how?
and we said...
In Oracle8i, release 8.1 ref cursors may be opened from a
"string" and bound to easily.  Here is an example:

scott@8i> variable x refcursor
scott@8i> set autoprint on
scott@8i>
scott@8i> declare
  2      p_arg_to_query    varchar2(20) default 'KING';
  3  begin
  4      open :x for
  5         'select ename, empno, sal ' ||
  6           'from emp ' ||
  7          'where ename = :x' USING p_arg_to_query;
  8  end;
  9  /

PL/SQL procedure successfully completed.

ENAME           EMPNO        SAL
---------- ---------- ----------
KING             7839       5000

see
http://technet.oracle.com/doc/server.815/a67842/10_dynam.htm#7875
for all of the details.
June 12, 2000 Vinnie -- Thanks for the question regarding "Password Protection", version 8.1.5
You Asked
Tom,

We have various PRO*C programs which are lanched at system startup.  We
currently have hardcoded ORACLE username & passwords in the code.  Is there a
way to store the password in the dB so we can somehow pull it & then start the
programs?

Perhaps you might have another suggestion for where to get the password from?

The apps are running on the machine with the dB.

We have looked at your hashing solution along with using
'ops$'
Does the ops$ solution only work with a sqlplus connect?
Or can you use it inside a app using a straight connect to?
and we said...
Since the applications are running on the same machine with the database server,
the best approach is to create the accounts "identified externally".

This is what I do on my servers when I have scripts or applications that need to
run in the background and access the database.  In this fashion, they can get
logged on without a password simply by being started in the right environment.

The steps I undertake to make this happen on Unix is:

o I like to set the init.ora parameter os_authent_prefix.  This is set to a
string that will be pre-pended onto the OS username when in the database.  If I
have an OS user "tkyte", I'll have a database user "ops$tkyte".  You do not have
to use ops$, you can use anything (or nothing) you like.

o create the user "identified externally", eg:
  create user ops$tkyte identified externally;

Now, your Pro*C application only needs to:

char *  USERID = "/";

    EXEC SQL CONNECT :USERID;

and your application will log in as the OS user.
June 12, 2000 Hakan -- Thanks for the question regarding "dynamically reference the type columns.", version version 8.1.5
You Asked
hi tom.

i need a little PL/SQL hint.
part of my code (indeed this is a version of your code :-) )

create or replace type maytayp as object( statistic# number,name
varchar2(64),class number,value varchar2(100),sid1
varchar2(100));
create or replace type maytabletayp as table of maytayp

create or replace package p_sta is
  l_data mayTableTayp:=maytabletayp();
  l_data_eski mayTableTayp:=maytabletayp();
  function sta return maytabletayp;
end;

and in the package body,
...
      if j.sid=1 then
        select value into p_sta.l_data(sayac).sid1 from
v$sesstat where sid=j.sid and statistic#=sayac-1;
        if p_sta.l_data_eski.count=sayi and
p_sta.l_data(sayac).sid1<>v(p_sta.l_data_eski(sayac).sid1) and
p_sta.l_data(sayac).sid1<>0 then
          p_sta.l_data(sayac).sid1:=p_sta.l_data(sayac).sid1 ||
' (%' ||
trunc((p_sta.l_data(sayac).sid1-v(p_sta.l_data_eski(sayac).sid1))
/p_sta.l_data(sayac).sid1,2) || ')';
        end if;
      end if;
...

and the que.
is it possible to reference p_sta.l_data(sayac).sid1 as
something like that

...
  a varchar2;
begin
  a:='sid1';
  p_sta.l_data(sayac).[a] or p_sta.l_data(sayac).[5] (like
VBasic)
...

thanks a lot.
have a nice day.
hakan yuksel.
and we said...
The answer is "sort of".

If the variables to which you need to refer are global package
variables, you can (with the requisite performance hit --
anything dynamic is slower then statis). Consider this example:

ops$tkyte@8i> create or replace type maytayp as object
  2  ( statistic# number,
  3    name       varchar2(64),
  4    class      number,
  5    value      varchar2(100),
  6    sid1       varchar2(100)
  7  );
  8  /

Type created.

ops$tkyte@8i>
ops$tkyte@8i> create or replace type maytabletayp as table of
maytayp
  2  /

Type created.

ops$tkyte@8i>
ops$tkyte@8i> create or replace package p_sta
  2  as
  3    g_data      mayTableTayp := maytabletayp();
  4    g_data_eski mayTableTayp := maytabletayp();
  5
  6    procedure sta;
  7  end;
  8  /

Package created.

ops$tkyte@8i> show err
No errors.
ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> create or replace package body p_sta
  2  as
  3      type myVarray is table of varchar2(25);
  4
  5  procedure sta
  6  is
  7      l_varName myVarray :=
  8              myVarray( 'name', 'class', 'value', 'sid1' );
  9
 10      l_idx     number default 1;
 11      l_value   varchar2(200);
 12
 13  begin
 14
 15      g_data.extend;
 16      g_data(l_idx) := maytayp( 1, 'name field', 2,
 17                              'value field', 'sid1 field' );
 18
 19
 20      for i in 1 .. l_varName.count
 21      loop
 22          execute immediate
 23                  'begin
 24            :valueof := p_sta.g_data(:y).'||l_varName(i)||';
 25                   end;'
 26          USING out l_VALUE, in l_idx;
 27
 28          dbms_output.put_line
 29                  ( 'The value of p_sta.g_data( ' ||
 30            l_idx || ').' ||l_varName(i) ||
 31            ' is "' || l_value || '"' );
 32      end loop;
 33  end;
 34
 35  end;
 36  /

Package body created.

ops$tkyte@8i>
ops$tkyte@8i> exec p_sta.sta
The value of p_sta.g_data( 1).name is "name field"
The value of p_sta.g_data( 1).class is "2"
The value of p_sta.g_data( 1).value is "value field"
The value of p_sta.g_data( 1).sid1 is "sid1 field"

PL/SQL procedure successfully completed.

They have to be package global variables in order for this to
work.
June 12, 2000 Reji -- Thanks for the question regarding "INIT.ORA - parameter definition -- where can I get a full list of them online", version 8.1.6
You Asked
Tom:
    Would you please point me to a URL where I can find out
    the definition of all the init.ora parameters?

    TIA
    Reji
and we said...
The server reference, online at
http://technet.oracle.com/doc/oracle8i_816/server.816/a76961/toc.htm
has them all
June 12, 2000 Vikash -- Thanks for the question regarding "Standby Database", version 8.0.5.2.1
You Asked
Can I create Oracle Standby database if the application is using unrecoverable
option while loading a table.
and we said...
Yes you can -- but you have to help it out somewhat.

In Oracle8i, release 8.1.6, they added to the documentation a manual dedicated
to nothing other then Standby Database operation.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76995/toc.htm
Even though its for 8.1.6, it applies mostly to 8.0 and 7.3 as well.

In particular, the answer to your question is:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76995/standbym.htm#27273
which describes the steps available to you after performing an unrecoverable
option on the primary server.
June 12, 2000 V Siva -- Thanks for the question regarding "Column Histograms -- what are they about.", version 7.3.2.3.0
You Asked
Hi Tom,

While I was reading a article on Oracle Tuning, I've gone through the following
paragraph:

"The most frequent cause of high miss rates in the library cache is the use of
literals rather than bind variables in SQL statements. Bind variables reduce
parse overhead by allowing otherwise identical SQL statements with different
query parameters to be matched in the shared pool. However, bind variables
preclude the use of column histograms and thus are not suitable in all
circumstances."

Here there is term "Column Histograms" used. I want to little bit more about
this.

Thanks
Siva
and we said...
In some situations, you might have a column with very skewed data.  For example,
you might have a table with 1,000,000 rows.  500,000 of the rows are such that
column C is unique (it contains the values 1 .. 500,000).  for the remaining
500,000 rows -- the value of C is a constant - they all have -1 as their value.

This data is very skewed.  If I run a query:

select * from T where C = :x

and the value of :x is anything OTHER then -1, I would really want you to use an
index.  If :x is the value -1 -- I do NOT want you to use an index.

The server, given the above query would make the assumption that C is selective
and would opt to use the index.  Thats great for every thing BUT the query where
:x = -1.  That query takes a really really long time and chews up your disk with
single block IO.

When computing statistics, you can have it compute histograms as well.  In this
case, the server will remember what values for C are selective and which are
not.  Now, if you submit the query:

select * from T where C = 1;

and

select * from T where C = -1;

the optimizer will come up with 2 different plans based solely on the constraint
against C.  It will index range scan for C = 1, and it will FULL SCAN T for C =
-1.

This typically only occurs in a data warehouse where the time to execute a query
far far outweighs the time to parse it.  In a typical enviroment (surprisingly
to many people) it takes longer to parse and optimize many queries then it does
to actually execute them.

In general -- ALWAYS use bind variables and then go back and put in the hard
coded values for these very very exceptional cases.  Do not stop using bind
variables!!  They are crucial...

(although -- i hesitate to mention this as people might stop using them -- in
8.1.6, there is a new "autobinding" feature. Applications, including many
packaged applications, that use literals instead of bind variables in SQL can
see improved performance because release 8.1.6 can automatically substitute bind
variables in place of the literal values. This lets multiple users share the
parsed SQL regardless of the literal value, dramatically reducing the SQL parse
time and saving memory in these applications.  Haven't tested it myself yet --
on the list of "things to do")
Review & Followup
Rating: 5
Thank you March 28, 2002
Reviewer: erik cook
Thank you, thank you, thank you. You are the man! I always find a good answer
here!

June 13, 2000 Gunjeet -- Thanks for the question regarding "ORA-00106 Error with MTS Oracle configuration", version 8.1.6
You Asked
Hi,

We are getting ORA-00106 while doing a shutdown
immediate/abort of Oracle running in MTS mode.

ORA-00106: cannot startup/shutdown database when connected to a
dispatcher
Cause: An attempt was made to start up or shut down an instance
while
connected to a shared server process via a dispatcher.
Action: Reconnect to the database using a dedicated server.

The command used for shutdown is :

connect sys/<whatever> as sysdba
shutdown immediate

How do I get a dedicated connection to perform the shutdown ?

Please help.

Thanks,

Gunjeet
and we said...
o are you logged into the machine directly?

o are you using sqlplus or svrmgrl?

o do you have the environment variable TWO_TASK set?

If you are doing this over the network or have TWO_TASK set (so
that is it using a sqlnet connection anyway) make sure you have
set it up so that if the network is configured for MTS and a
particular client requires dedicated server mode, the
TNSNAMES.ORA file can be configured with a net service name that
uses a dedicated server. This is achieved with
(SERVER=DEDICATED) in the CONNECT_DATA section of a connect
descriptor:

net_service_name=
(description=
(address= ( protocol_address_information))
(connect_data=
(service_name= service_name)
(server=dedicated)
)
)
June 13, 2000 Gnanaparan -- Thanks for the question regarding "Get the days different in hh:mm:ss ", version Oracle 7.3, Sqlplus 3.3
You Asked
Hi Tom,

I have worked out to get no of days between two days. I want to
get in hh:mm:ss format.

This is the sql. System date is 13-jun-00.

select sysdate, to_date('08-jun-00') receive_date,
sysdate -to_date('08-jun-00') no_of_days
from dual

Result:

SYSDATE   RECEIVE_D NO_OF_DAYS
--------- --------- ----------
13-JUN-00 08-JUN-00  5.4894676

How can I get the NO_OF_DAYS in hh:mm:ss ?
and we said...
Using some simple MODS and TRUNCS, we can derive this answer.
Using the CREATED field of all users -- I'll find out how long
ago the first record returned was created:

ps$tkyte@8i> select
  2  to_char( created, 'dd-mon-yyyy hh24:mi:ss' ) Created,
  3  to_char( sysdate, 'dd-mon-yyyy hh24:mi:ss' ) today,
  4  trunc( (sysdate-created)*24 ) || ':' ||
  5  trunc( mod( (sysdate-created)*24*60, 60 ) )  || ':' ||
  6  trunc( mod( (sysdate-created)*24*60*60, 60 ) ) Elaps
  7  from all_users
  8  where rownum =1
  9  /

CREATED              TODAY                ELAPS
-------------------- -------------------- -----------------
20-apr-1999 13:08:42 13-jun-2000 07:04:50 10073:56:8

If you don't like the hours going over 24, you print out "days
hh:mi:ss" instead like this:

ops$tkyte@8i>
ops$tkyte@8i> select
  2  to_char( created, 'dd-mon-yyyy hh24:mi:ss' ) Created,
  3  to_char( sysdate, 'dd-mon-yyyy hh24:mi:ss' ) today,
  4  trunc( sysdate-created ) || ' days ' ||
  5  to_char(trunc(mod((sysdate-created)*24,24)),'fm00')
  6  ||':'||
  7  to_char(trunc(mod((sysdate-created)*24*60,60)),'fm00')
  8  ||':'||
  9  to_char(trunc(mod((sysdate-created)*24*60*60,60)),'fm00')
 10  ELAPS
 11  from all_users
 12  where rownum =1
 13  /

CREATED              TODAY                ELAPS
-------------------- -------------------- -----------------
20-apr-1999 13:08:42 13-jun-2000 07:04:50 419 days 17:56:08

ops$tkyte@8i>
June 13, 2000 sijo -- Thanks for the question regarding "qn on tables and their count", version 8.1.5
You Asked
i want to display the tablenames in 1 column & their count of
rows in 2nd column using a single sql query like
dept 4
emp  14...
and we said...
Well, if you analyze the tables -- you can get a very good
estimate of the rows via:

SQL> select table_name, num_rows from user_tables;

It'll be an estimate or approximation however as the stats are
not maintained in "real time".

In Oracle8i, which you are using, we can use dynamic sql in a
function to be called from SQL.  In this case, we can in fact
code:

scott@8i> create or replace
  2  function get_rows( p_tname in varchar2 )
  3    return number
  4  as
  5      l_columnValue    number default NULL;
  6  begin
  7     execute immediate 'select count(*)
  8                     from ' || p_tname INTO l_columnValue;
  9
 10      return l_columnValue;
 11  end ;
 12  /

Function created.

scott@8i>
scott@8i> select table_name, get_rows(table_name)
  2    from user_tables
  3  /

TABLE_NAME                     GET_ROWS(TABLE_NAME)
------------------------------ --------------------
BIG_TABLE                                         3
BLOB_TEST                                         3
BONUS                                             0
CHRIS                                             0
CLOB_DEMO                                         1
CUSTOMER                                          0
CUSTOMER_SERVICE                                  0
DEMO                                              1
DEPT                                              4
DUMMY                                             1
EMP                                              14
EMPLOYEE                                          0
EXECUTABLES                                       4
IMAGE                                             2
IMAGES                                            1
IMAGE_TABLE                                       1
MAPPING_TABLE                                     8
MYTABLE                                           0
NEW_EMP                                          28
ORDERS                                            0
PRODUCT                                           0
SALGRADE                                          5
SPAREPARTCOMB                                     1
T                                                 3
T1                                                2
T2                                                2
TESTLR                                            0
TEST_IMAGES                                       1
X                                                 0

29 rows selected.

scott@8i>

As you can imagine -- getting the count(*) will be an expensive
operation and should be used somewhat sparingly.
Review & Followup
Rating: 2
use function get_rows results in ORA-0942 August 07, 2001
Reviewer: Gus Spier from Middleburg, VA
Use of function "get_rows" results in an ORA-0942 at line 6, table or view
doesn't exist.

Kind of frustrating and too late at night to track down ... tomorrow we'll try
just executing function with hand-jammed value for 'p_tname'

Rating: 5
selecting the count(*) of all user_tables. January 30, 2003
Reviewer: heyvaert from Belgium (Europe)

June 13, 2000 Anwar -- Thanks for the question regarding "Job Queues - what are they.", version 7.3.2
You Asked
Hello Tom!

I've heard about the concept of job queues in Oracle 7 but don't
know exactly what are they & how can we create them, please
explain?
and we said...
See
http://technet.oracle.com/doc/server73x/SAD73/Ch7.htm#toc059
for the documentation on this feature.

Job Queues are the mechanism on top of which features such as
"snapshots" are built.  They are sort of like cron for the
database -- they run jobs either on a one off or recurring
basis.  They are a convienent tool for you to run some
procedures in the background or do things that are "impossible".

For example, lets say you wanted to create a new user every time
a row was inserted into a database table.  You cannot do this in
a trigger since a trigger cannot commit and DDL such as CREATE
USER commits.  You could write a stored procedure that uses
DBMS_SQL to create a user and instead of having the trigger call
this procedure, the trigger calls DBMS_JOB (your api into the
job queue) to schedule a call to this procedure AFTER you've
committed.  Shortly after your transaction commits, your job
will run and create the user for you in the background.  This is
nice for 2 reasons:

o you could not create the user otherwise from the trigger

o if the insert into the table gets rolled back and not
committed, the job will be rolled back and never executed as
well -- it makes this more "transactional".

Job queues have many other uses as well, for example to schedule
your "analyze tables" on a recurring basis, to run a report in
the backgroup, to do ddl in a trigger and so on....
June 13, 2000 Iceymole -- Thanks for the question regarding "Append 'A' in UTL_FILE", version 3.0
You Asked
The UTL_FILE has 3 modes of operation - 'R','W','A'.

The reference manual says, if we specify 'A', while
opening the file,
ie. UTL_FILE.FOPEN(path,filename,'A');

If the file exists it appends to the file and if it
doesnot exist it will open the file in Write mode.

I have tried by having no existing file in the directory
and it returns me an error
'Invalid Operation'.

So, if I go into the UNIX box and create an empty file, then
it works fine.

Can you explain this.

Thanks in advance.
and we said...
database version?  It is most likely v7.3.  There is a bug
whereby the append mode does not create the file.  The
workaround is to code:

    begin
        file_stat := utl_file.fopen(file_dir,file_name,'a');
    exception
        -- if file does not exist, fopen will fail with
        -- mode 'a' - bug:371510
        when utl_file.invalid_operation then
            -- let any other exception propagate
            -- to the outer block as normal
            file_stat := utl_file.fopen(file_dir,file_name,'w');
    end;

It is fixed in version 8.0.3.  The above is functionally
equivalent to the way it does work in 8.0 and up.  For ease of
use, you would probably put the above into a small subroutine
somewhere and replace it with just

        file_stat := utl_file.fopen(file_dir,file_name,'a');

when you goto v8 or up.
June 13, 2000 minnie -- Thanks for the question regarding "How to use varray type in where_clause of select statements?", version Oracle 8i 8.1.5
You Asked
Hi,Tom
If I have a table including a column which is a varry type,

such as
create table myarray as varray(5) of number(10);
create table mytest(col1 number,col2 myarray)
insert into table mytest(1,myarray(1,2,3,4,5));

I try to use the values of varray type column as condition in
where_clause like
"select * from mytest where col2=myarray(1,2,3,4,5);",
but I failed . How I can do
and we said...
From the PLSQL reference:

<quote>
Comparing Whole Collections

Nested tables and varrays can be atomically null, so they can be
tested for nullity, as the following example shows:

DECLARE
  TYPE Staff IS TABLE OF Employee;
  members Staff;
BEGIN
...
   IF members IS NULL THEN ... -- condition yields TRUE;
END;

However, collections cannot be compared for equality or
inequality. For instance, the following IF condition is
illegal:

DECLARE
  TYPE Clientele IS TABLE OF Customer;
  group1 Clientele := Clientele(...);
  group2 Clientele := Clientele(...);
BEGIN
...
  IF group1 = group2 THEN -- causes compilation error
...
  END IF;
END;

This restriction also applies to implicit comparisons. For
example, collections cannot appear in a DISTINCT, GROUP BY, or
ORDER BY list.

</quote>

So, you need to use an OBJECT type to do this and, much like you
would in Java or C++, you must create an "operator" to do the
comparision -- Just as in Java you have to use:

     stringVariable.isEqual( "some other string" )

we must use

     objectCol.isEqual( some other object instance )

Here is a small example:

ops$tkyte@8i> create type myarray as varray(5) of number(10);
  2  /
Type created.

ops$tkyte@8i> create type myObject as object
  2  ( array myArray,
  3    member function isEqual( p_other in myArray default null)

                       return number
  4  )
  5  /

Type created.

ops$tkyte@8i>
ops$tkyte@8i> create type body myObject
  2  as
  3      member function isEqual( p_other in myArray )
                return number
  4      is
  5      begin
  6          if ( self.array.count <> p_other.count )
  7          then
  8              return 0;
  9          end if;
 10
 11          for i in 1 .. self.array.count
 12          loop
 13              if ( self.array(i) <> p_other(i) )
 14              then
 15                  return 0;
 16              end if;
 17          end loop;
 18          return 1;
 19      end;
 20  end;
 21  /

Type body created.

ops$tkyte@8i> create table mytest(col1 number,col2 myObject)
  2  /

Table created.

ops$tkyte@8i> insert into mytest
              values ( 1, myObject( myarray(1,2,3,4,5) ) )
  2  /

1 row created.

ops$tkyte@8i> select t.col2.array Array from mytest T
  2  /

ARRAY
-------------------------
MYARRAY(1, 2, 3, 4, 5)

ops$tkyte@8i> select t.col1, t.col2.array array
  2    from mytest t
  3   where t.col2 = myobject( myarray(1,2,3,4,5) )
  4  /

no rows selected

No data found, object1 <> object2...

ops$tkyte@8i>
ops$tkyte@8i> select t.col1, t.col2.array array
  2    from mytest T
  3   where t.col2.isEqual( myArray(1,2,3,4,5) ) = 1
  4  /

      COL1 ARRAY
---------- -------------------------
         1 MYARRAY(1, 2, 3, 4, 5)

But out compare works OK
June 14, 2000 Venku Reddy -- Thanks for the question regarding "Webdb Parameter Printing", version 2.2
You Asked
I have developed the report in webdb 2.2 using reports option in
the tool. I am having parameter form for entry for parameters
(ex apr 2000). I want to print this parameter in report output
in HEADER PART. iF my report header is "statistics for the month
of april 2000" i have to print. How I can i acheive this in
webdb.

Thanks
Regards
Venku Reddy
and we said...
You have to write some PL/SQL to achieve this.  In the
"...before displaying the form" advanced PL/SQL code for the
report you could do the following...

<example>

declare
  l_input :=
DB.wwv_name_value.get_string(
               l_arg_names,
               l_arg_values,
               '<BIND_VARIABLE_NAME>',
               '<DEFAULT_VALUE_IF_BIND_IS_NOT_SET>' );
begin
  htp.p( 'The inputted value was: ' || l_input );
end;

</example>

You can use WEBDB.wwv_name_value.get_string() to get any value
passed to any WebDB object, not just reports.
Review & Followup
Rating: 5
Brilliant! November 20, 2001
Reviewer: Kavitha from UK
Hi,

I didn't know that there was a way to do this! I always used an intermediate
table to store the parameter value using a form and run the report based on this
table and display the string on the report page as a heading using before
processing of report. Thanks a lot for this! Its absolutely brilliant!

Thanks a lot!

Rating: 5
Can you clarify something? November 20, 2001
Reviewer: Kavitha from UK
Hi,

I tried your example on a report. I accepted a date parameter from the user and
I wanted to display this on the report.show page. I put in the code you have
given, and just corrected few errors that it threw back.

WebDB accepted the code and I entered the parameter and hit the show button. But
the code kept returning the default value and not the actual parameter value.
Where have I gone wrong?

The code I put into before displaying the form is:
declare
  l_input VARCHAR2(100) :=
WEBDB.wwv_name_value.get_string(
               l_arg_names,
               l_arg_values,
               'tdate',
               '01-JAN-2001' );
begin
  htp.p( 'The inputted value was: ' || l_input );
end;

Please let me know how to correct this code.
Thanks in advance!

Rating: 5
Perfect solution to problem September 06, 2002
Reviewer: Gary from UK Hull
I have a searchable knowledge base which creates wweb pages from records of a
table A_TO_Z. I needed a hit count for each page (record).

Using the following on the report showing the webpage and taking the variable
passed from the search results report I now have a hit count for each record.
The hit count is now displayed on the search results and in a management report
chart also. Top tip ... thanks Tom!

declare
  l_input VARCHAR2(50) :=
WEBDB.wwv_name_value.get_string(
               l_arg_names,
               l_arg_values,
               'myid',
               '100' );
begin
  UPDATE A_TO_Z SET HITCOUNT = HITCOUNT + 1 WHERE ID = l_input;
end;

June 14, 2000 -- Thanks for the question regarding "Performance, Update vs. Insert", version Oracle 8.1
You Asked
Hi Tom,

     I came across codes that instead of updating the table
which
     would work just fine,
     it truncates the table and repopulate it.  The programmer
said
     it is faster that way,
     can you explain why?

     Thanks
     Gojo
and we said...
Well, if they were going to update every row anyway and could
live with the fact the table would be unavailable during the
reload -- this will be faster and less resource intensive.

A command like "UPDATE" will generate both Rollback (before) and
Redo (after) images.  If you update 10meg of data, you may
generate ~10meg of rollback (or more, indexes and such) and
~20meg of redo (or more).

If, on the other hand, you TRUNCATE the table -- no significant
rollback or redo is generated (small amount for dicitionary
managed tablespaces, virtually nothing for locally managed
tablespaces).  If you reload using the direct path loader in
unrecoverable mode or a direct path INSERT /*+ APPEND */, you
can avoid again the rollback and redo on the subsequent load
operation as well.

So, it is the fact they are bypassing all rollback and redo
generation that this will be faster.  It should be noted that
truncate is very non-selective -- you either truncate every row
or you do not.  You cannot have a where clause with a truncate.
June 14, 2000 Sanjay -- Thanks for the question regarding "Connection from client to oracle 7.3 without giving the database name", version 2000 version 1.6
You Asked
We are using oracle 7.3 and developer 2000 version 1.6 . I have
always noticed that to connect from the client site i need to
give the username/password@databasename. To the best of my
understanding we can aovid the entry of the database name by
setting some local variable like "local_database". could u help
me in this issue.

Secondly for the past couple of days we are geting an error
insufficient SGA memory. I am sure some process is going to an
endless loop or some stupid thing is happening with the database
procedures. Is there any way in which i can find out the process
that are running and the amount of SGA each database process is
consuming.

Sanjay
and we said...
The first part is achieved by setting the registry variable

LOCAL = tns_connect_string

in the registry.  Find the key for the oracle software and put
this into the key for the oracle_home that contains the d2k
softare.

For the second part, the query:

select c.username, a.sid, b.name, round( a.value/1024/1024, 1 )
  from v$session c, v$sesstat a, v$statname b
 where a.STATISTIC# = b.STATISTIC#
   and c.sid = a.sid
   and b.name like 'session%mem%'
   and c.username is not null
 order by 1,2,3
/

will give you that information.
June 15, 2000 lalitha -- Thanks for the question regarding "privileges to one procedure in a package", version 8.0
You Asked
Hi Mr Tom,
         If I give an execute privilege to a package the
particular user will have privileges to all the procedures
 in the package.Is there any way I can  give privileges only to
some procedures within a package ?

Thanks,
Lalitha
and we said...
No there is not.  Grants are done at the object level, not at
the subobject level.

What you would do in this case is either:

o break the package into 2 packages to give you the granularity
you need.

or

o simply create a small "stub" standalone procedure that calls
the packaged procedure for you.  This stub would look like:

  create or replace procedure p( <same inputs as pkg'ed proc> )
  as
  begin
     package.p( <parameters );
  end;

you can grant on P to anyone (and still use the package as you
do now)
June 15, 2000 -- Thanks for the question regarding "Query Tuning -- question on top 10 buffer get percentage", version 7.3.4
You Asked
***Code from Oracle Performance Tuning Tips & Techniques
- Richard J Niemiec

set serveroutput on
Declare
  cursor c1 is
  SELECT buffer_gets
    FROM v$sqlarea
  ORDER BY buffer_gets DESC ;
  cursor c2 is
  SELECT sum(buffer_gets)
    FROM v$sqlarea ;

sumof10  Number:= 0;
mybg     Number:= 0;
mytotbg  Number:= 0;

Begin
dbms_output.put_line('Percent');
dbms_output.put_line('-------');

Open c1 ;
for i in 1..10 loop
    fetch c1 into mybg ;
    sumof10 := sumof10 + mybg ;
end loop ;
close c1 ;
open c2 ;
fetch c2 into mytotbg ;
close c2 ;
dbms_output.put_line(round((sumof10/mytotbg*100),2));
End;
/

" Top Memory Abusers as a Percent of all Statements"
Percent
-------
87.93

The Question is the above percentage bad ?
Will it affect the queries running against the database ?
or does it not affect at all ?

Thanks in advance .
and we said...
The answer is:  insufficient data to arrive at a conclusive
answer.

The only thing the above percentage tells you is that the 10
queries with the MOST cumulative buffer gets have done 88
percent of your buffer gets.

Is that bad?  Well, it depends on...

o how many items do you have in your sqlarea.  the more then
have, the lower you might expect this percentage to be.  In a
well tuned system, with maximal use of shared sql, this
percentage could be very high (as you have fewer sql statements
floating around).  On the other hand, if you have 10's of
thousands of sql statements in the shared pool, this high
percentage might be a flag (but then again, if you have 10's of
thousands of queries in the shared pool you've probably forgot
to use bind variables and your tuning lies in that direction
first!)

o how many times are those queries executed (especially in
respect to how many times other queries are executed).  I would
rather tune the query that is executed 10 times and hits
1,000,000 buffers (100,000 buffer gets/query on avg) rather
then tune the query that is executed 1,000 times and hits
2,000,000 buffers (2,000 buffer gets/query on avg).

o whether you consider buffer gets a bad thing.  sometimes they
are unavoidable.

By itself, this number is rather meaningless in my opinion.  You
might use it to look at queries that take alot of resources but
you really need to consider how many statements you have, the
number of times these "bad" ones are actually executed and so
on.  Each query must be looked at in isolation then.  There is
no threshold I am aware of you want to be hitting with this.
June 15, 2000 sijo -- Thanks for the question regarding "procedure,fn &packages -- whats the main difference between standalone procedures and packages", version 7.x,8.x
You Asked
hi tom,
thanx for ur last answer,
can u tell me the main difference between procedures,functions &
packages with eg;
and we said...
One of the biggest differences is in the handling of
dependencies between procedures that call each other and what
happens when you recompile a procedure/function.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:286816015990
for a detailed discussion of that.

Another is the fact that packages can maintain a state, can have
"global variables".  If I have a package such as:

create package my_pkg
as
   procedure foo;
end;
/

create package body my_pkg
as
   number_of_times_called number default 0;

   procedure foo
   is
   begin
       number_of_times_called := number_of_times_called+1;
       ....
   end;
end;
/

I can maintain a "state" in the server for my session (that
variable is specific to MY session, no one else will see my
variable)....

Another big thing is in reducing the size of your namespace.
Lets say you have 20 procedures -- 10 of which only YOU call and
10 of which others are allowed to call.  If I used standalone
procedures, I would have to expose 20 procedures in the data
dictionary.  With a package -- I can expose 1 thing in the data
dictionary and only let 10 of the procedures be known outside of
the package (in other words, they support encapsulation).  for
example:

create package my_pkg
as
  procedure p1;
  procedure p2;
end;
/
create package body my_pkg
as
   procedure internal_proc1
   is
     ...

   procedure p1
   is
     ...

   procedure p2
   is
     ....
end;
/

Another is that packaged procedures/functions can be overloaded
whereas a standalone procedure cannot be, for example:

create package my_pkg
as
   procedure p( x in number );
   procedure p( x in varchar2 );
   procedure p( x in date );
end;
/

There I have 3 versions of P.  Each will be called based solely
on the input data passed to it.  Very handy....

Another is that packages can have "elaboration code" or startup
code.  This is code that is executed the very first time a
package is executed and can be used to default package variables
with complex values.  For example:

create or replace packgage my_pkg
as
   procedure p;
end;
/
create or replace package body my_pkg
as
   g_some_value   varchar2(255);

   procedure p
   is
   begin
      ....
   end;

begin
   select C into g_some_value from T where .....;
end;
/

that little begin/end block at the end will be run immediately
before P is invoked for the first time -- making it so I don't
have to put something like:

   if ( not_initialized ) then
      select C into ....
      not_initialized := FALSE;
   end if;

in procedure P (and any other procedure in my_pkg)....
Review & Followup
Rating: 5
March 13, 2001
Reviewer: Brenda Telford from Welland, ON CANADA

Rating: 3
August 02, 2001
Reviewer: Pichaimani from San Jose, CA, USA

Rating: 5
April 10, 2002
Reviewer: Marianne from Nice, France
Very useful answer, as the others available on the site ! Detailed and most of
the times with an example. Thanks a lot !

June 15, 2000 Shrikanth -- Thanks for the question regarding "foms and reoprts 6i -- what versions of Oracle does it work with", version 6i
You Asked
hi tom

does the devlpoer rel 6i work only on oracle 8i database or it
work on on 7.x or 8.x databases

thanx once again
shrikanth
and we said...
Developer 6i is supported against:

Oracle7, 7.3.4 only
Oracle8
Oracle8i
June 15, 2000 Ambarish -- Thanks for the question regarding "granting rights on objects in others schema", version 7.3 onwards
You Asked
Is it possible for the DBA to grant priviliges on objects
exisiting in
another user's schema ?

I log in as system/manager and do this:

grant select on scott.dept to cluser;

I get an error message saying insufficient privileges.

Thanks in advance for any help
and we said...
In order for this to work directly, using a simple "grant select
on scott.dept to cluser", SCOTT would have needed to have
granted:

SQL> grant select on dept to SYSTEM with grant option;

Now, a DBA has lots of powerful privileges - among them are:

o create any procedure
o execute any procedure

since by default a procedure executes as the "owner", we can use
that to our advantage if we are in a pinch and really need to
grant on someone elses objects. (no, this is not a bug, not a
hole -- this is a direct side effect of having the incredibably
POWERFUL privileges listed above).

If a user has "CREATE ANY PROCEDURE" and "EXECUTE ANY PROCEDURE"
(eg:a DBA), the following script works well:

---------------------------------------------------------------
rem 1 = OWNER OF OBJECT
rem 2 = OBJECT NAME
rem 3 = PRIV to grant
rem 4 = WHO to grant to

show user

create procedure &1..dba_parse_$$( p_cur in number, p_str in
varchar2 )
as
begin
    dbms_sql.parse( p_cur, p_str, dbms_sql.native );
end;
/

column grantee format a8
column grantor format a8

select grantee, grantor, privilege from dba_tab_privs
where owner = upper('&1') and table_name = upper('&2')
/

declare
    exec_cursor     integer default dbms_sql.open_cursor;
    rows_processed  number  default 0;
    sql_stmt        varchar2(255);
begin
    sql_stmt := 'grant &3 on &1..&2 to &4';
    &1..dba_parse_$$( exec_cursor, sql_stmt  );
    rows_processed := dbms_sql.execute(exec_cursor);
    dbms_sql.close_cursor( exec_cursor );
end;
/

select grantee, grantor, privilege from dba_tab_privs
where owner = upper('&1') and table_name = upper('&2')
/

drop procedure &1..dba_parse_$$;
-------------------------------------------------------------

You would run it as such:

SQL> @dogrant scott emp all public

user is "TKYTE"
old   1: create procedure &1..dba_parse_$$( p_cur in number,
p_str in varchar2 )
new   1: create procedure scott.dba_parse_$$( p_cur in number,
p_str in varchar2
)

Procedure created.

old   2: where owner = upper('&1') and table_name = upper('&2')
new   2: where owner = upper('scott') and table_name =
upper('emp')

no rows selected

old   6:     sql_stmt := 'grant &3 on &1..&2 to &4';
new   6:     sql_stmt := 'grant all on scott.emp to public';
old   7:        &1..dba_parse_$$( exec_cursor, sql_stmt  );
new   7:        scott.dba_parse_$$( exec_cursor, sql_stmt  );

PL/SQL procedure successfully completed.

old   2: where owner = upper('&1') and table_name = upper('&2')
new   2: where owner = upper('scott') and table_name =
upper('emp')

GRANTEE  GRANTOR  PRIVILEGE
-------- -------- ----------------------------------------
PUBLIC   SCOTT    ALTER
PUBLIC   SCOTT    DELETE
PUBLIC   SCOTT    INDEX
PUBLIC   SCOTT    INSERT
PUBLIC   SCOTT    SELECT
PUBLIC   SCOTT    UPDATE
PUBLIC   SCOTT    REFERENCES

7 rows selected.

old   1: drop procedure &1..dba_parse_$$
new   1: drop procedure scott.dba_parse_$$

Procedure dropped.

SQL>
===============================================================

that shows that it worked (the grants were in fact given)
without logging in as the other user.
Review & Followup
Rating: 5
grant to other schema May 29, 2001
Reviewer: Alejandro Camacho from Bogota, Colombia
Very useful. thanks

Rating: 4
Doesnt it work in 9i July 03, 2003
Reviewer: jianhui from DC
FYI:
I can do grant of other's object to another user in 9i , but not in 8.1.7

It seems it was a design problem in previous versions, so in 9i , DBA is more
like a real DBA now.

June 15, 2000 Daniel -- Thanks for the question regarding "OR set operatioon", version 80521
You Asked
Tom,

I have an update statement like:

update ...
set ...
where col1 = subquery1
      OR
      col2 = subquery2

And I know multiple rows will be updated by this statement.

My question here is how Oracle really does the updates,
row by row or one update operation updates a set of rows.

If Oracle updates row by row then how you compare this with a
PL/SQL updates loop in terms of performance;

If one update operation updates a set of rows then Oracle still
has to check the where clause row by row. In this case, why
Oracle does not do the updates row by row;

If Oracle checks the where clause conditions row by row then how
Oracle handles the subueries within it;

Finally, I know that Oracle converts an OR operation to two
equivelent union statements for a SELECT statement. How about
the UPDATE statement here?

Basically, I want to know what I am missing here and how Oracle
works with this type of statements.

Thanks,
Daniel Wang
and we said...
Not enough information to answer this one. It could go either
way.  Consider this example:

ops$tkyte@8.0> create table t ( x int, y int, z int );
Table created.

ops$tkyte@8.0> create index y_idx on t(y);
Index created.

ops$tkyte@8.0> create index z_idx on t(z);
Index created.

ops$tkyte@8.0>
ops$tkyte@8.0> set autotrace on explain
ops$tkyte@8.0> update T
  2     set x = x + 1
  3   where y = ( select 5 from dual )
  4          or z = ( select 6 from dual )
  5  /

0 rows updated.

Execution Plan
----------------------------------------------------------
   0      UPDATE STATEMENT Optimizer=CHOOSE
   1    0   UPDATE OF 'T'
   2    1     CONCATENATION
   3    2       TABLE ACCESS (BY INDEX ROWID) OF 'T'
   4    3         INDEX (RANGE SCAN) OF 'Z_IDX' (NON-UNIQUE)
   5    4           TABLE ACCESS (FULL) OF 'DUAL'
   6    2       FILTER
   7    6         TABLE ACCESS (BY INDEX ROWID) OF 'T'
   8    7           INDEX (RANGE SCAN) OF 'Y_IDX' (NON-UNIQUE)
   9    8             TABLE ACCESS (FULL) OF 'DUAL'
  10    6         TABLE ACCESS (FULL) OF 'DUAL'

There the plan shows that the subquery is evaluated and then
we use the indexes to access only the rows that will be updated
in T and update them.  In other words -- we updated a subset
identified by the index, we did not full scan T and see if we
needed to update each row

ops$tkyte@8.0> update T
  2     set x = x + 1
  3   where y = ( select 5 from dual where dummy = to_char(y) )
  4      or z = ( select 6 from dual where dummy = to_char(z) )
  5  /

0 rows updated.

Execution Plan
----------------------------------------------------------
   0      UPDATE STATEMENT Optimizer=CHOOSE
   1    0   UPDATE OF 'T'
   2    1     FILTER
   3    2       TABLE ACCESS (FULL) OF 'T'
   4    2       TABLE ACCESS (FULL) OF 'DUAL'
   5    2       TABLE ACCESS (FULL) OF 'DUAL'

Here, on the other hand, since we used a co-related subquery,
we find that it actually processed the update much like this
psuedo code:

   for C in ( select * from T for update ) loop
      if ( c.y = (that select)
           or
           c.z = (that other select) )
      then
           update t set x = x+1 where current of ...
      end if;
   end loop

ops$tkyte@8.0> set autotrace off

So, it depends.  It has the ability to do the same things in an
UPDATE as it does in a select as far as query optimization goes.
June 15, 2000 V Siva -- Thanks for the question regarding "Discrete Transaction", version 7.3.2.3.0
You Asked
Hi Tom

Can u explain me what is a discrete Transaction. What are the Other types of
transactin?

And What is the link between a discrete transaction's commit and the redo log
information, i.e., what Oracle will do during this commit?

Thanks
Siva
and we said...
Discrete transactions are described in:
http://technet.oracle.com/doc/server73x/SCN73/ch12.htm#toc097
beside descrete transactions, the only other transaction type (besides the
"standard" one) is an autonomous transaction.  They are new in Oracle8i.  You
can read about them at
http://osi.oracle.com/~tkyte/autonomous/index.html
...
June 15, 2000 VIMAL -- Thanks for the question regarding "Need more details about Advantages of Database Procedure", version 8.1.6
You Asked
Hi,

I'm working as a new DBA at one of our client sites.
Here front end application is wrtten in VB. They are using lots
of embaded SQL. Database group is pushing to move all the
embaded SQL to Database procedures,functions and db triggers.Are
you aware of any technical documentaion/white papers explaining
advantages of
Database procedures over EMBADED SQL. The development folks need
something like that.My explanation is not enough to change their
mind. Please help me.

Thanks

VK
and we said...
See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a77069/01_oview.htm#1051
"advantages of plsql".

The one thing it does not mention that is worth the move to
stored procedures (whether you want to write them in java or
plsql) is the ease of maintenance.  Lets say you discover a
query is in error and needs to be fixed (or tuned).  In the
existing model, you would update the VB code, rebuild the
application, redeploy it to lots of desktops.  If, on the other
hand, they used stored procedures that returned result sets (see
http://osi.oracle.com/~tkyte/ResultSets/index.html
for some good examples including VB of how that works), you
could update a stored procedure and your application is fixed.
This is HUGE, this is big, this is the number one reason to do
this.

You lose NO functionality, you gain alot (of control, of tuning
ability, of security -- right now, if your end users grab some
ODBC tool -- they are in and doing to your data what your
application does to it -- inserting, updating, deleleting -- if
they want to!!)
June 16, 2000 Vinod -- Thanks for the question regarding "Getting Value to a Unix Variable From Oracle Using Korn Shell Script", version Ora 7.3.4
You Asked
Hi Tom, I am using Korn shell. My question is that how can i
retrieve a value from a Oracle table and assign that value to a
shell variable.

(eg)

#!/bin/ksh
temp_batch()
{
ABC=ANIL;
echo $ABC
sqlplus dw_dev/rainbow <<+
DECLARE
  A VARCHAR2(10);
BEGIN
  SELECT 'VINOD' INTO A FROM DUAL ;
'ABC':=A ; -- Here i want to assign the value of the pl/sql
variable A to the Shell variable ABC
END;
/
+
}

Awaiting for ur reply.

Regds
Vinod
and we said...
Try:

#!/bin/ksh

ABC=ANIL;
echo $ABC

ABC=`sqlplus scott/tiger <<+ | grep '^-' | sed 's/-//'
set serveroutput on
DECLARE
  A VARCHAR2(10);
BEGIN
    SELECT 'VINOD' INTO A FROM DUAL ;
    dbms_output.put_line( chr(10) || '-' || A );
END;
/
exit
+`
echo $ABC
===========================================================

(those are backticks around `sqlplus ..... and +`)
Review & Followup
Rating: 5
Getting Value to a Unix Variable From Oracle Using Korn Shell Script May 14, 2003
Reviewer: Jim Brooks from Honolulu, Hi. USA
thanks !!! I was using this archaic spool to file and grep method until I found
this on your website ...

June 16, 2000 Vimal -- Thanks for the question regarding "Oracle Application Server (4.0.8.1)", version 4.0.8.1
You Asked
Hi Tom,

Can we call a  PL/SQL cartiridge from a stand alone application
(for e.g. C application), in other words can a client browser be
replaced by a stand alone C program ? If so then how ?

Regards
Vimal
and we said...
Yes, in at least 2 ways.

One, all the PLSQL cartridge does is connect to the database and
run a stored procedure.  You have the ability to do that
yourself -- you can connect to the database using OCI or Pro*C
and run the stored procedure.

Two, you can open a socket to the webserver -- do an HTTP GET
request and retrieve the output.  I have a very simple C api I
wrote up to do such a thing (you would have to bullet proof the
code).  It works with this structure and API:

#ifndef _WWW_GRAB_
#define _WWW_GRAB_

typedef struct tag_www_page
{
    int     status;
    /* HTTP Status code, always filled in */

    char    statusMsg[255];
    /* HTTP Status msg, always filled in  */

    char    contentType[255];
    /* Content Type, check for NULL       */

    int     contentLength;
    /* Content Length, always filled in   */

    char    * content;
    /* Content itself, check for NULL     */
    /* Use Content length for size, NOT   */
    /* NULL TERMINATED!!!                 */

    int     totSize;
    /* Original size, used internally     */

    char    header[1];
    /* HTTP Header, always filled in      */
}
    www_page;

www_page * get_url( char * url );

www_page * get_url_via_proxy( char * proxy, char * url );

#endif

And the source code is:
==================== www_grab.c ============================

include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>

#include "stdio.h"
#include "errno.h"

#include "www_grab.h"
void writeto( int sock, char * string )
{
    write( sock, string, strlen(string) );
    printf( "%s", string );
}

static void parse_header( www_page * thePage )
{
char    * cp;
char    * eol = "\n";
int        eol_len = 1;
char    dbl_eol[10];
char    tmp[255];

    if ( strncmp( thePage->header, "HTTP/", 5 ) )
    {
        thePage->status = -1;
        strcpy( thePage->statusMsg, "Unable to find HEADER" );
        return;
    }

    cp = strchr( thePage->header, '\r' );
    if ( cp && cp < strchr( thePage->header, '\n' ) )
    {
        eol = "\r\n";
        eol_len = 2;
    }
    sprintf( dbl_eol, "%s%s", eol, eol );

    cp = strstr( thePage->header, dbl_eol );

    if ( !cp )
    {
        thePage->status = -1;
        strcpy( thePage->statusMsg,
                "Unable to find data after header" );
        return;
    }

    cp += eol_len;
    *cp = 0;
    cp += eol_len;

    thePage->contentLength = thePage->totSize -
                             (cp-thePage->header+1) + 1;
    thePage->content       = cp;

    cp = strstr( thePage->header, eol );
    strncpy( tmp, thePage->header, cp-thePage->header+1 );
    tmp[cp-thePage->header+1] = 0;

    strtok( tmp, " " );
    thePage->status = atoi( strtok( NULL, " " ) );
    strcpy( thePage->statusMsg, strtok( NULL, "" ) );

    sprintf( tmp, "%sContent-Type: ", eol );
    cp = strstr( thePage->header, tmp );
    if ( cp )
    {
        strncpy( tmp, cp+strlen(eol)+strlen("Content-Type: "),
                      sizeof(tmp)-1 );

        tmp[sizeof(tmp)-1] = 0;
        cp = strstr( tmp, eol );
        if ( cp )
        {
            *cp = 0;
            strcpy( thePage->contentType, tmp );
        }
    }
}

static www_page * process( char * hostName, int portNo,
                           char * url )
{
int            sock;
char        *cp;
int            n;
int            i;
struct         sockaddr_in    name;
struct        hostent        * hent;
char        buffer[4096];
int            first;
www_page    * thePage;
int            one = 1;

    thePage = (www_page *)malloc( sizeof(www_page) );
    memset( thePage, 0, sizeof(www_page) );

    sock = socket( AF_INET, SOCK_STREAM, 0 );
    setsockopt( sock, SOL_SOCKET, SO_OOBINLINE,
                (void*)&one, sizeof(one) );

    if( (hent = gethostbyname( hostName )) == 0 )
    {
        thePage->status = -1;
        strcpy( thePage->statusMsg, strerror( errno ) );
        return thePage;
    }

    name.sin_port = htons( portNo );
    name.sin_family = AF_INET;
    name.sin_addr.s_addr = (u_long) *
                       (u_long *)hent->h_addr_list[0];

    sprintf( buffer, "GET %s HTTP/1.0\r\n", url );
    printf( "%s", buffer ); fflush(stdout);

    printf( "connecting to %s\n", hostName ); fflush(stdout);
    if( !connect( sock,
                  (struct sockaddr *)&name, sizeof(name) ) )
    {
        printf( "connected to %s\n", hostName ); fflush(stdout);
        write( sock, buffer, strlen(buffer) );
        write( sock, "\r\n", strlen("\r\n") );

        while( (n=recv( sock, buffer,
                         sizeof(buffer)-1, 0 )) > 0 )
        {
            thePage = (www_page*)realloc( thePage,
                    sizeof(www_page)+thePage->totSize+n+5 );
            memmove( thePage->header+thePage->totSize,
                     buffer, n );
            printf( "%.*s\n", n, buffer );
            thePage->totSize += n;
            printf( "#" ); fflush(stdout);
        }
        parse_header( thePage );
    }
    else
    {
        thePage->status = -1;
        strcpy( thePage->statusMsg, strerror( errno ) );
    }

    return thePage;
}

www_page * get_url( char * url )
{
char        * url_copy = strdup( url );
char        * protocol;
char        * hostName;
char        * portNo;
char        * path;
char        * realPath;
int            realPort;
www_page    * thePage;

    protocol = strtok( url_copy, ":" );
    hostName = strtok( NULL, "/" );
    path     = strtok( NULL, "" );
    strtok( hostName, ":" );
    portNo   = strtok( NULL, "" );

    realPath = (char *)malloc( path? strlen(path)+5 : 5 );
    sprintf( realPath, "/%s", path?path:"" );
    realPort = portNo ? atoi( portNo ) : 80;

    thePage = process( hostName, realPort, realPath );

    free( url_copy );
    free( realPath );

    return thePage;
}

www_page * get_url_via_proxy( char * proxy, char * url )
{
char        hostName[255];
char        * portNo;
int            realPort;

    strcpy( hostName, proxy );
    strtok( hostName, ":" );
    portNo   = strtok( NULL, "" );
    realPort = portNo ? atoi( portNo ) : 80;

    return process( hostName, realPort, url );
}

================== eof ====================================

an example using this api, a simple command line page grabber
is:

------------------------ test.c --------------------------

#include "stdio.h"
#include "www_grab.h"

main( argc, argv )
int    argc;
char *    argv[];
{
www_page    * thePage;
FILE * tmp;

    if ( !argv[1] )
    {
        printf( "usage: %s
http://.../n
 argv[0] );
        printf( "       %s proxy-server
http://../n
 argv[0]);
        exit(1);
    }

    if ( !argv[2] )
    {
        thePage = get_url( argv[1] );
        printf( "Gotten directly\n" );
    }
    else
    {
        thePage = get_url_via_proxy( argv[1], argv[2] );
        printf( "Gotten via proxy\n" );
    }

    printf( "Status:         %d\n", thePage->status );
    printf( "StatusMsg:      %s\n\n", thePage->statusMsg );

    if ( thePage->status > 0 )
    {
        printf( "Content-Length: %d\n",
                  thePage->contentLength );
        printf( "totSize       : %d\n\n", thePage->totSize );

        printf( "Header        : \n%s\n\n", thePage->header );

        tmp = fopen( "test.dat", "wb" );
        if ( tmp )
        {
            fwrite( thePage->content, 1,
                    thePage->contentLength, tmp );
            fclose( tmp );
        }
    }
}
----------------------- eof ---------------------------------

I've gotten this to run on many Unixes (and even NT, minor mods
-- email me if you need that one)....
June 16, 2000 Reji -- Thanks for the question regarding "orapw file", version 8.1.6
You Asked
Tom:
    I am trying to create a DB using a script and at the end
    of the DB creation and it is complaining about "can't read
    orapw from $ORACLE_HOME/dbs directory.

    Would you please let me know who creates this file?  and
    Do I have to create this file before the oracle db creation?

   TIA
   Reji
and we said...
orapwd is the command to create this file.  It needs to exist if
certain init.ora parameters are set (remote_login_passwordfile
for example).

$ orapwd

Usage: orapwd file=<fname> password=<password> entries=<users>

  where
    file - name of password file (mand),
    password - password for SYS and INTERNAL (mand),
    entries - maximum number of distinct DBA and OPERs (opt),
  There are no spaces around the equal-to (=) character.
June 16, 2000 Hector -- Thanks for the question regarding "PL/SQL vs 3GL langage performance", version 8.1.5
You Asked
My customer is suprised by the comparison of Pro*C vs. a PL/SQL
stored procedure.

They are selecting 20,000 rows 9 bytes / row in each case.

Case 1) Pro*C with embedded SQL cursor compiled to C fetching
20,000 rows all at once (this is not an anonymous block).

Case 2) Pro*C with an embeded SQL anonymous block containing
a call to a PL/SQL stored package.procedure which uses a
bulk collect into a cursor to pass back all 20,000 rows at once.

The performance shown in TKPROF is .16 CPU for case 1 and
.77 CPU for case 2.

Is this kind of (poor) performance (of PL/SQL) to be expected?

Is PL/SQL truely compiled when stored in the database or is it
interpreted?

I just wanted an expert to confirm that what is happening is
expected or that we have some tuning issues to explore.
and we said...
Its not that PLSQL is performing poorly here -- its that the
implimentation that uses PLSQL is adding lots of totally
unnecessary code.

In the first case, you have Pro*C doing a massive array fetch --
so its:

  Pro*C -> dedicated server -> database

You are doing virtually nothing in the dedicated server beyond
reading data and blowing it back to the client.

In the second case, you have Pro*C binding to huge arrays of
data that PLSQL had to allocate memory for, manage the storage
of and move the data into and then out of.  (not to mention that
the anonymous block had to be compiled and all as well).  That
PLSQL layer in the middle -- in effect did nothing.  It added no
value and just ate CPU time (most of it in doing really big
memmoves and mallocs probably).  Its runtime was just added to
the sql trace.  It moved lots of data from point A to point B
and from point B to point C -- it should not have been there.

If someone was to tell me they needed to return a result set of
20k rows from a stored procedure, I would not even dream of bulk
collecting into arrays and passing the arrays back to the client
(the memory that must have allocated on the server, the overhead
that introduced -- for nothing).  I would have gone immediately
to a REF CURSOR (see
http://osi.oracle.com/~tkyte/ResultSets/index.html
for examples of using them).  That is the correct and proper way
to return a result set from a stored procedure.

I would never dream of bulk collecting (or even array fetching)
20k rows at a time.  I believe you'll find the pro*c program to
go much faster with an array size of around 100.  In fact, with
Pro*C in Oracle8i, you should just set the "prefetch=100" on the
precompile line and do away with Array fetching alltogether --
we implement it under the covers for you. In this manner, you'll
avoid the issues of having to have large arrays laying around
but get all of the advantages of having array fetches (that and
you can easily play with different array sizes without mucking
around with the code).

PLSQL in the server is run in much the same fashion as Java is
run anywhere.  PLSQL is compiled into PCode and the PCode is
interpreted at runtime.  I do lots with PLSQL (a whole lot).
When used properly, it flies....  When not -- it'll be slow.

Try the test with a ref cursor to see how much overhead a PLSQL
routine would add in the real world.
June 16, 2000 V Siva -- Thanks for the question regarding "Standby database -- what is it", version 7.3.2.3.0
You Asked
Hi Tom,

I want to know what is a standby database. What is it's use/purpose of creation.

Thanks
Siva
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:199412348073
here is an extract from the full support note at that link that details how to
do the standby datbase in v7.3

    Standby Database Feature of ORACLE7 Version 7.3

Introduction
============
The objective of the Standby Database feature is to support the
capability of maintaining a duplicate, or standby, database of a primary, or
on-line, database for recovering from disasters at the production site.  Standby
Database consists of an external interface and checks within the  Oracle7 kernel
code to detect and correct data corruption situations. This paper describes the
design concepts and external interfaces of the  Standby Database
feature.
June 16, 2000 Prakash -- Thanks for the question regarding "Findind SQL Statements involved in Transaction", version 8.0.3
You Asked
Hi  Tom
Can you tell me How can I find out all Sql statements involved
in a transaction by a session.

V$SQLArea & V$SQLTEXT views allows selection of SQL statements
for a particular User.

But,  Actually I want to Find Out SQL Statements fired by a
SESSION (One user can have more than one session )

Prakash
and we said...
v$sqlare and v$sqltext can be used in conjunction with v$session
to find the sql a given user session is CURRENTLY executing.
They cannot be used to find all sql ever executed by a session.
Some SQL statment I executed may be aged out of the shared pool
and disappear from these views.  We do not track all of the sql
you have executed in a sesssion.

You can find the cursors they currently have open but that will
not be an exhaustive list of all cursors they may have used in
their session.  It will be indicative of what they are currently
doing.  The view V$OPEN_CURSOR will show you all of the cursors
they currently have open.

We can use v$session joined to v$sqlarea by ADDRESS will show
you the sql someone is currently executing by session.
June 16, 2000 Venkata -- Thanks for the question regarding "changing from 2k to 4k block size of an existing database", version 8.05
You Asked
I would like to migrate my 2k block size to 4k and like to
organise my files in different disks please advice.
Thanks giri
and we said...
The only way to do this (change a block size) is to build an
entirely new instance and export from the old database into the
new database (or copy the data in another fashion, the use of
exp/imp as a tool is optional).

The migration guide, which discusses how to do the exp/imp from
v7 to v8 -- is a good reference to use in this sort of a
migration.  It explains how you do this full database exp/imp.

See
http://technet.oracle.com/doc/server.804/a58243/migeximp.htm#6940
for more info.
June 16, 2000 Abhijit -- Thanks for the question regarding "Cost value in Explain plan -- well, if I can't use that what do I use?", version Oracle 8.0.5
You Asked
I have read one of your replies where you advised not to compare
cost of
two SQL queries even if they are closely similar. While I
understand you explanation of the cost factor, I would like to
ask
you the following question
Consider a hypothetical scenario, that you were requested to
look into an SQL query which is running slow. You executed an
Explain PLan to find out the query plan , to figure out if it is
doing
full table scan etc. You made certain improvements - may be by
adding
hints. How will you compare the performance of newly constructed
query
to the existing one ? Is there any technique for
doing that ? If yes, then will you please explain that.
Thanks
Abhijit Bhattacharya
and we said...
I use SQL_TRACE, Timed_statistics and TKPROF.  I use the actual
execution (run time) metrics observed during typical executions
of the query.

TKPROF will tell me what the execution plan was....
How many rows flowed through each step of the plan....
How many logical io's I did...
How many phyisical io's...
How long it took to parse the query..
To execute it...
To fetch from it...
How many rows I got...

and so on.  See
http://technet.oracle.com/doc/server.804/a58246/strace.htm#1018
which is the chapter on SQL_TRACE and TKPROF in the server
tuning manual....


Subject | Article | Last Updated (East coast time)
Re : Launching OEM on UNIX | article only | Jun 19, 2000 06:43 am
How to maintain the session ID in Pl/sql cartridge | article only | Jun 19, 2000 07:09 am
EXEC_SQL package | article only | Jun 19, 2000 07:36 am
a function to put a list in columns | article only | Jun 19, 2000 07:44 am
certification for windows 2000 | article only | Jun 19, 2000 10:08 am
Tabel I/O -- getting fileno from a rowid. | article only | Jun 19, 2000 03:18 pm
creating BFILE | article only | Jun 19, 2000 03:40 pm
Objects | article only | Jun 19, 2000 04:08 pm
EXEC_SQL or DBMS_SQL | article only | Jun 20, 2000 07:08 am
SQl*Loader Errors | article only | Jun 20, 2000 09:27 am
Oracle 8i migration utiliity - Multiplier | article only | Jun 20, 2000 09:34 am
Getting CD's -- OTN and the technology tracks | article only | Jun 20, 2000 12:15 pm
load data | article only | Jun 20, 2000 12:18 pm
Oracle Threads -- redo threads. | article only | Jun 20, 2000 02:46 pm
Oracle Archive -- | article only | Jun 20, 2000 02:55 pm
pl/sql and components -- getting result sets. | article only | Jun 20, 2000 07:50 pm
Killing a process ? | article only | Jun 21, 2000 08:25 am
Is Mutiple Type Creation possible in a single sql file? | article only | Jun 21, 2000 08:46 am
Poor performance using public synonyms | article only | Jun 21, 2000 09:08 am
How to run user interaction within a PL/SQL block_stored procedure or function? | article only | Jun 21, 2000 09:25 am
SQL*Loader Error 524 Partial Record found at end of datafile | article only | Jun 21, 2000 09:39 am
Tablespace in backup mode | article only | Jun 21, 2000 04:02 pm
SELECT stmt runs MUCH slower in anonymous block | article only | Jun 21, 2000 04:10 pm
Using Check constraints with varray types | article only | Jun 21, 2000 04:13 pm
INVALID_OPERATION | article only | Jun 21, 2000 04:21 pm
Logfile Status | article only | Jun 22, 2000 08:08 am
how to pass a tablename/column name into a procedure | article only | Jun 22, 2000 08:30 am
snapshot column length from 4000 to 2000 | article only | Jun 22, 2000 08:53 am
sys.user_lock pacakge | article only | Jun 22, 2000 08:57 am
SESSION's Privilege in SESSION_PRIVS table | article only | Jun 22, 2000 12:53 pm
EXTPROC_CONNECTION_DATA -- what is it | article only | Jun 22, 2000 02:11 pm
Delete database | article only | Jun 22, 2000 02:16 pm
syncronization in oracle - some recovery questions | article only | Jun 22, 2000 02:22 pm
error messaging system -- handling FRM-40510-UNABLE TO DELETE THE RECORD | article only | Jun 22, 2000 03:19 pm
Export/Import of a database -- how to ignore object creation errors | article only | Jun 23, 2000 09:11 am
Oracle Application Server on Windows 2000 | article only | Jun 23, 2000 09:32 am
Login in WebDB | article only | Jun 23, 2000 09:47 am
How to get the particualer date on every month | article only | Jun 23, 2000 09:50 am
Creating Objects in Oracle --ORA-00439: feature not enabled: Objects | article only | Jun 23, 2000 09:52 am
DISPLAY MESSAGES FROM STORED PROCEDURES ON THE FORMS5 | article only | Jun 23, 2000 09:55 am
row(s) 1 - 40 of 40
June 19, 2000 Vince Crismer -- Thanks for the question regarding "Re : Launching OEM on UNIX", version 8.0.5
You Asked
Greetings,

Hi there. How do I launch the OEM on a UNIX/LINUX machine. Is
there any OEM available for that platform? Thanks

- Vince Villena
and we said...
You would use the java version of OEM for this.  It (the GUI)
runs in a browser as java applets.  This is accomplished via OEM
2.x.  As far as I know though, you will need a Solaris Unix
server for a supported configuration.

Article-ID:         <Note:69384.1>

OEM 2.X Architecture
====================

Oracle Enterprise Manager V2 implements a new three-tier
architecture. This new architecture provides greater
availability and flexibility, enabling the console to be run
from a thin client and repository sharing between multiple
consoles.

Tier 1 - The Console:
---------------------

Like OEM 1.X, the console allows DBA administration to be
manipulated remotely from one machine. There are a few
additional features in OEM 2.0.4 and it has been rewritten from
C++ to Java.

The enhancements to the OEM 2.x console are:

- web-enabled console and DBA Management Packs. The Java-based
tools are capable of running on Windows/NT, Windows95,
Windows98, and now also on Sun Solaris 2.6.

- OEM 2.x repository information may be shared across multiple
clients to multiple DBAs through the Oracle Management Server
(OMS).

- integrated applications are launched locally or downloaded as
a Java applet. These applications are known collectively as the
DBA Management Pack. They are essentially the same as in OEM 1.6
with a few additional features.

Tier 2 - The Oracle Management Server (OMS):
--------------------------------------------

This may be installed on an Windows/NT or Sun Solaris 2.6
server. One or more Management Servers must be configured to
manage the domain.

The OMS uses the OEM 2.X Repository to store all the system
data, application data and the state of the managed nodes
throughout the environment. The Repository is stored in a
database schema stored in any database accessible throughout the
network and contains a set of tables, view, and indexes. In OEM
version 2.x, the repository information may be shared.

Most services in version 2, such as the job and event systems,
are similar to the Common Services in version 1. However, these
services have been separated from the console in version 2 and
are started at the OMS.

The OMS allows:
  - access to domain information in the Repository from multiple
clients, allowing DBAs to share data
  - dispatching of the console requests
  - control of job execution
  - monitoring of events
  - notification of the results of the executed jobs and the
triggered events by email or by pager. (Paging Service is NT
specific.)

The use of multiple Management Servers provides:
  - a distribution of the load without any additional management
overhead
  - additional management resources to meet management demands
  - fault tolerance, where an OMS can assume the workload of
another OMS.

Third-tier: Managed Objects:
----------------------------

Managed objects could be network nodes, databases, listeners or
other Oracle services installed on those nodes.  An intelligent
agent is installed on each server node to execute jobs and
monitor events on the managed objects.

The Intelligent Agent is available for all Oracle supported
platforms. The latest Intelligent Agent version could be
installed in a separate ORACLE_HOME to take advantage of the new
features available, so there would be no pressure to upgrade the
database to use these features.

Note: the Intelligent Agent in OEM 2.0.4 is fundamentally the
same as in OEM v1.X. There is still only one Intelligent Agent
allowed per machine.
Review & Followup
Rating: 4
web-enabled console October 09, 2002
Reviewer: Abdal-Rahman Agha from Yemen
Hi Tom,

  I have oracle database 817 (Personal Edition) installed in W2K professional. I
have installed OMS also within it. At the end, I have installed Oracle
Enterprise Manager website, and I checked for the 'oem_webstage' directory and
it is there. the HTTP server is installed and running. Also OMS is running. My
host is 'agha.sanaa.yeman'. Then when I write the address '
http://agha.sanaa.yeman:80'/
in my browser
(ver.5.5),the index (EMWebSite.html) page did not appear. Instead, a page with
thw title 'Oracle HTTP Server
Components' comes. WHY?

June 19, 2000 Anuj -- Thanks for the question regarding "How to maintain the session ID in Pl/sql cartridge", version 4
You Asked
Hi Tom,
I would like to know how do we maintain session id in pl/sql
cartridge will developing web application through oracle web
appilcation server.

i just want to maintian the user session to check that the user
asking for any information, is the actual user who had already
logged through the username and password.
i would like to if u can give an example with the code for me to
understand.

the major problem we face is in maintaining session.
we actually want that the  user is not allowed to go directly to
any page except the 1st page(loggin page) by tying the complete
URL in the location bar

Incase of ASP we are able to maitian the session ID and can
check it through out the session by session object.

Thanks and regards
Anuj Chauhan
and we said...
You will either:

o pass a value from page to page.  this value is their session
id.

o use a cookie to pass a session id from page to page.

Here is an example using cookies.   This example is distributed
with OAS:

CREATE OR REPLACE PROCEDURE cookiejar
IS
     v_names owa_cookie.vc_arr;
     v_vals owa_cookie.vc_arr;
     v_num_vals INTEGER;
     v_cookie owa_cookie.cookie;
BEGIN

   -- Look for a cookie named "count"
   -- you would probably be looking for a cookie named
   -- "sessionid" or something similar
   v_cookie := owa_cookie.get('COUNT');

   -- Now, this shows how to set the cookie.  We have
   -- to produce the mime headers and then the cookie itself
   --
   -- this logic would ONLY be in your login routine (the
   -- logic to set the cookie).   All other pages would
   -- just use the line of code above (owa_cookie.get) to
   -- look for the existence of a cookie.
   owa_util.mime_header('text/html', FALSE);
   IF (v_cookie.num_vals > 0) THEN
      owa_cookie.send('COUNT', v_cookie.vals(1) + 1,
                               Sysdate + 1);
    ELSE
      owa_cookie.send('COUNT', 1, Sysdate + 1);
   END IF;
   owa_util.http_header_close;

   htp.htmlopen;
   htp.headopen;
   htp.title('C is for Cookie');
   htp.headclose;
   htp.bodyopen;

   htp.line;
   htp.img('/ows-img/ows.gif');
   htp.header(1,'C is for Cookie');
   htp.line;

   IF (v_cookie.num_vals > 0) THEN
      htp.print('You have visited this page ' ||
                  htf.strong(v_cookie.vals(1) + 1) ||
                ' times in the last 24 hours.');
    ELSE
      htp.print('This is the first time you
                 have visited this page in
                 the last 24 hours.');
   END IF;

   htp.line;
   htp.em('Each time you visit the page, the count will be
           incremented by one, as long as you are using a
           cookie enabled browser.  This state is kept in the
           browser in the form of a cookie, rather than
           having the server keep track of it.');

   htp.bodyclose;
   htp.htmlclose;
END;
/
June 19, 2000 Roger -- Thanks for the question regarding "EXEC_SQL package", version v6
You Asked
Hi Tom,

The question is to access two DBs simutaneous by EXEC_SQL
package with Oracle Forms.

I have a WHEN-BUTTON-PRESSED trigger to activate a package
called DS_CONNECT(.EXEC_CONNECTION),
but I can't sort out the  problem of 'ORA_06502' when press the
button.

Can you point what part in the package go wrong?

Cheers

Roger

Codes attached.

-- WHEN-BUTTON-PRESSED trigger
declare
    ret_value varchar2(12);
begin
       ds_connect.exec_connection1 (1,'sa/sa@ca',ret_value);
    :course.ca_id := ret_value;
end;

-- Package

PACKAGE ds_connect IS
  procedure exec_connection1 (caid IN number,
  connection_string IN VARCHAR2 DEFAULT NULL,
 l_ca_id out varchar2);
  END ds_connect;

package body ds_connect IS

  procedure exec_connection1 (caid IN number,
  connection_string IN VARCHAR2 DEFAULT NULL,
  l_ca_id out varchar2) IS

  connection_id EXEC_SQL.ConnType;
  cursor_number EXEC_SQL.CursType;
  sql_string  varchar2(200);
  ret           PLS_INTEGER;
BEGIN
    IF connection_string IS NULL THEN
  connection_id := EXEC_SQL.DEFAULT_CONNECTION;
ELSE
  connection_id :=
    EXEC_SQL.OPEN_CONNECTION(connection_string);
END IF;
cursor_number :=
   EXEC_SQL.OPEN_CURSOR(connection_id);

sql_string :='select col2 from rog_temp where col1=:ca';

EXEC_SQL.PARSE(connection_id, cursor_number,
sql_string,exec_sql.V7);
EXEC_SQL.DEFINE_COLUMN(connection_id, cursor_number, ':ca',
caid);
EXEC_SQL.DEFINE_COLUMN(connection_id, cursor_number, 1,
l_ca_id,12);

ret := EXEC_SQL.EXECUTE(connection_id, cursor_number);
ret:=EXEC_SQL.Fetch_Rows(connection_id, cursor_number);
EXEC_SQL.Column_Value (connection_id, cursor_number,1,l_ca_id);
-- return_value :=l_ca_id;
EXEC_SQL.CLOSE_CURSOR(connection_id, cursor_number);
EXEC_SQL.CLOSE_CONNECTION(connection_id);

EXCEPTION
  WHEN EXEC_SQL.PACKAGE_ERROR THEN
    TEXT_IO.PUT_LINE('ERROR (' ||
      TO_CHAR(EXEC_SQL.LAST_ERROR_CODE
       (connection_id)) || '): ' ||
      EXEC_SQL.LAST_ERROR_MESG(connection_id));
    IF EXEC_SQL.IS_CONNECTED(connection_id) THEN
      IF EXEC_SQL.IS_OPEN(connection_id,
        cursor_number) THEN
        EXEC_SQL.CLOSE_CURSOR(connection_id,
        cursor_number);
      END IF;
      EXEC_SQL.CLOSE_CONNECTION(connection_id);
    END IF;
END exec_connection1;

END ds_connect;

-- the source table
SQL> select * from rog_temp;

     COL1 COL2
--------- ------------
        1 AAAAAAAAAAA
        2 BBBBBBBBBBBB
and we said...
You are DEFINING when you should be BINDING.  Define is for OUT
variables.  BIND is for IN variables.

EXEC_SQL.DEFINE_COLUMN(connection_id,
                       cursor_number, ':ca', caid);
EXEC_SQL.DEFINE_COLUMN(connection_id, cursor_number, 1,
                       l_ca_id,12);

should be:

EXEC_SQL.BIND_VARIABLE(connection_id,
                           cursor_number, ':ca', caid);
EXEC_SQL.DEFINE_COLUMN(connection_id, cursor_number, 1,
                       l_ca_id,12);

You will have another problem next though and that is your
trigger always calls ds_connect with a NULL ret_value.  You will
bind NULL to :ca for the query:

    'select col2 from rog_temp where col1=:ca'

which will always select 0 rows (where col1 = NULL will never
every be true no matter what is in the table).  You Fetch_rows
but never check to see if you actually got one before calling
column_value.  This is an error as well -- you'll need to check
the return from fetch_rows to see if you can actually call
column_value first.
June 19, 2000 Vittorio -- Thanks for the question regarding "a function to put a list in columns", version 8i
You Asked
can i dinamically create from list (a,b,d,r,g,f) columns
containg the values ?

i mean

input

list
--------------
a,f,d,g,t,

output

col1  col2  col3  col4  coln
----------------------------
a     f     d     g     ....

thanks
and we said...
since a sql query must have a FIXED number of columns, you must
have some upper bound on this (eg: I will have no more then "6"
of these columns or "10" of these columns).

It can look like this:

ops$tkyte@8i> variable str varchar2(25)
ops$tkyte@8i>
ops$tkyte@8i> exec :str := 'a,b,c,d,e'

PL/SQL procedure successfully completed.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> select substr(:str,1,instr(:str||',',',')-1) C1,
  2             substr(:str,instr(:str||',',',',1,1)+1,
     instr(:str||',',',',1,2)-instr(:str||',',',',1,1)-1 ) C2,
  3             substr(:str,instr(:str||',',',',1,2)+1,
     instr(:str||',',',',1,3)-instr(:str||',',',',1,2)-1 ) C3,
  4             substr(:str,instr(:str||',',',',1,3)+1,
     instr(:str||',',',',1,4)-instr(:str||',',',',1,3)-1 ) C4,
  5             substr(:str,instr(:str||',',',',1,4)+1,
     instr(:str||',',',',1,5)-instr(:str||',',',',1,4)-1 ) C5,
  6             substr(:str,instr(:str||',',',',1,5)+1,
     instr(:str||',',',',1,6)-instr(:str||',',',',1,5)-1 ) C6
  7    from dual
  8  /

C1    C2    C3    C4    C5    C6
----- ----- ----- ----- ----- -----
a     b     c     d     e

ops$tkyte@8i> exec :str := 'how,now,brown,cow'

PL/SQL procedure successfully completed.

ops$tkyte@8i> /

C1    C2    C3    C4    C5    C6
----- ----- ----- ----- ----- -----
how   now   brown cow

If you would like to see a generic way to turn then into rows --
not columns, see:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:139812348065,%7BLIST%7D
for an example.  this is much more flexible as you do not have
to have an artificial limit of "6" or "10" (you can get as many
rows as you like).
June 19, 2000 fergus -- Thanks for the question regarding "certification for windows 2000 ", version financials 11.03
You Asked
is oracle financials certified for use windows 2000?
and what components does it require on the local machine?
e.g tnsnames.ora, intranet address, j-initiator etc

any information about this product and it's configuration would
be greatly appreciated
and we said...
I went to the product group with this question and as of June
19'th they say:

...
We are wrapping up the W2K certification for Release 11.0.3
(server side and middle tier).  It should be completed within 2
weeks.

The client-side (JInitiator) is not yet certified with Windows
2000, but may be by the end of this month.  The issue is with
JavaSoft, which is why we can't be more specific.

As far as what components are required on the local machine- it
is just another OS, like NT... so requires nothing different.
....

So, the answer is "not today but very shortly 11.0.3 will be
available on Win2k".
June 19, 2000 Jim -- Thanks for the question regarding "Tabel I/O -- getting fileno from a rowid.", version 8.1.5.1.1
You Asked
I would like to get the I/O for a given table.  I'm having
trouble relating the table to the file.  I can find the relative
file number on the rowid, but it is hex(?).  It looks like AAB.
The column datatype on dba_data_files are number.  How can I get
the filename from the rowid?

TIA,

Jim
and we said...
Well, tables don't relate directly to a file -- a row does not
related to a file either.  The rowid shows where the head piece
of the row is but the row itself, or part of the row, may be far
far away (in another file all together)...

The rowid is base64 encoded -- in Oracle7.x they are in hex.

There is the dbms_rowid package for breaking out the pieces, it
could look like this:

  1  select dbms_rowid.rowid_relative_fno(rowid),
  2*       dbms_rowid.rowid_to_absolute_fno(rowid,'SYS','DUAL')
from dual
ops$tkyte@8i> /

DBMS_ROWID.ROWID_RELATIVE_FNO(ROWID)
DBMS_ROWID.ROWID_TO_ABSOLUTE_FNO(ROWID,'SYS','DUAL')
------------------------------------
----------------------------------------------------
                                   1
                       1

that shows that SYS.DUAL has a row that starts in file #1.

You should really use a query against dba_extents to see the
file(s) a table might reside in (as tables can be in >1 file)

ops$tkyte@8i> select distinct file_id, relative_fno from
dba_extents where owner = 'SYS' and segment_name = 'DUAL';

   FILE_ID RELATIVE_FNO
---------- ------------
         1            1
June 19, 2000 Reji -- Thanks for the question regarding "creating BFILE", version 8.1.6
You Asked
Tom:
    How do I create a BFILE object and write data to it?

    -TIA
    -Reji
and we said...
BFILES are *read only*.  You do not write to a BFILE.

Here is how to store a bfile:

ops$tkyte@8i> create table demo
  2  ( id            int primary key,
  3    theBlob       bfile
  4  )
  5  /

Table created.

ops$tkyte@8i> create or replace directory my_files as
'/export/home/tkyte/public_html';

Directory created.

ops$tkyte@8i> insert into demo
              values ( 1, bfilename( 'MY_FILES', 'aria.gif' ) );

1 row created.

ops$tkyte@8i>
June 19, 2000 Vinnie -- Thanks for the question regarding "Objects", version 8.1.5
You Asked
If I create an object:

create person of type object
(name varchar2(40),
addr  varchar2(40));

How do I create a table using that object that looks like this?

ORDERS
ordno  number
name   varchar2(40)
addr   varchar2(40)
quant  number

Can I embed this object type into ORDERS so if I want to change
the object PERSON it automatically changed ORDERS?
and we said...
You do not -- you would (could) create a table that looks like:

ORDERS
ordno    number
orderer  PERSON
quant    number

you would have a table with three columns -- not 4.  name/addr
are not standalone attributes, they are a single entity.

Here is an example showing how to do the above and then how to
do this so if the PERSON instance changed, Orders would reflect
the change right away:

ops$tkyte@8i> create or replace type person as object
  2  ( name varchar2(40),
  3    addr varchar2(40)
  4  )
  5  /

Type created.

ops$tkyte@8i> create table orders
  2  ( ordno   number,
  3    orderer PERSON,
  4    quant   number
  5  )
  6  /

Table created.

So, that shows when you create a table with an object column
-- it has only one attribute.  Physically there will be all of
them but as far as SQL is concerned there is just one

ops$tkyte@8i>
ops$tkyte@8i> desc orders
 Name                             Null?    Type
 -------------------------------- --------
----------------------
 ORDNO                                     NUMBER
 ORDERER                                   PERSON
 QUANT                                     NUMBER

ops$tkyte@8i> drop table orders;
Table dropped.

Now we want to create the object so that if we update a
persons name or address -- it is reflected in orders.  In order
to accomplish this we must have a separate table of PEOPLE and
this table must be an OBJECT table so we can have a REF to it

ops$tkyte@8i> create table orders
  2  ( ordno   number,
  3    orderer REF PERSON,
  4    quant   number
  5  )
  6  /

Table created.

ops$tkyte@8i>
ops$tkyte@8i> create table people of person
  2  /

Table created.

ops$tkyte@8i>
ops$tkyte@8i> insert into people
              values ( person('tom','reston,va') );

1 row created.

ops$tkyte@8i> insert into orders
  2  (ordno,orderer,quant)
  3  values
  4  (1,(select ref(p) from people p where p.name='tom'),100);

1 row created.

That shows how we get a row into orders.  We insert a
SELECT...

ops$tkyte@8i>
ops$tkyte@8i> select ordno, deref(o.orderer) orderer, quant
  2  from orders o
  3  /

     ORDNO ORDERER(NAME, ADDR)              QUANT
---------- --------------------------- ----------
         1 PERSON('tom', 'reston,va')         100

ops$tkyte@8i>
ops$tkyte@8i> update people p set p.addr = 'herndon,va' where
p.name = 'tom'
  2  /

1 row updated.

ops$tkyte@8i>
ops$tkyte@8i> select ordno, deref(o.orderer) orderer, quant
  2  from orders o
  3  /

     ORDNO ORDERER(NAME, ADDR)              QUANT
---------- --------------------------- ----------
         1 PERSON('tom', 'herndon,va')        100

and that shows the update working as expected...
Review & Followup
Rating: 5
November 20, 2001
Reviewer: Helena Markova from Bratislava, Slovakia
Thank you for explanation.

June 20, 2000 Roger -- Thanks for the question regarding "EXEC_SQL or DBMS_SQL", version v6
You Asked
Hi Tom,
In Dynamic PL/SQL package (DBMS_SQL or EXEC_SQL in Forms), will
PL/SQL table_type be accepted as DEFINE_COLUMN parameter?
The question is raised for looking a solution on fetching multi
rows to a Form (Oracle Developer)
simutaneously by EXEC_SQL for multi-data source. I thought if a
PL/SQL table-type is usable, one
can easily fetch multi rows and present them at a time.
(I wolud be grateful if you have some better idea to achieve the
same goal.)
For your advice. Code attached.

Cheers

Roger

-- PL/SQL table defination
PACKAGE tab IS
  TYPE num IS TABLE OF NUMBER(10)
  INDEX BY BINARY_INTEGER;
  TYPE var IS TABLE OF VARCHAR2(30)
  INDEX BY BINARY_INTEGER;
END;

-- Trigger (WHEN BUTTON PRESSED)
declare
    ret_value TAB.NUM;
    sqlstr varchar2(100);

begin
    sqlstr :='select * from c_r where cr_id = :c1';
  ds_connect.exec_connection1
('sa/sa@CA',sqlstr,':c1',:course.cr_id,null,null,ret_value);

  FOR i in 0 .. ret_value.count Loop
    :course.ca_id(i) := ret_value(i);
  END LOOP;

end;

PACKAGE ds_connect IS
    procedure exec_connection1 (connection_string IN VARCHAR2
DEFAULT NULL,
      sql_string IN VARCHAR2,
                place_holder1 varchar2 default null,
              in_value1 IN NUMBER default null,
              place_holder2 varchar2 default null,
              in_value2 IN NUMBER default null,
              l_ca_id out tab.num);

END ds_connect;

package body ds_connect IS

    procedure exec_connection1 (connection_string IN VARCHAR2
DEFAULT NULL,
      sql_string IN VARCHAR2,
                place_holder1 varchar2 default null,
              in_value1 IN NUMBER default null,
              place_holder2 varchar2 default null,
              in_value2 IN NUMBER default null,
              l_ca_id out tab.num) IS

  connection_id EXEC_SQL.ConnType;
  cursor_number EXEC_SQL.CursType;
  ret           PLS_INTEGER;
  counter           PLS_INTEGER;

BEGIN
    IF connection_string IS NULL THEN
  connection_id := EXEC_SQL.DEFAULT_CONNECTION;
ELSE
  connection_id :=
  EXEC_SQL.OPEN_CONNECTION(connection_string);
END IF;
cursor_number :=
   EXEC_SQL.OPEN_CURSOR(connection_id);

EXEC_SQL.PARSE(connection_id, cursor_number, sql_string,
exec_sql.V7);
EXEC_SQL.BIND_VARIABLE(connection_id, cursor_number,
place_holder1, in_value1);
EXEC_SQL.BIND_VARIABLE(connection_id, cursor_number,
place_holder2, in_value2);

-- Here is the problem: wrong type or length.
EXEC_SQL.DEFINE_COLUMN(connection_id, cursor_number, 1,
l_ca_id,30);

ret := EXEC_SQL.EXECUTE(connection_id, cursor_number);

FOR I IN 0..ret loop
  counter:=EXEC_SQL.FETCH_ROWS(connection_id,cursor_number);
    if counter =0 then
     exit;
 EXEC_SQL.COLUMN_VALUE(connection_id,cursor_number, 1,
l_ca_id(counter));
END LOOP;

EXEC_SQL.CLOSE_CURSOR(connection_id, cursor_number);
EXEC_SQL.CLOSE_CONNECTION(connection_id);

EXCEPTION
  WHEN EXEC_SQL.PACKAGE_ERROR THEN
    TEXT_IO.PUT_LINE('ERROR (' ||
      TO_CHAR(EXEC_SQL.LAST_ERROR_CODE
       (connection_id)) || '): ' ||
      EXEC_SQL.LAST_ERROR_MESG(connection_id));
    IF EXEC_SQL.IS_CONNECTED(connection_id) THEN
      IF EXEC_SQL.IS_OPEN(connection_id,
        cursor_number) THEN
        EXEC_SQL.CLOSE_CURSOR(connection_id,
        cursor_number);
      END IF;
      EXEC_SQL.CLOSE_CONNECTION(connection_id);
    END IF;
END exec_connection1;

END ds_connect;
and we said...
The short answer is dbms_sql could, exec_sql cannot, however you
never want to use dbms_sql from forms.

The better answer in my opinion is to NEVER use dbms_sql in a
client side form (very very "chatty") and only use EXEC_SQL for
inserts/updates/deletes (use the easier forms_ddl for ddl).  If
you are going to do a select, the easiest and fastest method
would be record groups.  Record groups have the added bonus that
forms will ARRAY fetch into them to fill them up -- providing
for much faster response times then the single row fetches
provided by exec_sql.

A record group will behave much like a 2 dimensional array and
provides the functionality you are looking for above (in lots
less code).  You'll have to use a database link instead of >1
connection.
June 20, 2000 Ravinder -- Thanks for the question regarding "SQl*Loader Errors", version 8.1.5
You Asked
Hi Tom,

Sometime, I face the following error while loading data using
SQL*Loader

SQL*Loader-524 Partial Record found at end of datafile

I can't use load=????? in my load script , because I dont know
how many records will be there in the datafile,I am going to
load. How can I ignore the partial record and load the rest of
data.

Thanks

Ravi
and we said...
This is a bug in 8.0.5-8.1.5 sqlldr.  If the last line of the
input TEXT file does not have a newline, it will not work.

The work around is to add the missing newline to the datafile.
If you are are unix for example -- something like:

awk '{print $0}' < test.dat > test2.dat

will clean it up.  If test.dat is "big" and you don't want two
copies, you can:

$ mknod test2.dat p

(make a named pipe) and then:

$ awk '{print $0}' < test.dat > test2.dat &
$ sqlldr .... data=test2.dat ....

that is, sqlldr from the named pipe.  that way the file will
only really exist "once".
June 20, 2000 ams -- Thanks for the question regarding "Oracle 8i migration utiliity - Multiplier", version 8.1.5
You Asked
The migration program (8.1.5 on SUN ) MIG has a parm. called
Multiplier specifically for increasing the size
of i_file#_block#. The default is 1.5 times of V7 size.
How do we know if this is sufficient ?
What rule of thumb do we use to estimate how much bigger it
should be in
Oracle 8i ?
and we said...
The MULTIPLIER option specifies the initial size of the Oracle8
i_file#_block#  index relative to the Oracle7 i_file#_block#
index.  For example, MULTIPLIER=30 triples the initial size when
the index is created, where no MULTIPLIER specified, by default,
uses the i_file#_block# value of 15, creating an index for
Oracle8 that is 1.5 time larger than the Oracle7 i_file#_block#
index.

In most cases, the default 15 is adequate.  There is an issue
when migrating a database with a 4k blocksize (not 2k, not 8k,
just 4k).  If you migrate a database with a 4k block size, you
should use a multiplier value of 30.
June 20, 2000 Santosh -- Thanks for the question regarding "Getting CD's -- OTN and the technology tracks", version 8I
You Asked
How can I get FREE CD's from Oracle ?
I heard that we can get free CD's for Oracle products but for
that we have to register.
Can you please get some more info on this ??
and we said...
By signing up at
http://technet.oracle.com/
(which is free) you can download software
(might take a bit of time, the downloads are large and technet
gets quite busy).

For the CD's you sign up for a technology track. For US$200,
OTN's Technology Tracks give all the software you need to
develop applications on Oracle. Your 12 month subscription
includes developer licenses and free updates.

See
http://technet.oracle.com/software/htdocs/track_benefits.htm
for more info on that.
June 20, 2000 razvan -- Thanks for the question regarding "load data", version 7.3.2
You Asked
hello tom,

there is a posibility to load from a unix shell periodically a
large cantity of data besides using the sql_loader.
(i have a solution to make a form but i am interesting in using
shell unix) ??

another question is if i make periodically backup of unix
filesystems on which i have oracle database is sure for me that
i have an oracle backup too ?? (so for an unix administrator
oracle is transparent )

with respect
razvan

thanks a lot
and we said...
from the unix shell you must use *some* program to load data.
You can:

o write your own in pro*c or oci.
o use sqlldr

Using the "shell" by itself will not work.  You could get dbperl
and do it in perl (but thats a whole lot like "write it
yourself").

sqlldr is pretty flexible and can be invoked from the shell --
you should use it if you can.

As for the filesystem backup -- IF AND ONLY IF the database is
entirely shutdown when you do it.  If the database is up -- it
will not work.  It is more normal to do a database backup where
you backup the database itself -- independent of the file
system.
June 20, 2000 Seetharaman -- Thanks for the question regarding "Oracle Threads -- redo threads.", version 8
You Asked
Hello Tom,

  Greetings.

  What is Thread in Oracle Database?. What is a Public Thread
and Private Thread?. pls. explain me.

With Regards

Seetharaman Srinivasan
and we said...
are you talking about redo threads perhaps.  If so:

A private thread is a redo log created using the ALTER DATABASE
ADD LOGFILE command with the THREAD clause.

A public thread is a redo log created using the ALTER DATABASE
ADD LOGFILE but without specifying a THREAD clause.

see
http://technet.oracle.com/doc/server.815/a67778/ch6_dbar.htm#1115
for more info.  Unless you are using OPS (parallel server) you
need not be concerned about this feature.
June 20, 2000 Seetharaman -- Thanks for the question regarding "Oracle Archive -- ", version 8.1
You Asked
Hello Tom,

  Greetings.

  Database is in No Archive Mode.  I want to restore the
Database using Export and Import utility.  How to go about it?..
Can I use Alter system (database) recover database until change
command. How to do it?..

With Regards

Seetharaman Srinivasan
and we said...
Export and Import are not really backup tools in the
traditional sense.  They are tools for extracting data and
schemas (DDL) at a point in time and putting that data back in.

You can never point in time recover an export.  You get the
data that was exported and thats it.  Any subsequent changes are
"lost".  Consider an export to be an extract, no different then
if you wrote a program to dump the data into a flat file (it
really is no different then that, export is just a program to
dump the data to a file).

So, you will not be restoring a database using export and
import -- they are not for that purpose.

NOARCHIVELOG mode is a mode you can run your test database
in if you don't care about the data in it.  I can think of no
good reason to ever run a production database in noarchive log
mode.  Basically this mode says "if you lose a disk, the data on
that disk is quite simply gone forever".  The best you can
hope is to restore the data to the point in time you last backed
it up.  You will lose all changes that occurred between the
backup and the failure.

NOARCHIVELOG mode means we will simply overwrite redo log once
we no longer need it for instance recovery.  Normally, in
archivelog mode, we save this information so that, when we need
to, we can take an old copy of a datafile and apply the archived
redo log to it to "catch it up" to the rest of the database.
June 20, 2000 prakash -- Thanks for the question regarding "pl/sql and components -- getting result sets.", version Oracle 8i
You Asked
Hi kyte,
 can a pl/sql procedure or a function return a recordset(with
 multiple rows)
 to a middle tier component(active x dll or java bean) written
in
 vb 6.0 or
 java?. we are using oracle 8i on a unix platform.

 thanks,
 Prakash
and we said...
yes -- see

see
http://osi.oracle.com/~tkyte/ResultSets/index.html
for the details.  Examples using VB and Jdbc are there.
June 21, 2000 Raman -- Thanks for the question regarding "Killing a process ?", version 8.0.4
You Asked
(1) I had fired a SELECT statement, that was taking long time to
process, so I killed that session, BUT that process was running
in background on Oracle Server and that was causing performance
problem. How can I kill that Process that is running in
background for that killed session ?

As same, if a fired a procedure, and I don't want to  be
completed and I kill the session, still process is going on
server end causing performance problem.

what should I do ?

(2) Is it possible to import one user's objects into another
user's DEFAULT TABLESPACE ?
and we said...
You must wait for the kill to take effect.  If you like, you can
impose resource profiles for various users.  Using these
resource profiles you can place an upper limit on the amount of
CPU, physical IO's, logical IO's and so on a session or a call
to the database may consume.  The system will automatically
abort these sessions that exceed these limits.

See
http://technet.oracle.com/doc/server.804/a58397/ch20.htm#1148
for details on that feature.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:47812348053,%7BMOVING%7D
for how to use export/import to move objects (which tells you
how to import objects into another tablespace, one that is
different from the tablespace specified in the .dmp file)
June 21, 2000 Ramesh -- Thanks for the question regarding "Is Mutiple Type Creation possible in a single sql file?", version 8.0.5
You Asked
I wanted to create a list of types like

CREATE OR REPLACE TYPE nameList is TABLE OF VARCHAR(32);
CREATE OR REPLACE TYPE dateList is TABLE OF DATE;
and so on..

globally to be used across multiple packages.

But the sql script having multiple "create type" statements
does not compile/run on the SQL prompt. It gives an error
whenever a second create statement is encountered in the sql
script.

I dont want to create a new sql file for each type that
i create. How can i group all such create statements in a single

sql file?

thanks in advance

regards
ramesh
and we said...
you need a / after each create type statement.  Since a create
type may include a semi-colon naturally, sqlplus will not run
the statement until it sees the "run buffer" character.

Code this:

CREATE OR REPLACE TYPE nameList is TABLE OF VARCHAR(32);
/
CREATE OR REPLACE TYPE dateList is TABLE OF DATE;
/

and it'll work.
Review & Followup
Rating: 4
Great September 21, 2002
Reviewer: Jason James from Newcastle, Australia
After 8hrs searching the Oracle Corp site (and heaps of mirrors) with no answer
I found this site, searched my query and had an answer (that worked - and was in
simple terms) in about 2 minutes. Now I can get my Uni DBMS assignment in on
time (and with the correct syntax).

Thanks all at askTom,
Jason James
Monash University
Australia

June 21, 2000 Michael -- Thanks for the question regarding "Poor performance using public synonyms", version 8.0.5.1
You Asked
Hello Tom,

A person has been giving seminars all over Australia and one of
his suggestions to his audience has been 'don't use public
synonyms if you have a large user base'. His argument is
summarised on his webpage:
http://www.ixora.com.au/q+a/2000_02.htm
(search for 'public synonyms')

He says that he has proven this using memory dumps.

My understanding of his argument during the seminar was that
each user is allocated space in the library cache for each
public synonym object referenced by code that they execute. The
volume of entries is causing the poor performance.

We use public synonyms extensively and we are about to release
our first 200+ user application, so an answer would be
appreciated.

regards,

Michael
and we said...
Steve Adams is a smart guy.

Public Synonyms are not entirely evil.  They are something you
can avoid if you want to.  They are not, in my opinion,
something to be totally avoided.  I use them but I do not
overuse them.

I do most all of my work with packages -- end users never see
the tables at all.  There are relatively few "exposed" packages
when compared to the total number of packages + tables and so
on.  So, there are a moderate number of synonyms in use.

You have to consider that thats the way the database works as
well.  We have dbms_output (no one calls sys.dbms_output), we
have dbms_alert, dbms_pipe, utl_file, .... and so on.  We have
all_objects (not sys.all_objects) and so on.  The database
itself makes use of these public synonyms.

In the end, its a matter of sizing and testing.  I for one
cannot fully reproduce some of his points.  The CPU parse point
for example.  I tried:

scott@ORA806.WORLD> declare
  2      type rc is ref cursor;
  3      x rc;
  4  begin
  5      for i in 1 .. 500 loop
  6          open x for select * from tkyte.t;
  7          close x;
  8      end loop;
  9  end;
 10  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:02.99
scott@ORA806.WORLD>
scott@ORA806.WORLD> declare
  2      type rc is ref cursor;
  3      x rc;
  4  begin
  5      for i in 1 .. 500 loop
  6          open x for select * from t_pub_syn;
  7          close x;
  8      end loop;
  9  end;
 10  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:02.60
scott@ORA806.WORLD>
scott@ORA806.WORLD> declare
  2      type rc is ref cursor;
  3      x rc;
  4  begin
  5      for i in 1 .. 500 loop
  6          open x for select * from t_priv_syn;
  7          close x;
  8      end loop;
  9  end;
 10  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:02.58
scott@ORA806.WORLD>

tkprof shows me:

SELECT *
FROM
 TKYTE.T

call     count       cpu    elapsed       disk      query
------- ------  -------- ---------- ---------- ----------
Parse      500      0.85       0.86          0          0
Execute    500      0.15       0.13          0          0
Fetch        0      0.00       0.00          0          0

SELECT *
FROM
 T_PUB_SYN

call     count       cpu    elapsed       disk      query
------- ------  -------- ---------- ---------- ----------
Parse      500      0.89       0.88          0          0
Execute    500      0.10       0.08          0          0
Fetch        0      0.00       0.00          0          0

SELECT *
FROM
 T_PRIV_SYN

call     count       cpu    elapsed       disk      query
------- ------  -------- ---------- ---------- ----------
Parse      500      1.01       1.00          0          0
Execute    500      0.11       0.09          0          0
Fetch        0      0.00       0.00          0          0

So, the public synonym did not take 4x the CPU of the fully
qualified or the private synonym -- they were all pretty much
"equivalent" in this case.  I would need to see his test case to
fully understand how the 1:2:4 ratio came about.

So, I would take into consideration what Steve says -- however,
I would also look at how my system is performing.  I run a
system that gets about 1,000-2,000 different named users every
day.  We use public synonyms for lots of different top level
packges (but not on other stuff).  It works well.  Since each of
our packages are in different schemas, a simple "alter session
set current_schema" would not work for us (we have about 100
application schemas -- we don't know which one of these you want
to use up front).
Review & Followup
Rating: 2
How can acces by other users ????? May 31, 2001
Reviewer: Emit from San Juan, Puerto Rico
If i not create the public synonym others users can acces to the object, what i
need to create for acces that object created without synonym ?

Rating: 5
Tom September 18, 2001
Reviewer: Akhilesh from India
In order to beat this topic to death, why dont we ask Steve adams directly
at-
http://www.ixora.com/contact.htm

June 21, 2000 Ying -- Thanks for the question regarding "How to run user interaction within a PL/SQL block_stored procedure or function?", version Oracle 7.3
You Asked
Hi Tom,
My question is whether I can get user input from a stored
procedure or a function using SQLPLUS ACCEPT function? If not
what are the alternatives so that I can get user interaction
within a plsql block? (Shell script/PERL etc ???)
Please advise.
Thanks
Regards,
Hwee
and we said...
PLSQL runs in one of two places:

o entirely in the server.  when run in the server, there is no
opportunity for user interaction as the server is generally on
another machine else where in the network.  Programmatically --
when you make a stored procedure call -- control switches to the
server where execution runs until completion and control returns
to the caller.  There is no opportunity to interact with anyone
when in the SERVER.

o entirely on the client -- as in forms and reports.  Here plsql
is running on the client machine making sql calls to the
database.  Since the plsql code is actually running on the
client, interaction is possible (we are all on the same
machine).  You would have to use a development environment such
as forms to accomplish this.

PLSQL was not designed to be an "interface" language.  In forms
it can do this -- in the database -- it cannot.
June 21, 2000 Ravinder -- Thanks for the question regarding "SQL*Loader Error 524 Partial Record found at end of datafile", version 8.1.5
You Asked
Hi Tom,

Sometime, I face the following error while loading data using
SQL*Loader

SQL*Loader-524 Partial Record found at end of datafile

I have seen the reply you have given for this. But the problem
is I am working on Win NT 4.0 and my file size is normally
between 500MB - 950MB. And I cant open the file. The problem
which I have faced is that sometime the file has a end of file
marker and it is treating this as a record.

Is there any way to remove this in Win NT or how can I ignore
this using SQL*Loader. I will be upgrading 8.1.6 shortly.

Thanks

Ravi
and we said...
I wrote a tiny C program (will email you the binary as an
attachment in another email).  It simply opens the file for
APPEND in binary mode and a mode that allows reading as well as
writing.  I goto the end of the file, read the last character.
If that is NOT '\n', I put a '\n' at the end of the file.  If it
is a '\n', I do nothing at that point (file is unchanged).

The source code is:

#include "stdio.h"

void main(int argc, char * argv[])
{
FILE    * input;

    if ( argc < 2 )
    {
        printf( "usage: addnl FILENAME\n" );
        exit(1);
    }

    /* Append in binary mode, allow for reading */
    input = fopen( argv[1], "a+b" );

    if ( input == NULL )
    {
        printf( "Error opening file %s\n", argv[1] );
        perror( "fopen()" );
        exit(1);
    }

    /* goto last character */
    fseek( input, -1, SEEK_END );

    if ( fgetc( input ) != '\n' )
    {
        printf( "Adding newline, was not there\n" );
        fseek( input, 0, SEEK_END );
        fputc( '\n', input );
    }
    else
    {
        printf( "Newline detected at EOF, not added\n" );
    }
    fclose( input );
}

and it should be relatively fast as it does not rewrite the
entire file, just fixes it up in place.  I'll send you the full
source, binary and makefile.
June 21, 2000 Sanjay -- Thanks for the question regarding "Tablespace in backup mode", version 7.3.4
You Asked
Tom,
What are the long term effects of keeping a Tablespace in
a backup mode for an extended period of time ? E.g:
We scheduled an online backup of our database via a
3rd-party tool. However, the backup was not sucessful
and the tablespaces remained in backup mode for 3 days
w/o loss of service i.e no errors,performance problems etc.
Meanwhile, the DB was in archivelog mode, generating archive
logs which were backed up and deleted. We were able to bring
the Tses out of the backup mode, w/o being prompted for
an archived redo file.
My concern is what happens to the data
integrity. In hot backup mode, Oracle writes directly to
redo instead of the normal way. If the redo buffer
is full then, it can get archived. How does Oracle
maintain the integrity of the data ?
When does it apply the archived redo, if the TS is in backup
mode for
a long time?
thanks
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:271815712711,%7BHOT%7D%20and%20%7BBACKUP%7D
for some more info but basically its OK to have the file in
backup mode for that long -- it works OK.  It would only need
the archive redo log if the instance failed, crashed during
that period.

Datafiles are continously written to during a hot backup as
normal.  We do not "buffer the changes" off to the side or
anything as complex as that.  We generate additional redo the
first time a block is modified in backup mode but we still flush
the block to the datafile during a checkpoint.
June 21, 2000 Randy -- Thanks for the question regarding "SELECT stmt runs MUCH slower in anonymous block", version 8.1.5
You Asked
I have some developers trying to run a SQL SELECT that is in a
package function.  When calling this function in the package, it
runs in a negligible amount of time.  When the SELECT statement
is extracted out and run in an anonymous block, it takes over 5
min.

Is there some issue with the query plan, caching, or something
else that is particular with queries running in a compiled
package vs. an anonymous block.

(The SELECT is identical in both cases, except for using
literals in the WHERE clause in the anonymous block)

Thanks,

Randy
and we said...
(The SELECT is identical in both cases, except for using
literals in the WHERE clause in the anonymous block)

that is the difference and its *HUGE*.  The two queries
cannot even be compared at that point they are so different.

The difference to the optimizer (especially the CBO) between:

select * from emp where ename like :x

and

select * from emp where ename like 'KIN%';

is enormous.  In the first case, the optimizer has very little
information -- it has to assume :x is "%" and a full table scan
would be in order.  In the second case, it can look at the
constant and figure out -- hey, an index would work great here.

We cannot compare the plans of queries with bind variables
versus queries without.  Make the queries *identical* (take the
constants out -- assign them to plsql variables and then test)
and you'll find the queries run the same.
June 21, 2000 Eric -- Thanks for the question regarding "Using Check constraints with varray types", version 8.1.5
You Asked
Tom,

I am planning a migration a system off of MySQL to Oracle 8.1.5.
 In MySQL they have a data type of SET.  It allows multiple
values to be stored in a record like a VARRAY in Oracle. In
MySQL the SET datatype also limits values entered to predefined
values similar to a check constraint within Oracle.  Here is my
question:  Can I use a check constraint along with a varray
datatype within Oracle to mimic this behavior?

Thanks,
Eric
and we said...
You can use a trigger to do this.

ops$tkyte@8i> create or replace type myArray as varray(25) of
number;
  2  /

Type created.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> create table t ( x int, y myArray );

Table created.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> create or replace trigger t_trigger
  2  after insert on T for each row
  3  declare
  4          l_array myArray;
  5  begin
  6          l_array := :new.y;
  7
  8          for i in 1 .. l_array.count loop
  9                  if ( l_array(i) not between 1 and 5 ) then
 10                          raise PROGRAM_ERROR;
 11                  end if;
 12          end loop;
 13  end;
 14  /

Trigger created.

ops$tkyte@8i>
ops$tkyte@8i> insert into t values ( 1, myArray( 1,2,3,4,5 ) );

1 row created.

ops$tkyte@8i> insert into t values ( 1, myArray( 1,2,3,4,5,6 )
);
insert into t values ( 1, myArray( 1,2,3,4,5,6 ) )
            *
ERROR at line 1:
ORA-06501: PL/SQL: program error
ORA-06512: at "OPS$TKYTE.T_TRIGGER", line 8
ORA-04088: error during execution of trigger
'OPS$TKYTE.T_TRIGGER'
June 21, 2000 Mohammad -- Thanks for the question regarding "INVALID_OPERATION", version ORACLE 8.0.5
You Asked
Hi...
I am trying to create a file using UTL_FILE package. I have
defined UTL_FILE_DIR parameter in my initSID.ora file at the
server and rerun Oracle again. But when I run the program it is
giving me error as INVALID_OPERATION (user defined exception.
The code looks like :

SET SERVEROUTPUT ON;
DECLARE
   d_file1             UTL_FILE.FILE_TYPE;
   d_directory1 varchar2(80):= '/export/home/clarify/aperdata';

   BEGIN
        dbms_output.put_line('1st...');
        d_file1 :=UTL_FILE.FOPEN(d_directory1,'test.txt','W');
        dbms_output.put_line('2nd ...');
     IF UTL_FILE.IS_OPEN(d_file1) = FALSE
     THEN
        dbms_output.put_line('File is not open');
     END IF;

     /*** Document Headers ***/
     UTL_FILE.PUT_LINE(d_file1,'Name');
     UTL_FILE.PUT_LINE(d_file1,'Address');
     UTL_FILE.PUT_LINE(d_file1,'');

 UTL_FILE.FCLOSE(d_file1);

EXCEPTION
  WHEN UTL_FILE.INVALID_PATH THEN
     DBMS_OUTPUT.put_line('Error : Invalid Path (' ||
d_directory1 ||') ') ;

  WHEN UTL_FILE.INVALID_OPERATION THEN
     DBMS_OUTPUT.put_line('Error : Invalid File Operation');
        IF UTL_FILE.IS_OPEN(d_file1) = TRUE Then
                UTL_FILE.FCLOSE(d_file1);
        END IF;
  WHEN UTL_FILE.INVALID_MODE  THEN
     DBMS_OUTPUT.Put_line('Error : Invalid Mode ') ;
  WHEN OTHERS THEN
     DBMS_OUTPUT.put_line('ERROR: ' || SQLCODE || '- '||
SQLERRM);

END;
/
exit;

Basically my program giving me message as "1st...." but not
"2nd......" (I put as test purpose).

Any help in this regard is highly appricieted.

Thanx in advance.

Arif
and we said...
I would hazzard a guess that '/export/home/clarify/aperdata' is
your home directory and the permissions are such that the Oracle
account (which is running the server - which is doing the
UTL_FILE call) does not have write permission on your home
directory.

Remember -- utl_file files will be read/written with the
ownership of the Oracle software owner.  He who starts the
database -- writes the files.
June 22, 2000 Saibabu -- Thanks for the question regarding "Logfile Status", version 8.1.5
You Asked
Hi,
   I have referred Oracle documentation and still confused with
different status of V$logfile,especailly STALE,INVALID,DELETE.
  Can you just set some examples with each status.
 Thanks
saibabu
and we said...
A status of STALE means that Oracle could not write to the file.
 Therefore the file is marked as stale and never reused. This is
usually caused when Oracle is unable to write to the file at an
operating system level.  It can be caused by a damaged disk or
even a dismounted volume.

UNKNOWN or INVALID is a status assigned to a brand new log file.
 Until the new redo log is used, it will continue to show as
unknown or invalid. You can force a log switch by issuing an
ALTER system switch logfile. You can repeat this command several
times until the switch reaches the desired logfile.

Status of BLANK means that it is actively in use.

Status of DELETED means the file is no longer used.  It has been
dropped from the database.
Review & Followup
Rating: 5
your explanation of stale status is missing something February 07, 2002
Reviewer: Nag
look at the following scenario...
SQL> desc v$log
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 GROUP#                                             NUMBER
 THREAD#                                            NUMBER
 SEQUENCE#                                          NUMBER
 BYTES                                              NUMBER
 MEMBERS                                            NUMBER
 ARCHIVED                                           VARCHAR2(3)
 STATUS                                             VARCHAR2(16)
 FIRST_CHANGE#                                      NUMBER
 FIRST_TIME                                         DATE

SQL> select group#,members, status from v$log;

    GROUP#    MEMBERS STATUS
---------- ---------- ----------------
         1          1 CURRENT
         2          1 INACTIVE
         3          1 INACTIVE

SQL> desc v$logfile ;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 GROUP#                                             NUMBER
 STATUS                                             VARCHAR2(7)
 MEMBER                                             VARCHAR2(513)

SQL> select group#, status
  2  from v$logfile;

    GROUP# STATUS
---------- -------
         1
         2 STALE
         3 STALE

it shows 2 stale groups... but when I

SQL> alter system switch logfile;

System altered.

SQL> select group#, status
  2  from v$logfile;

    GROUP# STATUS
---------- -------
         1
         2
         3 STALE

it show only one , when I further do

SQL> select group#,members, status from v$log;

    GROUP#    MEMBERS STATUS
---------- ---------- ----------------
         1          1 INACTIVE
         2          1 CURRENT
         3          1 INACTIVE

SQL> alter system switch logfile;

System altered.

SQL> select group#, status
  2  from v$logfile;

    GROUP# STATUS
---------- -------
         1
         2
         3

NOW NO STALE FILES

SQL> select group#, status
  2  from v$logfile;

    GROUP# STATUS
---------- -------
         1
         2
         3

SQL> select group#,members, status from v$log;

    GROUP#    MEMBERS STATUS
---------- ---------- ----------------
         1          1 INACTIVE
         2          1 INACTIVE
         3          1 CURRENT

Tom, if I have not used the logroup at all , and I have just created the db,
will the status show as unknown or stale.

You have said it shows  up as unknown, but my scenario shows that it is showing
up as STALE.

KINDLY CORRECT ME IF IAM WRONG.

Further, is there any difference between the status shown in v$Log and
v$logfile, or are they speaking about the same status.

Rating: 3
Other meaning for STALE July 19, 2002
Reviewer: Doug from CT, USA
On metalink's note 43746.1 it says:

The STALE status indicates that a member of a logfile group is incomplete in
terms of the redo it contains. Marking a member STALE prevents the user from
being able to drop it before that logfile group is archived. There are 3 ways
(in 7.1 code) whereby a member could become stale:

        1) When building the logfile entry in the controlfile after media
recovery and using resetlogs/noresetlogs we set all members to STALE
- to force archiving before any log member can be dropped.

        2) When recovering after a crash also we are not sure which member of a
logfile group had the last redo piece written to it, so we must make sure that
ALL log members are archived before they can be dropped.
           Marking them STALE achieves this - it indicates that the log
information is not complete in any one member, so all are needed to reconstruct
during archiving.

        3) If a write error occurs when writing to a member it is marked stale,
and if the max error count has been exceeded for that file it is closed. This
will alert the archiver to look at the other log members to complete the
logfile.

So it sounds like stale means either bad or in-doubt, and sometimes Oracle does
this on purpose I guess.

June 22, 2000 PRATHAP -- Thanks for the question regarding "how to pass a tablename/column name into a procedure", version 8.1.5
You Asked
Hi Tom,
    I want to create a procedure which accepts two parameters
1. Table name(say TAB1)  2. Table column(say COL1) and return
the maximum
column value in order to increment to next number.
The problem I face is I cannot use :
  SELECT NVL(MAX(COL1),0)+1 INTO temp FROM TAB1;
since TAB1  is not treated as variable here.

   Plese suggest a solution.

Thanks
Prathap Kumar
and we said...
Please use SEQUENCES for this!!!! Please.  The solution you have
above does not work in a multi-user environment unless you
serialize (eg: lock the table) access to the table.  Sequences
will allow you to do this in a totally non-blocking fashion
(very scalable, very fast).  Please name a sequence after your
table/column name do a routine like:

ops$tkyte@DEV8I.WORLD> create or replace
  2  function get_id( p_tname in varchar2, p_cname in varchar2 )
  3  return number
  4  as
  5      l_number number;
  6  begin
  7      execute immediate
  8      'select ' || p_tname || '_' || p_cname || '_seq.nextval
  9         from dual' INTO l_number;
 10
 11      return l_number;
 12  end;
 13  /

Function created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> create sequence T1_C1_seq start with 1000
  2  /

Sequence created.

ops$tkyte@DEV8I.WORLD> create sequence T2_C1_seq start with 567
  2  /

Sequence created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> begin
  2    dbms_output.put_line( get_id('t1','c1') );
  3  end;
  4  /
1000

PL/SQL procedure successfully completed.

ops$tkyte@DEV8I.WORLD> begin
  2    dbms_output.put_line( get_id('t1','c1') );
  3  end;
  4  /
1001

PL/SQL procedure successfully completed.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> begin
  2    dbms_output.put_line( get_id('t2','c1') );
  3  end;
  4  /
567

PL/SQL procedure successfully completed.

ops$tkyte@DEV8I.WORLD> begin
  2    dbms_output.put_line( get_id('t2','c1') );
  3  end;
  4  /
568

PL/SQL procedure successfully completed.

If you feel you must for whatever reason use the max(col1) from
T, you can see how to do it now using EXECUTE IMMEDIATE (but you
really should not do it that way -- its error prone, slow, and
highly non-concurrent)
June 22, 2000 Guoan -- Thanks for the question regarding "snapshot column length from 4000 to 2000", version 8.1.5
You Asked
Dear Sir,
    I have table t1 (id number(3) primary key ,col1
varchar2(4000)) at db1.world. And I create snapshot t1 at
db2.world
But When I desc t1 at  db2.world,the result is
id number(3),
col1 varchar2(2000)
So,replcation between db1.world and db2.world is not
successfuly.
Could you give me suggestion? I use Orace8.1.5 at Linux2.2.13

Thanks a lot

                     Your truly
                                      Andy Wu
and we said...
This is bug 893259.

It is fixed in the 8.1.5.1 patchset.  Please contact support and
request that patchset.
June 22, 2000 Amit -- Thanks for the question regarding "sys.user_lock pacakge", version 8.0.5
You Asked
Hi Tom,

Consider the following stored-procedure (implemented in
an Oracle 8.0.5 database):

    create or replace
    procedure MyProc(iKey in varchar2)  is
      vHashVal  number;
      vLockStat number;
      vIdx      number;
    begin

    /* Compute Hash value for iKey
    */
      vHashVal := 0;
      for vIdx in 1 .. length(iKey) loop
        vHashVal := mod(vHashVal * 64
                 + ascii(substr(iKey,vIdx,1)),
                   const.N2GIGS);
      end loop;

    /* Create a user lock for hash(iKey)
    */
      vLockStat := sys.user_lock.request(
                    vHashVal,sys.user_lock.x_mode,
                    user_lock.maxwait,
                    sys.user_lock.global);

      -----------------------------------
      --    :
      --    :
      --    :
      -- CRITICAL SECTION:
      -- SOME CODE THAT MUST NOT RUN
      -- CONCURRENTLY FOR THE SAME iKey
      --    :
      --    :
      --    :
      -----------------------------------

    /* Release the user lock for hash(iKey)
    */
      vLockStat := sys.user_lock.release(vHashVal);

    exception
        when others then
        begin
          /* Release the user lock for hash(iKey)
          */
          vLockStat := sys.user_lock.release(vHashVal);
        end;
    end ;

There is a piece of code which I want to ensure will
not run concurrently for the same value of the iKey
input parameter (string).
It is a critical section (per iKey).

I am using "sys.user_lock" to accomplish this.
The package expects a numeric ID to identify the
user lock number, so I have to hash the string
to a number.

My questions:

1. What alternatives do I have to implementing
   my own hash computation ?
   Can I call oracle's internal hash functions
   through some package ?

2. Can there be cases where user_locks are not
   released (for example if a session is killed
   while in the critical section)?

   If there are such cases, can these locks
   be removed somehow ?

3. Have you any other tips related
   to user_locks that will be helpful ?

Thanks,
Amit.
and we said...
I am not familar with user_lock -- that was the name of the
dbms_lock package in 7.0 of the database however it is called
DBMS_LOCK since 7.0.12 at least....

Here is a response I've created for a very similar issue -- to
avoid 2 people inserting the same primary key simultaneously.  I
don't want 2 people to do the same thing with the same value --
very much like yours:

(as for #2 above -- if the session goes away, the locks held by
dbms_lock go away as well)

Try this:

create table demo ( x int primary key );

create or replace trigger demo_bifer
before insert on demo
for each row
declare
    l_lock_id   number;
    resource_busy   exception;
    pragma exception_init( resource_busy, -54 );
begin
    l_lock_id :=
       dbms_utility.get_hash_value( to_char( :new.x ), 0, 1024
);

    if ( dbms_lock.request
             (  id                => l_lock_id,
                lockmode          => dbms_lock.x_mode,
                timeout           => 0,
                release_on_commit => TRUE ) = 1 )
    then
        raise resource_busy;
    end if;
end;
/

-------------------------------------------------------

If, in 2 separate sessions you execute:

insert into demo values (1);

it'll succeed in the first one but immediately issue:

SQL> insert into demo values ( 1 );
insert into demo values ( 1 )
            *
ERROR at line 1:
ORA-00054: resource busy and acquire with NOWAIT specified
ORA-06512: at "TKYTE.DEMO_BIFER", line 12
ORA-04088: error during execution of trigger 'TKYTE.DEMO_BIFER'

in the second session (unless the first session commits and then
unique constraint violation will be the error message).

The concept here is to take the PRIMARY KEY of the table in the
trigger and put it in a character string.  we can then use
dbms_utility.get_hash_value to come up with a "mostly unique"
hash value for the string.  As long as we use a hash table
smaller then 1,073,741,823, we can 'lock' that value exclusively
using dbms_lock.

We take that hash value and use dbms_lock to request that hash
to be X locked with a timeout of ZERO (returns immediately if
someone else has locked that value).  If we timeout, we raise
ORA-54 resource busy.  Else, we do nothing.

Of course, if the primary key of your table is an INTEGER and
you don't expect the key to go over 1 billion, you can skip the
hash and just use the number.

You'll need to play with the size of the hash table (1024 in my
example) to avoid artificial 'resource busy' messages due to
different strings hashing to the same number.  Also, the owner
of the trigger will need execute on DBMS_LOCK granted directly
to them (not via a role).  Lastly, you might find you run out
of enqueue_resources if you insert lots of rows this way without
committing.  If you do, you need to modify the init.ora
parameter enqueue_resources to be high enough (you'll get an
error message about enqueue_resources if you hit this).
You might add a flag to the trigger to allow people to turn the
check on and off (if I am going to insert hundreds/thousands of
records, I might not want this check enabled for example)
June 22, 2000 Bhavesh -- Thanks for the question regarding "SESSION's Privilege in SESSION_PRIVS table", version 8i
You Asked
Dear Tom,
While I was trying to make a small PL/SQL procedure run - which
was using DBMS_SQL package, I reach to this question. In the excercise, I found
that the privileges entry in the SESSION_PRIVS table to be confusing.  Even
though I
have CREATE TABLE privilege on
SCOTT, I need  to grant it once again from SYSTEM.
(Note: The user SCOTT does not have quota problem, it
 has unlimited quota to its default tablespace.
 And, the platform is Sun/Solaris and Oracle8i)

 Following is the full cut/paste from my UNIX window:

 Pls go thru it carefully. At the end part, u will see the
 same set of privilege to SCOTT before and after REVOKEing
 the CREATE TABLE privilege from him.

 - - - - - - - - - cut/paste of UNIX window starts here - - - -
 SQL> show user
 user is "SCOTT"
 SQL> create table temp1 (col1 number(3) );

 Table created.
 SQL>l
   1* select * from session_privs where privilege like '% TABLE'
 SQL>/

 Press Enter...
 PRIVILEGE
 ----------------------------------------
 CREATE TABLE
 CREATE ANY TABLE
 ALTER ANY TABLE
 DROP ANY TABLE
 COMMENT ANY TABLE
 SELECT ANY TABLE
 INSERT ANY TABLE

 7 rows selected.

 SQL>
 create or replace procedure ddl_pl2 as
   c1      integer;
   c2    integer;
 begin
   c1 := dbms_sql.open_cursor;
   dbms_sql.parse( c1, 'create table tbl_1 ( col1 number)  ', 1 );
   c2 := dbms_sql.execute( c1 );
   dbms_sql.close_cursor( c1 );
 --dbms_sql.parse( c1, 'alter system switch logfile', dbms_sql.native );
 end;
 /

 SQL>show errors
 No errors.
 SQL>execute ddl_pl2;
 begin ddl_pl2; end;

 *
 ERROR at line 1:
 ORA-01031: insufficient privileges
 ORA-06512: at "SYS.DBMS_SYS_SQL", line 487
 ORA-06512: at "SYS.DBMS_SQL", line 32
 ORA-06512: at "SCOTT.DDL_PL2", line 6
 ORA-06512: at line 1

 SQL>connect system
 Enter password:
 Connected.
 SQL>show user
 SQL>user is "SYSTEM"
 SQL>grant create table to SCOTT;

 Grant succeeded.

 SQL>connect scott
 Enter password:
 Connected.
 SQL>show user
 SQL>user is "SCOTT"
 SQL>execute ddl_pl2;

 PL/SQL procedure successfully completed.

 SQL>desc tbl_1
  Name                            Null?    Type
  ------------------------------- -------- ----
  COL1                                     NUMBER

 SQL>select * from session_privs where privilege like '% TABLE'
   2  /
 Press Enter...

 PRIVILEGE
 ----------------------------------------
 CREATE TABLE
 CREATE ANY TABLE
 ALTER ANY TABLE
 DROP ANY TABLE
 COMMENT ANY TABLE
 SELECT ANY TABLE
 INSERT ANY TABLE

 7 rows selected.
 SQL>show user
 user is "SCOTT"
 SQL> connect system
 Enter password:
 Connected.
 SQL> revoke create table from scott;

 Revoke succeeded.

 SQL> connect scott
 Enter password:
 Connected.
 SQL> select * from session_privs where privilege like '% TABLE'
   2  ;

 PRIVILEGE
 ----------------------------------------
 CREATE TABLE
 CREATE ANY TABLE
 ALTER ANY TABLE
 DROP ANY TABLE
 COMMENT ANY TABLE
 SELECT ANY TABLE
 INSERT ANY TABLE

 7 rows selected.
 SQL>exit
 $
 - - - - - - - - - cut/paste of UNIX window ends here - -  - -

Please tell me why this is showing this way ??

Or am I wrong somewhere ?

Thanks and Regards,

Bhavesh Patel
Tata Telecom Ltd
Gandhinagar.
Tel: (02712) 21773 (x301)
e-mail: BhaveshPatel@tatatelecom.com
        BhaveshPatel@hotmail.com
and we said...
Scott had the ability to create the table via a role the first time around.  See
http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
for the details.
June 22, 2000 Reji -- Thanks for the question regarding "EXTPROC_CONNECTION_DATA -- what is it", version 8.1.6
You Asked
Tom:
   I was looking at the tnsnames.ora file, there is a
EXTPROC_CONNECTION_DATA service and the manual says it is
for external procecures...Would u please elaborate on this?

-Reji
and we said...
External procedures are a method of writing a stored procedure
in C.  External procedures are started in an address space
separate from the server.  They are started by the sqlnet
listener.  In order for it to be able to start this service --
it needs a tns entry -- this entry is always called
extproc_connection_data.

See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adg11rtn.htm#1656
for more info
June 22, 2000 Ellie -- Thanks for the question regarding "Delete database", version 8.1.5
You Asked
How can i delete database(instance) on Server? What other steps
do I have to proceed in order not  a " trace of it remains "?
PS I have a multiple instances inside 1 Oracle home in this
Server.
and we said...
On 8i you will use the database assistant to do this.  Here is a
support note that goes into further details as to a little more
cleanup that you will have to do to remove all traces of it:

<Note:1070355.6>

Problem Description:
====================

You are using the Database Configuration Assistant (dbassist) to
delete a database and then create a database with the same SID
and you get the following alert.

Database <sid> already exists.  Please specify another database
name.

Problem Explanation:
====================

When you use dbassist to delete your database it deletes the
database control files, redo logs, and database files, but
leaves behind the "init<sid>.ora" and everything under the
ORACLE_BASE/admin/<SID> directory.  This causes dbassist
to think the <SID> already exists.

Solution Description:
=====================

You need to remove everything under "$ORACLE_BASE/admin/<SID>"
and remove the "init<SID>.ora".  Below are two solutions - one
for UNIX, the other NT.

On UNIX
=======

1) Delete the database using dbassist.

2) Remove the "init<SID>.ora"
   - usually under "$ORACLE_HOME/dbs"

3) Remove the directory and everything under
"$ORACLE_BASE/admin/<SID>"

    ie.      SID= V804
        cd $ORACLE_BASE/admin/V804
                 ls
             bdump/   cdump/   create/pfile/   udump/
        cd ..
        rm -rf V804

Note
====

With Unix, you also have to remove any references to the
"$ORACLE_SID" in "/var/opt/oracle/oratab", or dbassist will
still see the database.

Just removing the files from the "admin" directory may not get
all of them.  Dbassist doesn't delete other files under the
"$ORACLE_BASE" and "$ORACLE_HOME" that have the SID prepended to
the name of the file.

You must do a find in order to locate all of the files.

Eg:  from the mount point of the "$ORACLE_HOME /u01":

    find . -name "*sid*" -print

On NT
=====

Do pretty much the same except the "init<SID>.ora" is usually
under "$ORACLE_HOME/Database" instead of "dbs".

Look in the registry for the "ORACLE_HOME", find the SID
directory, and delete the directory and its contents.

For example, if your ORACLE_HOME is C:\OraHome81 and SID is
NT815 then remove:

C:\OraHome81\Admin\NT815 directory

If this directory exists the database creation will fail.

In addition to this directory, the 'Oradata\NT815' directory
must be deleted or renamed:

C:\OraHome81\Oradata\NT815 directory

Having removed these directories, the database assistant should
then allow you to create the database.

Explanation
===========

The Database configuration assistant is supplied with 8.1 to
ease the creation of new databases, this may sometimes fail with
permission, space etc. errors.

Once you have resolved the cause of the error you may wish start
the assistant again to recreate the database. Even if you have
removed the services and all of the associated datafiles you may
get the error that the database already exists, and the creation
fails.

This is because the Assistant checks for the existance of the
instance name in the ORACLE_HOME\Admin or ORACLE_BASE/admin
directory.
Review & Followup
Rating: 5
"Delete database" December 07, 2003
Reviewer: ross walker from australia
exactly what i wanted - how to cleanly remove an oracle instance, safely when
other instances co-exist on the database.

June 22, 2000 razvan -- Thanks for the question regarding "syncronization in oracle - some recovery questions", version 7.3.2
You Asked
hello tom,

how oracle syncronize at the time of instance recovery control
file and datafile,redolog file etc.I quess i don 't understand
what oracle use: SCN,log sequence or checkpoint meckanism for
doing syncronization?

and why "process rollback segments are populated during the
roll-forward process" ?

thanks a lot
tom
and we said...
Thats a big question.  If we had a white board and some time
together, be glad to answer.  In a simple "q/a" like this, I'm
mostly going to point you to the requisite documentation.

The answer to "I quess i don 't understand what oracle use:
SCN,log sequence or checkpoint meckanism for  doing
syncronization" is all 3 and more.  Recovery is a complex
process -- its what you buy the database for.  The concepts
manual (which everyone should read from cover to cover) goes
into good detail on this.

As for:
and why "process rollback segments are populated during the
roll-forward process" ?

it is because we need to rollback uncommitted transactions that
were taking place when the instance failed.  In order to roll
them back we need their undo records.  Undo records are stored
in rollback.  We have to recover the rollback (which is cached
in the same fashion datablocks are in the SGA) in order to
rollback these transactions.  So, we roll forward and then
rollback.

See

recovery structures covers redo logs and so on:
http://technet.oracle.com/doc/server73x/SCN73/ch22.htm#toc154
intro to database recovery:
http://technet.oracle.com/doc/server73x/SCN73/ch24.htm#toc168
for more details.
June 22, 2000 habeebuddin -- Thanks for the question regarding "error messaging system -- handling FRM-40510-UNABLE TO DELETE THE RECORD", version 2.1
You Asked
sir,

Please tell me how to capture the database error messages in the
on-error event trigger.
example: The ORA-20036 for this error the form is generating the
generic error(FRM-40510-UNABLE TO DELETE THE RECORD).I used the
following method bu I could not.

 if error_type='ORA' and erro_num=20036 then

     message('test');

     raise form_trigger_failure;

 end if;

Regards....
Habeeb.
and we said...
In the ON-ERROR trigger you may use

dbms_error_text to get the message
dbms_error_code to get the error code (-20036)
June 23, 2000 rao -- Thanks for the question regarding "Export/Import of a database -- how to ignore object creation errors", version Oracle 8
You Asked
Hi Tom,
This is regarding the extraction of details from one database
to other by using exports and imports. When I am importing if the
object already exists in the schema, then it will give error message
and even the new rows also not importing. But I want to import only
the rows from the exported dump file. How can I do this?
and we said...
use the IGNORE=Y option on the import.  IGNORE=Y tells import to ignore errors
that occur due to objects already existing.

beware -- you can end up with duplicate constraints and such if you are not
careful this way.  For example consider:

ops$tkyte@8i> create table t ( x int check ( x > 0 ) );
Table created.

ops$tkyte@8i> select CONSTRAINT_NAME , SEARCH_CONDITION from user_constraints;

CONSTRAINT_NAME SEARCH_CON
--------------- ----------
SYS_C0025825     x > 0

Ok, so table T has one constraint on it -- the one we put there.  Lets export
the table:

ops$tkyte@8i> host exp userid=/ tables=t

Export: Release 8.1.5.0.0 - Production on Fri Jun 23 09:15:14 2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 - Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production
Export done in US7ASCII character set and US7ASCII NCHAR character set

About to export specified tables via Conventional Path ...
. . exporting table                              T          0 rows exported
Export terminated successfully without warnings.

And now, to pretend we are in another database, we'll recreate it
ops$tkyte@8i> drop table t;
Table dropped.

ops$tkyte@8i> create table t ( x int check ( x > 0 ) );
Table created.

And now import it with ignore=y.  Note that the constrant SYS_C0025825 no
longer exists in this database -- when we dropped T, we dropped that constraint.
 When we created T, we recreated that constrain but with a new default name!

ops$tkyte@8i> host imp userid=/ full=y ignore=y

Import: Release 8.1.5.0.0 - Production on Fri Jun 23 09:15:15 2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 - Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

Export file created by EXPORT:V08.01.05 via conventional path
import done in US7ASCII character set and US7ASCII NCHAR character set
. importing OPS$TKYTE's objects into OPS$TKYTE
. . importing table                            "T"          0 rows imported
Import terminated successfully without warnings.

ops$tkyte@8i> select CONSTRAINT_NAME , SEARCH_CONDITION from user_constraints;

CONSTRAINT_NAME SEARCH_CON
--------------- ----------
SYS_C0025826     x > 0
SYS_C0025827     x > 0

Note that after the import we have the constraint 2 times on the table -- once
from the create table and once because import brought back the originally named
constraint.

So -- this points out why you might want to name all constraints, if we had
named that constraint ourself, this would not happen.
June 23, 2000 Atchut -- Thanks for the question regarding "Oracle Application Server on Windows 2000", version 4.0.8.2
You Asked
Can Oracle Application server 4.0.8.2 be installed on Windows
2000? I tried installing 4.0.8.1, but the installer could not
recognize Windows 2000 as follwer of NT.
and we said...
Windows 2000 is planned to be supported in the future but is not
supported with 4.0.8.2.
June 23, 2000 KK -- Thanks for the question regarding "Login in WebDB", version 2.2
You Asked
Can I create a form in WebDB that can accept the user name
and password from the users?  Then can I assign the user name
and password to some global variables in WebDb?
and we said...
WebDB currently supports only database authentication or no
authentication.  The database authetication is performed via
BASIC Authentication and will use the builtin dialog box
provided by the browser (not an HTML page).

It would be possible for you to create a login page built around
a stored procedure that took a username/password. This routine
would validate the username and password and set up some sort of
cookie (you would be responsible for making the cookie "secure"
so no one could spoof you).  You would then setup a pre routine
on every form, report, chart, etc.  This pre routine would
simply validate the cookie and if the cookie was present and
valid -- allow the user to continue.  If the cookie was not
valid -- it would print out "not a valid session" or something
and issue a RETURN (to prevent the rest of the page from being
generated)
Review & Followup
Rating: 3
Main username and password February 12, 2002
Reviewer: vivek from ny
Hi Tom,

   I have webdb instralled on one machine and (webdb+ reports server) and  my
database is on another machine

  Now I have NET80/Admin entry for that database.
and I am able to connect to the databae via sqlPlus client from webdb + reports
6.0.8 machine to the database
(This proves tnsnames entry is ok)

  but I am unable to connect via
http://webDBmachine/webdb/.home
actual URL is (
http://127.0.0.1/WebDB/WEBDB.home
it gives me following error

/*

Database Log In Failed
TNS could not resolve service name

Verify that the TNS name in the connectstring entry of the DAD for this URL is
valid.

*/

 Where should I look ?
is there seperate username and password for webdb ?

I dont know what to put/how to put username in that box and
where is it looking for tns or dad (I don't know) entry.

 I am trying to connect with the dba privilaged account..

Thanks,
vivek

Rating: 4
web db August 31, 2003
Reviewer: Ismail from India
Web db will  be useful only when Forms is used as Front End tool. Is it so?

Please brief me where can i use web db tool effectively.

June 23, 2000 sindu -- Thanks for the question regarding "How to get the particualer date on every month", version version 8
You Asked
Hi Tom,

  How to get the particular date on every month?
  ex: every month 10th.
  10/01/2000
  10/02/2000
  10/03/2000   etc.
and we said...
  1  select add_months( to_date( '10-jan-2000' ), rownum-1 )
  2    from all_objects
  3*  where rownum < 13
  4  /

ADD_MONTH
---------
10-JAN-00
10-FEB-00
10-MAR-00
10-APR-00
10-MAY-00
10-JUN-00
10-JUL-00
10-AUG-00
10-SEP-00
10-OCT-00
10-NOV-00
10-DEC-00

12 rows selected.

is one way.  beware -- add_months on the LAST day of a month
gives the last day of the NEXT month.  So, if you start at:

  1  select add_months( to_date( '29-feb-2000' ), rownum-1 )
  2    from all_objects
  3*  where rownum < 13
ops$tkyte@8i> /

ADD_MONTH
---------
29-FEB-00
31-MAR-00
30-APR-00
31-MAY-00
30-JUN-00
31-JUL-00
31-AUG-00
30-SEP-00
31-OCT-00
30-NOV-00
31-DEC-00
31-JAN-01

12 rows selected.

you get the last day of every month -- not the 29'th.
June 23, 2000 Mohamed -- Thanks for the question regarding "Creating Objects in Oracle --ORA-00439: feature not enabled: Objects", version Oracle8 Enterprise Edition Release 8.0.4.0.0 - Production
You Asked
Hi,

We are using Oracle8 Enterprise Edition Release 8.0.4.0.0 -
Production. I executed the following statement.

 create type address as object
 (
 name varchar2(30),
 street varchar2(30),
 city  varchar2(30))
 state varchar2(30),
 country varchar2(30),
 zip varchar2(20)
 )

I got the following error message.

create type address as object
*
ERROR at line 1:
ORA-00439: feature not enabled: Objects

What is the problem? Please help!

regards,
rafi.
and we said...
With Oracle8 release 8.0, objects are an extra cost option to
the database that must be licensed separately.  Starting with
Oracle8i, release 8.1, objects comes with the Enterprise Edition
as a standard feature.

Please refer to the "getting to know" guides -- available online
at:
http://technet.oracle.com/
for each release to see what FEATURES (no cost) come with each
version and what OPTIONS (extra cost) are available with each.

If you have licensed the objects option with 8.0, it may be
installed from the CD.
June 23, 2000 Sankalp -- Thanks for the question regarding "DISPLAY MESSAGES FROM STORED PROCEDURES ON THE FORMS5", version 8.x
You Asked
Sir,

a)How to catch the mesaages which we insert in stored procedures
onto the form?

b)How to connect two databases. Can U provide me step by step
approach?

Thanks in advance
Regards
SANKALP
and we said...
a) do not understand this.  what do you mean by "insert in
stored procedures"?

b) database links are the answer to this.  The database will
connect for you to another database allowing you to perform
distributed transactions, cross database joins, and remote
procedure calls.  You use the "create <public> database link
<connect to username identified by password> using
TNS_CONNECT_STRING;"  See the SQL Reference manual
http://technet.oracle.com/doc/server.804/a58225/toc.htm
and
distributed systems
http://technet.oracle.com/doc/server.804/a58247/toc.htm
guide for more info.


Subject | Article | Last Updated (East coast time)
Interesting Query.. find the number of vowels in a string | article only | Jun 24, 2000 11:04 am
Backing up control files | article only | Jun 24, 2000 11:29 am
PL/SQL Qn | article only | Jun 24, 2000 11:38 am
oracle 8i services | article only | Jun 24, 2000 11:42 am
On-line redo log status meaning? | article only | Jun 24, 2000 11:45 am
Distributed Option in Oracle 7 | article only | Jun 24, 2000 11:47 am
Renaming a Index | article only | Jun 24, 2000 04:45 pm
SHowing Messges in Stored procedures onto form. | article only | Jun 26, 2000 09:52 am
Encrypting the password in unix text file. | article only | Jun 26, 2000 10:02 am
FORM CONVERSION FROM V3 TO V5 | article only | Jun 26, 2000 10:12 am
how To PASS TABLE AS ARGUMENT TO PROCEDURE | article only | Jun 26, 2000 10:39 am
8i Automated Standby Database | article only | Jun 26, 2000 10:43 am
Dynamic SQL | article only | Jun 26, 2000 10:52 am
Using multilple sets of Oracle binaries on same server | article only | Jun 26, 2000 12:08 pm
Doc attachment in Oracle Alert | article only | Jun 26, 2000 12:25 pm
WebDB 3.0 production release date | article only | Jun 26, 2000 12:37 pm
Report with row dependencies | article only | Jun 27, 2000 07:12 am
How to pass argument in PL/sql cartidges | article only | Jun 27, 2000 07:17 am
procedure auto executed | article only | Jun 27, 2000 07:25 am
Oracle user authentication in LDAP server with 3 tiers (you cannot) | article only | Jun 27, 2000 09:46 am
lob modofication -- syntax | article only | Jun 27, 2000 04:08 pm
Trace files from ARCH in 8i | article only | Jun 27, 2000 07:48 pm
export utility | article only | Jun 28, 2000 08:57 am
Realocate unused blocks of tablespaces | article only | Jun 28, 2000 12:52 pm
cleaning up grants | article only | Jun 28, 2000 01:08 pm
Input file | article only | Jun 28, 2000 01:20 pm
Pro C/C++ -- what compiler on windows | article only | Jun 28, 2000 01:35 pm
reducing reorganisation time of large indexes and tables | article only | Jun 28, 2000 01:50 pm
Security with respect to invoker's rights procedures | article only | Jun 28, 2000 03:11 pm
Cancelling asynchronous ADO OLE DB queries | article only | Jun 28, 2000 03:23 pm
View and Tables -- can i modify a view | article only | Jun 28, 2000 03:25 pm
Oracle intermedia for windows media server. | article only | Jun 28, 2000 03:32 pm
Where is the view DBA_WAITERS ? | article only | Jun 29, 2000 08:28 am
d2kwut32.dll in Forms 6.0.5 | article only | Jun 29, 2000 08:40 am
Call the print utility of the browser | article only | Jun 29, 2000 09:04 am
Insert variable in select and create statment in plsql code | article only | Jun 29, 2000 09:17 am
NT Oracle service accessing a network drive. | article only | Jun 29, 2000 09:23 am
IMPORTING OF DATA | article only | Jun 29, 2000 01:04 pm
@ > whenever sqlerror EXIT | article only | Jun 29, 2000 01:15 pm
Deployment -- linking the database with HTML | article only | Jun 30, 2000 07:12 am
Where to find the NEXT value of datafile | article only | Jun 30, 2000 07:21 am
Describing remote tables | article only | Jun 30, 2000 07:39 am
Replication -- does it generate redo/rollback? | article only | Jun 30, 2000 07:48 am
Very large Database - question on max files/max filesize | article only | Jun 30, 2000 07:53 am
Slow query | article only | Jun 30, 2000 08:17 am
Installing Oracle 8i and Developer 2000 | article only | Jun 30, 2000 09:11 am
User Account -- prioritization | article only | Jun 30, 2000 09:29 am
Export and ora-155 | article only | Jun 30, 2000 09:32 am
How to get the number of bytes in a LONG RAW column | article only | Jun 30, 2000 12:01 pm
Virtual Database - virtual private database.. | article only | Jun 30, 2000 12:02 pm
LOAD JAVA Erorrs | article only | Jun 30, 2000 12:13 pm
Differences between Oracle 7.3 and Oracle 8 (NOT the enterprise edition) | article only | Jun 30, 2000 12:41 pm
RE: Ask Tom Submission Logic Tables | article only | Jun 30, 2000 04:17 pm
row(s) 1 - 53 of 53
June 24, 2000 Dinesh -- Thanks for the question regarding "Interesting Query.. find the number of vowels in a string", version 8.0
You Asked
Hi tom ,
  i got a Author table which contain a column named text in
which  the description of the story will be there. now i have to
find  which text(row) has maximum number of vowels in it thru a
sql query ??

  Waiting for the Answer...

Dinesh
and we said...
try:

ask_tom@OSI1.WORLD> variable str varchar2(1000)
ask_tom@OSI1.WORLD>
ask_tom@OSI1.WORLD> exec :str := 'How Now Brown Cow'

PL/SQL procedure successfully completed.

ask_tom@OSI1.WORLD>
ask_tom@OSI1.WORLD> select
  2    length(:str)
  3    - length(replace(
  4                   translate(upper(:str),'AEIOU','AAAAA'),
  5                    'A','')) num_vowels
  6  from dual
  7  /

NUM_VOWELS
----------
         4

ask_tom@OSI1.WORLD>

we translate all vowels in A, replace A with nothing and
subtract the length of the resulting string from the original.
The difference is the number of vowels in the word.

Order by that DESC and fetch the first row.
June 24, 2000 Steven -- Thanks for the question regarding "Backing up control files", version Oracle 8.0.4.1
You Asked
I'm running Oracle 8.0.4.1 on Windows NT 4.0. I am try to backup
the control file to a remote machine on the LAN. I have the
drive mapped and I am using the 'alter database backup
controlfile to 'mapped drive''. I put the share in the
null_session_shares in the registry on the remote machine and
the control file will copy, but I am still getting errors
returned.

ORA-01587: error during controlfile backup copy
ORA-27068: skgfdisp: buffer is not aligned properly
OSD-04026: Invalid parameter passed. (OS 31523328)

Are these errors Oracle related, and if so do you know what to
do? Or is this an OS/network problem that needs to be fixed?
and we said...
These errors are due to the fact the mapped drive only exists in
your session -- not in the session Oracle is running (its not
like unix where either a device is mounted or not).

When an oracle instance is created the services that support it
are setup to "Log On As" the SYSTEM (or operating system)
account, this account has very few privileges and no access to
NT Domains. To access another NT machine the OracleServiceXXXX
must be setup to logon to the appropriate NT Domain as a user
who has access to the required location.

To change the default logon for the Oracle services, go to :

  -> Control Panel
     -> Services
        -> OracleServiceXXXX (where XXXX is the instance name)
           -> Startup
              -> Log On As

Choose the "This Account" radio button, then complete the
appropriate domain login information.
June 24, 2000 Reji -- Thanks for the question regarding "PL/SQL Qn", version 8.1.6
You Asked
Tom:
     I have a qn related to PL/SQL..Here is a code segment
     that I was trying to write - I am really new to PL/SQL.

     CREATE TYPE PriceRec IS RECORD (
      planid    NUMBER(10),
      plannamecode  CHAR(10));

      PriceCurType IS REF CURSOR RETURN PriceRec;

CREATE or replace procedure jack_acc
( Price_cv IN OUT PriceCurType) IS
   BEGIN
      OPEN Price_cv FOR
         SELECT planid, plannamecode from pricingplan
            ORDER BY planid;
END;
/

I am getting all sorts of erros when I installed this
procedure.
What I am trying to do is, to have this procedure in my db
and I have a crystal report app is going to use this to get
the data.  I was able to put the whole thing in a package
and it works but in crystal reports I can't see the package
so I an trying to create as standalone stored procedure.

How Do I accomplish this in a without using packages.

Reji
and we said...
It would look like this if you want a standalone procedure:

ops$tkyte@8i> create or replace package myTypes
  2  as
  3
  4       TYPE PriceRec IS RECORD (
  5        planid    NUMBER(10),
  6        plannamecode  CHAR(10));
  7
  8
  9        Type PriceCurType IS REF CURSOR RETURN PriceRec;
 10  end;
 11  /

Package created.

ops$tkyte@8i> CREATE or replace procedure jack_acc
  2  ( Price_cv IN OUT MYTYPES.PriceCurType) IS
  3     BEGIN
  4        OPEN Price_cv FOR
  5           SELECT empno, ename from emp
  6              ORDER BY empno;
  7  END;
  8  /

Procedure created.

put the types into a package spec and then refer to the package
name in the types in the standalone procedure.
June 24, 2000 rajesh -- Thanks for the question regarding "oracle 8i services", version oracle 8i
You Asked
Hi Tom!

What are extra services available in Oracle 8i? While
configuring the
Oracle 8i database in Tnsname by using Net admin, its asking for
whethe of
oracle 8i or oracle 8 databases. If you select Oracle 8i it asks
for
service_name. If select 8 database option, then its asks for
sid. What is the
difference between two?
and we said...
see
http://technet.oracle.com/doc/server.815/a68020/ch2.htm#140388
for this specific new feature description.

See
http://technet.oracle.com/doc/server.815/a68020/toc.htm
for an overview of all of the new 8i features over 8.0
June 24, 2000 Anwar -- Thanks for the question regarding "On-line redo log status meaning?", version 7.3.2
You Asked
Hello Tom!

The status of an on-line redo file as indcated by "status"
column of v$log dynamic view is very confusing to me. Can you
please explain it in detail?
and we said...
see (1)
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:338617361970,%7BREDO%7D%20and%20%7BSTATUS%7D
and (2)
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:289016045434,%7BREDO%7D%20and%20%7BSTATUS%7D
for the (1) exceptional and (2) normal values...
June 24, 2000 Anwar -- Thanks for the question regarding "Distributed Option in Oracle 7", version 7.3.2
You Asked
Hi Tom!

Is Oracle Distributed Option required for accessing remote
databases? Also, if there is some restriction on database
version i.e. the version shuld be same on all nodes?
and we said...
Distributed option was required to perform distributed
transactions in v7.x.  If you just query across a database link,
that was OK, if you update over a database link -- that was the
distributed option.

The versions may be hetergenous (eg: 7.3 to 7.1 works ok).
June 24, 2000 Ravinder -- Thanks for the question regarding "Renaming a Index ", version 8.1.5
You Asked
HiTom,

Can we rename a index ? how ?

Ravinder
and we said...
Sorry - I answered that too fast last time.

Alter index <old_name> rename to <new_name>;

is supported starting with version 8.0 of the database...
June 26, 2000 Sankalp -- Thanks for the question regarding "SHowing Messges in Stored procedures onto form.", version 8.x
You Asked
Dear Tom,
   Thnaks for the reply.
a)   With "Displaying messages from stored procedures onto form
", what I meant was, Eg we have a stored procedure LOAN
CAPITALIZATION used for batch process. Can messages displayed
(using dbms_output.put_line...) be displayed on the forms while
calling the procedure through form?
Is there any way out to show to the user the status of the batch
process,?

b) How to display PROGRES BAR in forms5.0. Thsi progress bar
should end when the batch process ends.

Thanks in advance
SANKALP
and we said...
We need to use 2 sessions to do this.  We can run the batch job
in a minimized forms window and "watch" its progress from the
other window.

I started with a procedure like:

create or replace procedure long_time( p_id in number,
                                       p_iterations in number )
as
begin
    for i in 1 .. p_iterations
    loop
        dbms_application_info.set_client_info( p_id ||
                       ' Step ' || i ||
                       ' of ' || p_iterations );
        dbms_lock.sleep( 1 );
    end loop;
end;
/

(you may need to grant execute on dbms_lock to the owner of this
procedure to compile this).  This procedure is your batch job.
I pass into 2 items (in addition to what YOU'll pass it to run
yours...).  The first is a "unique" key, something we can use in
our parent form to identify the row in v$session that represents
our batch job.  The other in this case is how many times this
loop should execute (you in general won't need that one).

I then wrote a standalone form with a block on DUAL and 2
triggers.  They are:

WHEN-NEW-FORM-INSTANCE:
DECLARE
     timer_clock TIMER;
     one_second     NUMBER(7):=1000;
BEGIN
     dbms_application_info.set_client_info
                 ( '1234 Just Starting' );
     set_window_property( FORMS_MDI_WINDOW, WINDOW_STATE,
                          MINIMIZE );
     timer_clock := CREATE_TIMER('CLOCK_TIMER',
                                  one_second,NO_REPEAT);
END;

That trigger simply minimizes our form and then creates a time
to fire in 1 second.  We need to use a timer to run our batch
job since the parent form that will run this form will not get
control back until AFTER the new form instance trigger
completes.

The second trigger in this form is simply:

WHEN-TIMER-EXPIRED:
-- normally, 1234 will be a parameter the parent form will
-- pass to us
-- it'll be used by the parent to display some info (to help
-- find OUR row)
--
-- 15 is for 15 iterations
long_time( 1234, 15 );
exit_form;

So, if you run this form, it'll simply show itself -- minimize
itself -- run the batch job -- and then exit.  The batch job
will constantly be filling in the CLIENT_INFO field in v$session
with our "key" (1234 -- you will pass this in with a unique
value so each client can id their rows) and the step it is on.

I then created another form.  It had a block on DEPT (just as an
example) and a control block (non-database) to show the
progress.  On this control block I put 3 items:

o a push button to run the job
o a text field I use to display the progress message
(name=clock)
o a RED backgrounded text field I'll use to show the "progress
  bar" (name=progress_bar)

On the button I put the following trigger:

WHEN-BUTTON-PRESSED:
DECLARE
     timer_clock TIMER;
BEGIN
       :b1.clock := null;
     run_product( FORMS,
  'C:\Documents and Settings\Thomas Kyte\Desktop\module2.fmx',
                  ASYNCHRONOUS, RUNTIME, FILESYSTEM, '', ''  );
     timer_clock := CREATE_TIMER('CLOCK_TIMER',1000,REPEAT);
     set_item_property( 'b1.progress_bar', WIDTH, 0 );
END;

It just fired off another form and ran it asynchronously.  I
create a timer that fires every second (this will be how
frequently we update our progress bar).  I set the width of the
"progress bar" to ZERO.

I then setup a WHEN-TIMER-EXPIRED trigger that looks like this:

WHEN-TIME-EXPIRED
declare
    l_width varchar2(255);
begin
  if ( GET_APPLICATION_PROPERTY(TIMER_NAME) = 'CLOCK_TIMER' )
  then
    begin
     select to_char(sysdate,'hh24:mi:ss') || ' ' ||
                 client_info
       into :clock
       from v$session
      where client_info like '1234 %';

      if ( :clock like '%Step % of %' )
      then
      l_width := substr( :clock, instr(:clock, 'Step ')+4 );
      l_width := substr( l_width, 1, instr(l_width,'of')-1 );
      l_width := ltrim(rtrim(l_width));
      set_item_property( 'b1.progress_bar', WIDTH,
                              to_number(l_width)*10 );
      end if;
    exception
     when no_data_found then
       if ( :clock <> 'Batch completed...' )
       then
         delete_Timer( 'CLOCK_TIMER' );
       end if;
       :clock := 'Batch completed...';
    end;
  end if;
end;

That timer trigger updates the text field with the contents of
the CLIENT_INFO field and a timestamp (see the Long_Time
procedure above -- it fills in this field).  It also gets out
the "step X of Y" part I put in there and sets the width of our
"red" progress bar to be that wide.  Thats our progress bar.

I do not have forms 5.0 installed which is what you have (I
currently have 6.0) so I cannot give you the forms directly but
I believe the above will get you going in the right direction.
Review & Followup
Rating: 5
March 23, 2001
Reviewer: Helena Markova from Bratislava, Slovakia

Rating: 4
Good idea! May 20, 2003
Reviewer: Andrew Pouckatch from Minsk, Belarus
Thanks

June 26, 2000 Ravi -- Thanks for the question regarding "Encrypting the password in unix text file.", version oracle 8.0.4.4
You Asked
Hi Tom,

I am working as a Oracle DBA. I have a clarification needed from
you. We have some shell scripts in unix(sun Solaris) as cronjobs
in the nights. Typically, these scripts connects to sqlplus and
run some sql and send the reports to us. Also, another script
uses sqlldr to load the data from flat file into oracle database
daily. The statment looks like this.

sqlplus <<EOF
$USERNAME/$PWD
...
...
EOF

or

sqlldr $USERNAME/$PWD control=ctlfilename data=datafilename ...

These variables (USERNAME and PASSWORD) are stored in a separate
flat file in unix. Our shell script sources this file and get
the value of these variables.

My concern is, if some one hacks our unix pwd, then he can also
see this database user name and pwd and I feel that the security
is lost. Can you suggest me, how this problem can be avoided.
That is ,I donot want to store the username and pwd in text
format. I feel that some sort of encrypt mechanism may solve the
problem.

I need your help in this regard. Your earliest reply in this, is
highly appreciated.

Thanks in Advance

With Warm Regards
Ravi Ammamuthu.
and we said...
I prefer to use OS authentication for this.  In this fashion you
would schedule the jobs to run as a unix user "X".  You would
have a database account, for examples "OPS$X".  You would have
granted to appropriate priveleges to OPS$X.  The unix user X can
now log into sqlplus using just "/" (no username/password).
Same with sqlldr, exp, imp, and so on.

When I set up my "oracle software account", I create an OPS$
account for that user and never use a password ever again.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:280615845330,%7BOS%7D%20and%20%7BAUTHENTICATION%7D
and
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:326217141412,%7BOS%7D%20and%20%7BAUTHENTICATION%7D
for examples of what I mean.
June 26, 2000 Syed -- Thanks for the question regarding "FORM CONVERSION FROM V3 TO V5", version Forms 5.2
You Asked
I am working on a conversion project from Oracle CUI to Oracle
GUI, that is, from V6 to V8. I am using Forms 5.2.

My question is;

1. If i leave old commands like next_field, previous_field,
field_characteristic, set_field as is, and donot change it to
new version, then what will be the impact?

2. Are these new versions have any improvement in performance?
and we said...
Hopefully, you really mean to v6 as it would be somewhat a waste
of time to migrate everything to an obsolete version of
software.

See
http://osi.oracle.com/~tkyte/sqlform3_to_6i.zip
for some info on this topic.
June 26, 2000 Anuj -- Thanks for the question regarding "how To PASS TABLE AS ARGUMENT TO PROCEDURE", version 4
You Asked
Hi tom ,
i am facing a problem. i want to pass table as a parameter to
PL/SQL cartridge on the basis of which it will do its
calculation. well i am passing a table as parameter coz i have
to pass some argument which are depending upon the database
query
well please responsed ASAP.
and we said...
You will want to read about dbms_sql (or EXECUTE IMMEDIATE in
Oracle8i, release 8.1 -- you don't mention the database
version).

See
http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:dbms_sql
for some examples....

Also see
http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:cellsprint
for some examples of the owa_util routine that prints
queries out for you dyanmically -- if that is what you are
trying to do.
June 26, 2000 Farah -- Thanks for the question regarding "8i Automated Standby Database", version 8i
You Asked
We are looking into creating a standby database for production,
and also building a read-only database for reporting.

What is "Oracle8i Automated Standby Database"?  How
stable/reliable is it... considering that this is a new feature?
 If anyone has implemented it, please list any issues or
problems encountered in configuring it, steps taken to switch
over to standby in case production database is down, are there
any performance issues or overhead on the production database.
How does it compare to the Parallel Server and Advanced
Replication Option?

Thanks,
Farah
and we said...
See
http://www.oracle.com/oramag/oracle/00-May/o30tom.html
for an article I did on standby databases, OPS,
Replication and other features.  It answers the bulk of your
questions.

As for "considering it is a new feature" -- the standby database
was introduced in Oracle7.3 -- some 4 years ago.  Its not really
too new of a feature.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76995/toc.htm
for in depth documentation on this feature.
June 26, 2000 Elvis -- Thanks for the question regarding "Dynamic SQL", version Oracle version 8.1.5
You Asked
I would like to know if procedures could be executed
dynamically.
What I mean that the name of the procedure is not know at design
time.  Let me explain.  I have a table which has 2 columns. One
is The Loan Number (an identifier) and the other is The
Transaction Number.  In my procedure I loop through this table
and, depending on the transaction number, I call another
procedure. The loan Number is passed as a parameter to the
procedure. Each Transaction Number has its own procedure.  The
proedures are named according to their transactions numbers e.g
prc_012 for transaction number 012, prc_057 for transaction 057
and so on. There are 75 transaction Numbers and their number
keeps growing everyday.  In the table, a loan number could have
anything from 1 to 75 transactions.  I could use 75 if then
elsif .. statements.  e.g IF transaction_number = '001' THEN
prc_001(loan_number); ELSIF transaction_number = '002' THEN
prc_002(loan_number);  ELSIF ........ IF transaction_number =
'075'  THEN prc_075(loan_number);  END;.  But since this would
not look good and also since the transactions keep increasing
frequently, I would like to build the name of the procedure into
a variable and then execute the procedure dynamically.  e.g.
prc_name := 'prc_'||transaction_number;  EXECUTE IMMEDIATE
prc_name;.  However, this will not work since only DML
statements can be executed dynamically.  Is there another way???
I am looking forward to a positive reply.
Thanks
Elvis Fernandes
and we said...
Any statement can be executed dynamically.

to run a procedure dynamically, you must put it in a block:

begin
    execute immediate 'begin ' ||
                       procname || '( :loan_number ); end;'
    using loan_name;
end;
/

in plsql for example dynamically executes the procedure in
PROCNAME using a bind variable whos value is in loan_name.
June 26, 2000 Jack -- Thanks for the question regarding "Using multilple sets of Oracle binaries on same server", version 8.0.5.2 & 8.1.6
You Asked
We are setting up two Sun servers in two different buldings
using Sun clustering and are using EMC dasd.  One will be the
primary and one the backup or failover server.  We currently
have one set of binaries for all the instances/db's on the
server.  Unix support has asked if we could set up a set of
binaries for EACH instance/db.   Per Oracle Tech support, this
is feasible, but they had heard of no one doing it.  We are NOT
running OPS.
It seems this would be an Oracle maintenance nightmare since if
we have say 15 instances/db's on one server, each new release of
Oracle or a patch set upgrade would mean 15 installs.  What is
your opinion on this?
and we said...
You can do this, I myself do it to support >1 version on the
same server.  I typically setup a UNIX account named after the
version of the software (eg: i have an ora716, ora734, ora806,
ora816 user on the same box).  Each has their own full install.

You can do the same for Oracle Sids if you wanted -- create a
unix account named after the sid, install the software into each
account and go.  Yes, it introduces a maintenance overhead as
you have 15 copies of the same software everywhere.

What I would actually do in this case myself -- I would merge
all 15 instances into 1 instance and be done with it.  Unless
they are "test", "development", and "production" versions of the
same application -- they should be all in the same instance.
You'll get more bang for the buck from your servers this way and
with tablespace point in time recovery and other features --
none of the old "but I need my own instance" arguments stand up
anymore.
June 26, 2000 Amitabh -- Thanks for the question regarding "Doc attachment in Oracle Alert", version 10.7NCA
You Asked
how to attach a .doc or .rtf file with the periodic alert . So
that the email should contain subject, some text and an
attachment . In the .doc file i want to pass data from alert .
and we said...
I asked someone who works with applications much more then I do
for some input and they say:

..
Out of the box, 10.7 Alert doesn't support an email attachment.
Interestingly, you can choose to send the contents of a file in
place of the body of an Alert email message.  This just inserts
the contents of the file inside the body of a message - works
fine if your file is text, messy if it is a .doc, .ppt, etc....

One option is to create an Alert action that submits an OS
command line command, as Todd mentioned.   This should work as
long as you can execute a command/command file on your operating
system (Unix or NT) that can send an email with a file
attachment. You could either send a standard file name each
time, or you could pass a parameter with the file name.

Another possibility would be to alter the actual email command
call Alert uses for messages.   That is what I did for the
standalone NT demo systems.   This would have larger implication
on Alert message processing and would need to be approached
carefully, if at all.
.........

me again.

Building on that, I can recommend a command line tool I've used
in the past to email things with attachments.  Its called "mutt"
and works on Unix.  You can pick that up at
http://www.mutt.org/
June 26, 2000 Joe -- Thanks for the question regarding "WebDB 3.0 production release date", version 3.0
You Asked
We are still waiting for WebDB 3.0 production release.
Last year someone from Oracle told us it would be by February,
2000.  Then we were told that it would be available by April,
2000.  Now it is almost July, 2000.  Could you please tell us
the more accurate released date for WebDB 3.0.  Thanks a lot.
and we said...
As of June 2000:

WebDB 3.0 is currently Beta.  WebDB 3.0 has a planned date
of mid August for Release To Manufacturing (RTM). This would
mean that customers could get WebDB some time in September.

The above is of course predicated on the successfullness of the
beta.
June 27, 2000 Pat -- Thanks for the question regarding "Report with row dependencies", version 2.2
You Asked
Ok, this is probably in a FAQ for newbies, but I couldn't seem
to find it. I'm using WebDB 2.2 with Oracle 8.1.6. Let's say I
have a table of users which looks like this:

UID    StartDate  Amount
------ ---------  ------
U001   06-Jun-00  23.4
U001   07-Jun-00  43.1
U002   07-Jun-00  12.8
U001   08-Jun-00  15.2
U002   09-Jun-00  17.24
U001   05-Jun-00  13.6

What I'd like to do is generate a report which shows these dates
and "delta amounts" through a WebDB report (by SQL query).
Effectively, the report will need to take into consideration the
user's input (ie, by UID), sort the results by date, and present
the changes between the current and next value. For example, if
the operator chooses to display U001, the report should look
like:

StartDate  Value  NewValue
---------  ------ --------
05-Jun-00  13.6   37.0
06-Jun-00  23.4   66.5
07-Jun-00  43.1   58.3
08-Jun-00  15.2   In progress

Essentially, NewValue = today's amount + tomorrow's amount
I'll need to do some similar reports which rely on calculations
with the same column & previous/next row.

I've not had much luck with the WebDB docs in non-trivial cases
like this. Thanks in advance for your help!
and we said...
this is definitely note a newbie question.  These are very hard
queries to do.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:304616560846for
one approach.

In your case above, if the dates are contigous (you only want a
NewValue for TODAY when there is a TOMORROW -- it can be NULL if
there is no TOMORROW) we can do it in an easier fashion with a
simply view.  Here is an example:

ops$tkyte@8i> create table t
  2  ( user_id   varchar2(25),
  3    startDate date,
  4    amount    number,
  5    primary key (user_id,startDate)
  6  );

Table created.

ops$tkyte@8i> insert into t values ( 'U001','06-Jun-00', 23.4 );
ops$tkyte@8i> insert into t values ( 'U001','07-Jun-00', 43.1 );
ops$tkyte@8i> insert into t values ( 'U002','07-Jun-00', 12.8 );
ops$tkyte@8i> insert into t values ( 'U001','08-Jun-00', 15.2 );
ops$tkyte@8i> insert into t values ( 'U002','09-Jun-00', 17.24
);
ops$tkyte@8i> insert into t values ( 'U001','05-Jun-00', 13.6 );

ops$tkyte@8i> create or replace view V
  2  as
  3  select a.user_id,
  4         a.startDate,
  5         a.amount,
  6         nvl2( b.amount, a.amount+b.amount, null ) newValue
  7    from T a, T b
  8   where a.user_id = b.user_id (+)
  9     and a.startDate+1 = b.startDate (+)
 10   order by a.startDate
 11  /

View created.

ops$tkyte@8i> set autotrace on explain
ops$tkyte@8i> select * from v where user_id = 'U001'
  2  /

USER_ID                   STARTDATE     AMOUNT   NEWVALUE
------------------------- --------- ---------- ----------
U001                      05-JUN-00       13.6         37
U001                      06-JUN-00       23.4       66.5
U001                      07-JUN-00       43.1       58.3
U001                      08-JUN-00       15.2

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   VIEW OF 'V'
   2    1     SORT (ORDER BY)
   3    2       NESTED LOOPS (OUTER)
   4    3         TABLE ACCESS (BY INDEX ROWID) OF 'T'
   5    4           INDEX (RANGE SCAN) OF 'SYS_C0025931'
(UNIQUE)
   6    3         TABLE ACCESS (BY INDEX ROWID) OF 'T'
   7    6           INDEX (UNIQUE SCAN) OF 'SYS_C0025931'

ops$tkyte@8i> set autotrace off

So, now we just build our webdb report on the view V and
parameterize it by user_id.
Review & Followup
Rating: 5
This is real gem! August 11, 2003
Reviewer: Richard from Oxfordshire, UK
I think I'll be putting this in my *Must Have* SQL toolbox... this sort of
problem can drive you crazy!

June 27, 2000 Anuj -- Thanks for the question regarding "How to pass argument in PL/sql cartidges", version 4.
You Asked
Hi ,
i want to know how to pass table as argument to PL/sql
cartridges in Orcale web application server using oracle 8i.
well the reason is the form fields are geting genreated on the
basisi of a query which can vary from people to people. and i
want to send these fields to the next pl/sql cartridge.

well please tell me how to send a table as pl/sql cartridge
argument
Anuj
and we said...
Its really easy.  If you have a form that has >1 field named the
same, all of the values will be passed as a PLSQL table to the
called routine.

For example, say you had the form:

<form action=my_pkg.my_procedure method=post>
<input type=text name=x>
<input type=text name=x>
<input type=text name=x>
<input type=submit>
</form>

Then, you can code:

create or replace package my_pkg
as
   type myArray is table of varchar2(255)
                        index by binary_integer;

   procedure my_procedure( x in myArray );
end;
/

create or replace package body my_pkg
as

   procedure my_procedure( x in myArray )
   is
   begin
       for i in 1 .. x.count loop
         htp.p( 'x(' || i || ') = ' || x(i) || '<br>' );
       end loop;
   end;
end;
/

and that'll do it.  Just make sure to define the tables of type
VARCHAR2(n) -- do not attempt to make a table of dates or
numbers -- only strings.  Thats the only supported array type.
They can be of varying widths from 1 byte to 2000/4000 (v7, v8).

There are builtin types you can use as well:

owa.vc_arr  -- varchar2(2000)
owa_util.id -- varchar2(30)

but I prefer to use my own types.
Review & Followup
Rating: 4
How to pass argument in PL/sql cartidges March 14, 2001
Reviewer: Jing from CA
Yes, it's quite helpful for me.

I have another question based on this one. What if I want to pass same the
PL/SQL TABLE parameter/variable to different 2 other web pages or procedures.
For example, in the example of yours,
<form action=my_pkg.my_procedure method=post>
  <input type=text name=x>
  <input type=text name=x>
  <input type=text name=x>
  <input type=submit>
  </form>
This form is only going to my_pkg.my_procedure, what if I need this "x" to be
passed to another procedure, say, my_pkg.my_new_procedure?
Thanks.
Jing
E-Mail: jing-cj_chen@usa.net

June 27, 2000 chen -- Thanks for the question regarding "procedure auto executed", version Oracle 8.1.6 & OAS4.0.8
You Asked
Dear sir,
There are two questions I want to ask you:
1.I have submited a procedure which should be executed half an
hour later.If this procedure will not been executed when the
computer running the database and the oas is restarted within
this hour?

2.There is procedure which should be executed every an hour,
  I have submited this procedure by DBMS_JOB.submit utility.Now
  I want to know if this procedure can be auto executed when the
  computer is restarted.

  Thank you very much!

Best Regards
John Chen
and we said...
I'm assuming you submitted these via DBMS_JOB.

Jobs submitted via dbms_job will be run as close to their
scheduled time as possible (but never BEFORE, always a little
AFTER).  The things that will impact the job as far as when it
starts are:

o the availability of a job_queue_process to run it.  If you
have job_queue_processes = 1 and you get 2 jobs to run at the
same time -- only 1 will execute and then the other.  You
control the concurrency of background jobs by raising or
lowering the number of job_queue_processes.

o the frequency with which these jobs inspect the queue.
job_queue_interval = NN where NN is some number of seconds
controls this.  If you set NN = 120, the jobs will run within 2
minutes AFTER they are scheduled (given the restriction of #1
above).  So, if the job was scheduled to run at 12:00:00, it
might run as late as 12:01:59 (or later given #1).

o if the machine (database) is not up -- the jobs will be run
when the server comes up (again #1 above will limit how many run
concurrently).

OAS and its available does not affect any of this.  Its all in
the database.
June 27, 2000 Najmal -- Thanks for the question regarding "Oracle user authentication in LDAP server with 3 tiers (you cannot)", version 8.1.6
You Asked
I am using Oracle 8.1.6, Netscape Drirectory Server(LDAP),
Oracle application server 4.0.7, Oracle developer server 6.0.
Oracle and Netscape Directory server is on different servers.
Now how do I authenticate oracle users on LDAP server while
accessing
an oracle application through a web browser.

I hope my question is clear. Please advice

Thank You
Najmal
and we said...
The answer is you can't mix two-tier and three-tier
authentication schemes.

In two-tier, SQL*NET would authenticate x.509 certificate
credentials against any LDAP server that has functionality >=
OiD (mostly from a fine granular access control perspective).
Developer on 2-tier using SQL*NET would use this.

Web-based apps can use LDAP, but the LDAP schema above is not
designed/optimized for web 3 tier authentication.  The problem
is one of trust.  Your browser/jvm would have to give your
credentials to a middle tier -- this middle tier would then have
to be allowed to present your credentials to a 3 tier -- the
database.  The database would have to accept these credentials.
Well, if we allowed that (if anyone allowed that) then the who
"security" thing is out the window.  If I can give me identity
to someone else and they can present those credentials to yet
another party and say "its him, let him in" -- then ANYONE I
gave my credentials to would be able to keep them and use them
to "become" me at any point in time.  The trusted path is broken
-- once you introduce the "man in the middle".
June 27, 2000 ade -- Thanks for the question regarding "lob modofication -- syntax", version 8.1.6.0.0
You Asked
I have a problem with modifying lob.
the following statemet produces an error. 'missing left
parenthesis' with asterix on 'store'. I've tried several other
combinations, but still have the same problem.

alter table clientsession modify
lob(hashtable) store as (tablespace amtrak_lobs);
and we said...
alter table clientsession
modify (hashtable) <<<<===== modify needs something after it
lob(hashtable)
store as (tablespace amtrak_lobs);
June 27, 2000 -- Thanks for the question regarding "Trace files from ARCH in 8i", version 8.1.5
You Asked
Oracle 8i generates trace files with  'trc' as suffix (e.g.
testbox_arc0_17349.trc) in the BDUMP directory whenever online
log files
are archived. It also sometimes generates a log file during
start-up and shut-down.
Most of the time it tells me which blocks are archived. It
doesn't seem like they are of much use.
Do they serve other purposes which I have not come acrossed yet
?
Is there a way to turn it off ?

Thanks.
and we said...
In 8.1.5 -- no, this is the "normal and expected behaviour".
There was an enhancement request filed against 8.1 for:

Hdr: 741649 8.1.3 RDBMS 8.1.3 PRODID-5 PORTID-453
Abstract: NEED TO GET A WAY TO DISABLE/CONTROL TRACE INFORMATION
WRITTEN TO TRACE FILES

This is implemented in 8.1.6 through "log_archive_trace"
parameter.  Prior to that, there is no way to disable this
informational trace.
June 28, 2000 Simon -- Thanks for the question regarding "export utility", version Oracle 7
You Asked
I have a script that exports all schema's for a set array of
users using a ksh script run under cron from root.

The problem is that some of the users use the csh & some use the
ksh, those that use the ksh, the export works fine for those
that
use the csh the export fails with the following error messages:

EXP-00000: Message 0 not found; No message file for
product=RDBMS, facility=EXP
EXP-00222: Message 222 not found; No message file for
product=RDBMS, facility=EXPBacking up the
cvu schema

Message 206 not found; No message file for product=RDBMS,
facility=EXP: Release 7.3.4.0.0 - Producti
on on Tue Jun 27 22:35:50 2000

Copyright (c) Oracle Corporatio
Export terminated unsuccessfully

any advice that you may have would be much appreciated.
and we said...
The environment is not setup for those users.  You could set up
a script in the /usr/local/bin that

- is a ksh script
- sets the oracle_home
- sets the oracle_sid
- sets the ld_library_path
- sets the path
- sets anything else you need
- does the export

and run that script from the root cron job INSTEAD of running
export directly.  The root cron job, running under ksh, is going
to try and run the ksh under the users and since they have their
setup in the .cshrc and its not being run, the oracle_home,
oracle_sid, path and such are not set.  Using a SCRIPT that
explicity sets the environment would be the correct approach for
all cron jobs (you can never be sure what the environment will
be unless you yourself set it).
June 28, 2000 Hans -- Thanks for the question regarding "Realocate unused blocks of tablespaces", version 7.3.4.0.0
You Asked
I'm using a query for auditing my tablespaces:

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

column tablespace_name    heading 'Tablespace'     format a20
column mbytes_blocks      heading 'Total MBytes'   format
999999.9
column sum_alloc_blocks   heading 'Total Blocks'   format
99999999
column sum_free_blocks    heading 'Free Blocks'    format
99999999
column percent_free       heading 'Free Percent'   format 9999
column biggest_block      heading 'Free Biggest'   format
99999999
column count_blocks       heading 'Free Groups'    format 999999

select     tablespace_name, -
        0.002048 * sum_alloc_blocks as mbytes_blocks,-
    sum_alloc_blocks, -
    sum_free_blocks, -
    trunc (100*sum_free_blocks/sum_alloc_blocks) as
percent_free, -
    biggest_block, -
    count_blocks -
    from (select     tablespace_name, -
            sum(blocks) sum_alloc_blocks -
                from dba_data_files -
            group by tablespace_name), -
                (select tablespace_name fs_ts_name, -
                    max(blocks) as biggest_block, -
                    count(blocks) as count_blocks, -
                    sum(blocks) as sum_free_blocks -
                    from dba_free_space -
                    group by tablespace_name) -
    where tablespace_name = fs_ts_name;

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

The result of this query is (as an example):

Tablespace           Total MBytes Total Blocks Free Blocks Free
Percent Free Biggest Free Groups
-------------------- ------------ ------------ -----------
------------ ------------ -----------
CV_ASMGR                      1.0          512         476
    92          476           1
EDM_ARCHIVE                   1.0          512         151
    29          151           1
EDM_ATTRDATA                314.6       153600       69514
    45        30884          27
EDM_ATTRIBUTES               10.5         5120        4225
    82         4225           1
EDM_AUDIT_LOG                10.5         5120        4619
    90         4619           1
EDM_FILE_BACKUP             314.6       153600       44504
    28        24604         253
EDM_FILE_DIRECTORY          157.3        76800       43732
    56        38542         222
EDM_HISTORY                  31.5        15360        5989
    38         5989           1
EDM_ROLLSPACE               188.7        92160       77269
    83        77269           1
EDM_SYSTEM                   41.9        20480       14006
    68        13606          10
EDM_TEMPSPACE               104.9        51200       51199
    99         6699          90
RBS                          10.5         5120        4339
    84         4339           1
SYSTEM                       41.9        20480       15166
    74        15166           1
TEMP                          5.2         2560        2559
    99          739          15
TOOLS                        10.5         5120        4219
    82         4219           1
USERS                         1.0          512         511
    99          511           1

16 rows selected.

As you can see the column 'Free Groups' of the tablespaces
EDM_FILE_BACKUP and EDM_FILE_DIRECTORY
are very large.

Q1: What are the consequences of these large values (performance
or not usable because they are to small)?
Q2: How can I realocate these blocks to reuse that space again?
and we said...
Just to straighten out some terms:

"free groups" sounds too much like "freelist groups".  Your free
groups are really the count of "extents that are not allocated
to any object" or "free extents".  Your "

You have for example:

Tablespace      Total  Total  Free   Free   Free       Free
                MBytes Blocks Blocks Pct    Biggest    Groups

EDM_FILE_BACKUP 314.6  153600 44504  28     24604         253

You can issue "alter tablespace edm_file_backup coalesce" and
see if some of the extents are actually contigous (this will
make them become 1 larger extent).

Having many free extents in itself is not necessarily bad, what
can be bad is if the extents can never actually be used due to
their being a "weird" size (too small for next extents and
such).

As to whether having 253 free extents is "bad" or not depends on
a couple of factors:

o as a ratio to the total number of extents in the tablespace.
The more total extents you have, the more "gaps" you will
naturally expect if you drop and recreate objects lots.

o are the extents usable.  Is the size of many or most of the
free extents *smaller* then the NEXT_EXTENT size of any object?
Find the minimum next_extent size and then determine how many of
these free extents are smaller (not usable when an object
extends) or larger (these will be used).

o are the extents multiples of the next extent sizes of your
objects.  If you are using a uniform sizing method (suggested --
have "pctincrease = 0" for all objects and have next extents
that are nice multiples of eachother -- better yet, have ALL
next extent sizes for all objects be EQUAL), they will be.  If
they are not, you'll end up with more unusable extents after
something does extend (eg: i need 5meg more, i'll take a 6meg
free extent, get my 5 and leave 1 leftover.  1m is too small for
anything else hence it'll just sit there).

The only way to reallocate that space is to physically move the
objects out and then back in.  It typically is never worth
the effort (by getting the data out and putting it back in
you'll get nicely formatted block, no migrated rows, less
chaining, perfect indexes -- any performance increase will be
due to that -- NOT due to getting the objects contigous or in a
single extent).

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:47812348053,%7BMOVING%7D
for the details on moving these objects around to achieve this.
June 28, 2000 Arie -- Thanks for the question regarding "cleaning up grants", version 8.1.6.1
You Asked
Hi Tom,

Lots of grants in our database are redundant. Lots of them come
'automatically' by using the security-screens in Oracle
Discoverer. For example, users get grants directly, via their
role(s), and also via public.

Are there utilities or scripts to detect these situations or,
even better, revoke the redundant grants?

Thanks,
Arie Smitskamp
and we said...
No, not that I am aware of.

In many cases the grants are not redudant.  For example, I might
have "select on emp" via a role but if I want to have a stored
procedure that accesses emp using definers rights (the default
model in 8.1 and the only model in 8.0 and before), I must have
select granted on emp directly to me.  The grant in this case
isn't redudant -- its needed.
June 28, 2000 Arokiasamy -- Thanks for the question regarding "Input file", version 8
You Asked
How do I find if the incomming column(field) from an external
source is an INTEGER or CHAR?
Is there a function called ISchar or ISnum in SQL?
and we said...
You can write your own very easily.  To find if something was a
number or a date -- i would normally just convert it and catch
the exception.  To verify something consists of a set of
specific character, I use translate+replace.  For example:

ops$tkyte@8i> create or replace
     function is_num( p_str in varchar2 ) return number
  2  is
  3          l_data number;
  4          not_a_number exception;
  5
  6          pragma exception_init(not_a_number,-1722 );
  7  begin
  8          select to_number(p_str) into l_data from dual;
  9          return 1;
 10  exception
 11          when NOT_A_NUMBER then
 12                  return 0;
 13  end;
 14  /

Function created.

ops$tkyte@8i>
ops$tkyte@8i> create or replace
     function is_alpha( p_str in varchar2 ) return number
  2  is
  3          l_alpha varchar2(50) default
                             ' abcdefghijklmnopqrstuvwxyz';
  4  begin
  5          if ( replace(
                   translate(lower(p_str),
                         l_alpha,rpad('a',length(l_alpha),'a')
                             ),'a','') is null )
  6          then
  7                  return 1;
  8          else
  9                  return 0;
 10          end if;
 11  end;
 12  /

Function created.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> select is_num('2') from dual;

IS_NUM('2')
-----------
          1

ops$tkyte@8i> select is_num('a') from dual;

IS_NUM('A')
-----------
          0

ops$tkyte@8i>
ops$tkyte@8i> select is_alpha( 'how now brown cow' ) from dual;

IS_ALPHA('HOWNOWBROWNCOW')
--------------------------
                         1

ops$tkyte@8i> select is_alpha( 'how now brown cow!' ) from dual;

IS_ALPHA('HOWNOWBROWNCOW!')
---------------------------
                          0
June 28, 2000 Javier -- Thanks for the question regarding "Pro C/C++ -- what compiler on windows", version 8i- 8.1.5.0.0
You Asked
Dear Tom,

I have Oracle 8i version 8.1.5.0.0 Enterprise, I will like to
know where the complie software is located or name of it to make
a exe file.  I have the Pro C/C++ that came with Oracle but I am
not able to find a complier to make a exe file.

Thank you...
and we said...
Since you say ".exe" I'll assume you are using Windows.  In that
case, we support MS Visual C/C++ as the compiler.  You'll need
that in order to build an application on NT/95-98/2000 (for 2000
you need 8.1.6)
June 28, 2000 Helfried -- Thanks for the question regarding "reducing reorganisation time of large indexes and tables", version 8.0.5
You Asked
What I did is the following (it is possible to open the database
in exclusive mode for a short time once a week):

* put temporary-, data- and index-tablespace on different
devices
* starting the database with an optimized parameterfile (larger
SGA)in exclusive mode
* using drop index / create index and export /truncate table /
import (export/import to/from an other device by another
controller)

What else can I do to reduce total amount of reorganization-time?
and we said...
to reduce the reorg time of a table -- stop doing it. Seriously.
You shouldn't have to do it.

If you are concerned with chained/migrated rows (only reason I
could think of for wanting to do this) -- analyze the table and
list the chained rows.  Create a temp table with this rows,
delete them from the "real" table and then insert them back.
They are no longer chained/migrated.  You can do this online.

For the indexes, in the rare cases where you do want to rebuild
them -- rebuild them, don't drop and recreate.  By rebuilding,
we don't have to sort and have lots less data to read through
(indexes are smaller then their base tables).

In 8i, you can do the index rebuild ONLINE meaning all DML can
take place against the table while you are rebuilding (no
downtime).

In 8i, you can also "alter table T move ..." to "rebuild it"
(but again, I've never ever rebuilt a table -- "dechained" it
maybe, rebuild it -- never.  I like the alter table move for the
case where you are totally reorganizing a database as it leaves
constraints and all in place and unaffected -- you only need to
rebuild the indexes after you move the table)

Partitioning and parallel processing can help here as well.
Partition the really large indexes and rebuild the partitions in
parallel.
June 28, 2000 Katrin -- Thanks for the question regarding "Security with respect to invoker's rights procedures", version 8.1.6
You Asked
I read the Oracle technical white paper, Database Security in
Oracle 8i, dated November 1999, to understand about new security
features provide in 8i.

On pages 8-9, under the header "Flexible Procedures To Lower
Cost of Ownership", the paper discusses the definer's rights
procedures vs. invoker's rights procedures.  With regards to
invoker's rights procedures, it is stated at the very end that
"the result is stronger security at a lower cost of deployment".

I remember back in 1994, we suddenly had to upgrade to a
new release of Oracle 7 (I think it was 7.1.4) because we were
told that the older release allowed a Trojan Horse attack via
stored procedures.  I remember this well because I had written
a software that suddenly broke when the new release was
installed.

The problem was that prior to the new release, stored procedures
by default operated with the invoker's rights.  So, A could give
B access to procedure A.p.  The procedure would be advertised
as doing something while it would also do something else that
would not be advertised.  For example, A could give B access to
table A.t; then since the procedure A.p would be invoked with
B's access rights, the procedure could read from table B.t, to
which A ordinarily would have no access, and write to A.t.  So,
now A has a copy of the data in B.t that would otherwise not
have been available to A.

Is there any safeguard in the way Oracle 8i implements invoker's
rights procedures to prevent a scenario like the one I described
above?

Thanks.

Katrin
and we said...
There must have been something else you were thinking about --
stored procedures have ALWAYS operated with the base
privileges of the creator of the procedure -- always.

The 7.0 manual stated:

<quote v7.0 concepts manual page 18-7>
Privileges Needed to Create or Alter a Procedure

To create a procedure, a user must have the CREATE PROCEDURE or
CREATE ANY PROCEDURE system privilege. To alter a procedure;
that is, to manually recompile a procedure, a user must own the
procedure or have the ALTER ANY PROCEDURE system privilege.

Additionally, the user who owns the procedure must have the
required privileges for the objects referenced in the body of a
procedure. To create a procedure, you must have been explicitly
granted the necessary privileges (system and/or object) to all
objects referenced by the stored procedure; you cannot have
obtained the required privileges through roles. This includes
the EXECUTE privilege for any procedures that are called inside
the stored procedure being created. Triggers also require that
privileges to referenced objects be granted explicitly to the
trigger owner. Anonymous PL/SQL blocks can use any privilege,
whether the privilege is granted explicitly or via a role.
</quote>

That is the definition of definers rights -- it has always been
that way.

As to your example above -- I can actually do that in any
release of Oracle from 7.0 on up!  Its not a trojan horse though
(there was a trojan horse bug in 7.0.13 fixed in 7.0.14 but
released as 7.0.15.  It had to do with the CREATE PROCEDURE priv
-- if you had CREATE PROCEDURE, you could actually "CREATE OR
REPLACE SOMEONE-ELSES.PROCEDURE".  So, you could replace a
system procedure with one you wrote that does what it should
have PLUS anything else SYS could do.  Thats the trojan
horse.)...

So, there is a way to do what you describe above today -- with
7.0 and up.  It is not straight forward (but once you see how to
do it it is rather straight forward).  I would also not classify
it as a bug.  You, the owner of the database, control the code
in the database.  You control who may or may not put code in the
database.  You control what types of privileges the owner of the
code has.  If you "over privilege" people -- in any environment
-- you run the risk of "malicious code" out there.  You should
not be placing into your database any code you do not "trust".

What you are looking for perhaps is Mandatory Access Control
(MAC) -- something we support with our "trusted" Oracle (a b1
multi-level secure implementation of the database).
June 28, 2000 Cliff -- Thanks for the question regarding "Cancelling asynchronous ADO OLE DB queries", version 7.3.4.4.0
You Asked
We would like to use ADO asynchronous queries to give our users
the ability to cancel long queries.  We have a test case in
which we invoke the recordset Cancel method from within its
FetchProgress event if the user clicks on a cancel button.  This
technique works well from the user point of view, but there's a
question about whether Oracle continues to process the query
after it has been cancelled.  Some contend that this technique
will degrade server performance because it will encourage users
to create these resource-consuming orphans.

When ADO is used to terminate a query, does Oracle terminate the
query on the server side, or is it functionally equivalent to
just breaking the connection between the client and the server?
and we said...
You know, I do not know.  There are OCI (Oracle Call Interface)
API's to cancel queries (in effect send a ctl-c to the server)
but I don't know if ADO uses them or not.

To find out, you can simply query the database to see whats
running.  Start a long running query as some user you can
identify (eg: let them log in only once or submit some query you
will recognize).  Then in SQLPLUS you can run the following
script:

-------------- showsql.sql ------------------------------------
column status format a10
set feedback off
set serveroutput on

select username, sid, serial#, process, status
from v$session
where username is not null
/

column username format a20
column sql_text format a55 word_wrapped

set serveroutput on size 1000000
declare
    x number;
begin
    for x in
    ( select username||'('||sid||','||serial#||
                ') ospid = ' ||  process ||
                ' program = ' || program username,
             to_char(LOGON_TIME,' Day HH24:MI') logon_time,
             to_char(sysdate,' Day HH24:MI') current_time,
             sql_address, LAST_CALL_ET
        from v$session
       where status = 'ACTIVE'
         and rawtohex(sql_address) <> '00'
         and username is not null order by last_call_et )
    loop
        for y in ( select max(decode(piece,0,sql_text,null)) ||
                          max(decode(piece,1,sql_text,null)) ||
                          max(decode(piece,2,sql_text,null)) ||
                          max(decode(piece,3,sql_text,null))
                               sql_text
                     from v$sqltext_with_newlines
                    where address = x.sql_address
                      and piece < 4)
        loop
            if ( y.sql_text not like '%listener.get_cmd%' and
                 y.sql_text not like '%RAWTOHEX(SQL_ADDRESS)%')
            then
                dbms_output.put_line( '--------------------' );
                dbms_output.put_line( x.username );
                dbms_output.put_line( x.logon_time || ' ' ||
                                      x.current_time||
                                      ' last et = ' ||
                                      x.LAST_CALL_ET);
                dbms_output.put_line(
                          substr( y.sql_text, 1, 250 ) );
            end if;
        end loop;
    end loop;
end;
/

column username format a15 word_wrapped
column module format a15 word_wrapped
column action format a15 word_wrapped
column client_info format a30 word_wrapped

select username||'('||sid||','||serial#||')' username,
       module,
       action,
       client_info
from v$session
where module||action||client_info is not null;
------------------- eof ----------------------------------

That script will show you everyone who is logged in, what SQL
they are executing if active and other information....  If you
still see an active session owned by your user running your
query after you cancel -- they have not really cancelled the
query.

Let me know what you discover...

(you can also use RESOURCE profiles as a query governor!)
June 28, 2000 Tim -- Thanks for the question regarding "View and Tables -- can i modify a view", version V 7.3.4
You Asked
Can you manipulate data through a view? OR
Can you only update and insert data in the table itself?
and we said...
You can do pretty much anything through a view that you can to a
table if the view is determined "updateable".  A view on a
single table is almost always updateable (unless you performed a
function on each and every column in the view, then we cannot
update that).

In Oracle8.0 and up -- you can modify absolutely ANY view you
want to, all views are updateable (if we cannot do it
automatically, you can teach us how to do it with instead of
triggers)
June 28, 2000 sadhanandham -- Thanks for the question regarding "Oracle intermedia for windows media server.", version 8i
You Asked
Hi,

 Can I stream my mp3 in windows media server
using oracle intermedia??
and we said...
Intermedia does not stream.  We can use a "Realserver plugin"
to perform the streaming however.

See
http://technet.oracle.com/products/intermedia/
and follow the link to the "RealServer Plugin".
June 29, 2000 Bhavesh -- Thanks for the question regarding "Where is the view DBA_WAITERS ?", version 8i
You Asked
Hi Tom,

I haee seen (in Jason Caochman's book on DBA certi. guide
(for ver 8.0)) following query to find out what session is
holding the object. I am not finding this view (even from
SYS or SYSTEM) on my Sun/Solaris/Oracle8i ?

SQL> select sid, serial# from v$session
     where sid in (select holding_session from dba_waiters);

What I want to do is, thenafter I wano to kill the session
using alter system command.

tia,
regds,
Bhavesh Patel.
and we said...
The DBA_WAITERS view is defined in $ORACLE_HOME/rdbms/admin/catblock.sql.  You
would install this view (and the others in it) by

o using svrmgrl
o connecting as SYS or internal
o running catblock.sql

You can then use utllockt (in the same directory) to have a wait graph displayed
for you -- you just need run utllockt and it'll show you the blocking session
and all of the people waiting on it.
June 29, 2000 Sergio -- Thanks for the question regarding "d2kwut32.dll in Forms 6.0.5", version 6.0.5
You Asked
How to use win_api_session.one_session from forms 6.0.5? I get
ORA-06508 error :(
(I need detect if forms runtime is running before user can launch
another runtime)

Thanks you !
and we said...
If WIN_API_SESSION.One.Session is not working correctly, follow this
procedure to verify that you are using it correctly:

1) Obtain  d2kwutil.pll and d2kwutil.dll from:

ftp://oracle-ftp.oracle.com/

in the directory: /dev_tools/patchsets/dev2k/Win95NT/d2kwutil/

(get the v604 version in your case)

2) Replace the d2kwutil.pll.

3) Replace the d2kwutil.dll in c:\oracle_home\bin with the new one.

4) Run Form 2 (shown below).

5) Run Form 1 (shown below).

Notes
=====
-- If you have other sessions opened, use the code shown in the form from which
you want to quit the current session.

-- Pass the following constants as a parameter for the appropriate version for
which you are trying to detect if a session is being  used:

   Version 4.5 -> 'ui23MDIroot_W32'
   Version 5.0 -> 'ui25MDIroot_W32'
   Version 6.0 -> 'ui60MDIroot_W32'

-- For the third parameter to WIN_API_SESSION.One_Session, called (MATCHTYPE),
you have a choice of Window, Module, or Both. In order to work correctly with NT
OS, you must pass WINDOW.

Code
====

BASED ON A FORM CREATED IN FORMS 5.0.6.16.0

FORM 1
--IN WHEN NEW FORM INSTANCE TRIGGER--

DECLARE
REG BOOLEAN;

BEGIN
set_window_property(FORMS_MDI_WINDOW, TITLE, 'Session0');
reg := WIN_API_SESSION.One_Session('Session0', 'F50RUN32.EXE', 'WINDOW', FALSE,
'ui25MDIroot_W32', FALSE);
if reg then
  message('session exists');
  exit_form;
else
  message('session doesn''t exist');
end if;
END;

FORM 2
--IN WHEN NEW FORM INSTANCE TRIGGER--
set_window_property(FORMS_MDI_WINDOW, TITLE, 'Session0');
June 29, 2000 chen -- Thanks for the question regarding "Call the print utility of the browser", version Oracle 8.1.6 & OAS4.0.8
You Asked
Dear sir,

Now I want to implement a function in the pl/sql web page,which
is that when the user click a button(e.g Print) in the web page
the print utility of the browser will be called and a
documentation can be printed out. If the calling to the print
utility can be implemented in the web page, by what method?
Pl/Sql itself? Javascript? or html?

Thank you very much!
Best regards

John Chen
and we said...
see
http://developer.irt.org/script/49.htm
for a method of doing this.
June 29, 2000 Giorgio -- Thanks for the question regarding "Insert variable in select and create statment in plsql code", version PLSQL - webdb2.2
You Asked
ni varchar2(20);
BEGIN
....
   path_immagine:='c:\oracle\webdb\webdb\images\&ni';
   create or replace directory DIR_IMMAGINE as &path_immagine;
   -- where path_image like ni is variable
....
END;

Result:
path_immagine = 'c:\oracle\webdb\webdb\images\immagine.gif';
create or replace directory DIR_IMMAGINE as
'c:\oracle\webdb\webdb\images\immagine.gif';

how write this row?
and we said...
The & is a "sqlplus'ism" -- its like a macro variable.  SQLPlus
physically replaces the &variable name with the text before it
submits the statement to the database.  You cannot parameterize
reusable code in this fashion.

In Order to do DDL in PLSQL, we'll need to use dynamic sql.  In
Oracle8.0 and before, this could look like this:

ops$tkyte@DEV8I.WORLD> create or replace
  2  procedure execute_immediate( p_sql in varchar2 )
  3  is
  4      cursor_name     pls_integer default
                         dbms_sql.open_cursor;
  5      ignore          pls_integer;
  6  BEGIN
  7      dbms_sql.parse(cursor_name, p_sql, dbms_sql.native);
  8      ignore := dbms_sql.execute(cursor_name);
  9      dbms_sql.close_cursor(cursor_name);
 10  END;
 11  /

Procedure created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> create or replace
  2  procedure create_dir( p_dir_name in varchar2,
  3                        p_path_name in varchar2 )
  4  as
  5  begin
  6      execute_immediate( 'create or replace directory ' ||
  7                          p_dir_name ||
  8                         ' as ''' || p_path_name || '''' );
  9  end;
 10  /

Procedure created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> exec create_dir( 'my_dir', '/tmp' );
BEGIN create_dir( 'my_dir', '/tmp' ); END;

*
ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "SYS.DBMS_SYS_SQL", line 487
ORA-06512: at "SYS.DBMS_SQL", line 32
ORA-06512: at "OPS$TKYTE.EXECUTE_IMMEDIATE", line 6
ORA-06512: at "OPS$TKYTE.CREATE_DIR", line 5
ORA-06512: at line 1

if you get that error, but you believe you are allowed to
create a directory, it will be because you have the right to
create the directory via a role, you must have the priv granted
DIRECTLY to you (or use autonomous transactions in 8.1 and up).
See
http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
for more info

ops$tkyte@DEV8I.WORLD> grant create any directory to ops$tkyte;

Grant succeeded.

ops$tkyte@DEV8I.WORLD> exec create_dir( 'my_dir', '/tmp' );

PL/SQL procedure successfully completed.

In Oracle8i release 8.1 and up, this is written more simply as
(no execute_immediate procedure needed, its builtin)

ops$tkyte@DEV8I.WORLD> create or replace
  2  procedure create_dir( p_dir_name in varchar2,
  3                        p_path_name in varchar2 )
  4  as
  5  begin
  6      execute immediate 'create or replace directory ' ||
  7                          p_dir_name ||
  8                         ' as ''' || p_path_name || '''';
  9  end;
 10  /

Procedure created.

ops$tkyte@DEV8I.WORLD> exec create_dir( 'my_dir', '/tmp' );

PL/SQL procedure successfully completed.

ops$tkyte@DEV8I.WORLD>
June 29, 2000 Pete -- Thanks for the question regarding "NT Oracle service accessing a network drive.", version 8.1.5
You Asked
Tom,
I am setting up an Oracle 8.1.5 testing instance on an NT 4.0
server.  I have been successful at creating the database when
all of the files (control/rbs/data) are on the c: drive of the
server.  However, this scenario does not meet OFA
recommendations.  I wanted to move some of my data files to
network drives so that I could reduce the vulnerability of the
database to a crash of the c: drive.

I have an administrator account on the server and I am able to
create files on the network drive (F:).  The Oracle instance is
named tnt1.  I have changed the oracle NT service
"oracleservicetnt1" to log on as my administrator account on the
server.  I then stop the service and reboot NT.  The service is
set to start automatically.  I then perform the following in
server manager:

SVRMGR> alter tablespace indx offline;
Statement processed.
SVRMGR> alter tablespace indx
     2> rename datafile 'c:\app\oracle\oradata\tnt1\indx01.dbf'
     3> to 'f:\oradata\tnt1\indx01.dbf'
     4> ;
alter tablespace indx
*
ORA-01525: error in renaming data files
ORA-01141: error renaming data file 5 - new file
'f:\oradata\tnt1\indx01.dbf' not found
ORA-01110: data file 5: 'C:\APP\ORACLE\ORADATA\TNT1\INDX01.DBF'
ORA-27041: unable to open file
OSD-04002: unable to open file
O/S-Error: (OS 1326) Logon failure: unknown user name or bad
password.
SVRMGR>

I am fairly certain this is a network type problem because when
I move the datafile to another location on the c: drive it is
successful.

SVRMGR>
SVRMGR> alter tablespace indx
     2> rename datafile 'c:\app\oracle\oradata\tnt1\indx01.dbf'
     3> to 'c:\app\oracle\oradata\tnt1b\indx01.dbf';
Statement processed.
SVRMGR>
SVRMGR> alter tablespace indx online;
Statement processed.
SVRMGR> select * from v$database;
DBID       NAME      CREATED   RESETLOGS_ RESETLOGS PRIOR_RESE
PRIOR_RES LOG_MODE
KPOINT ARCHIVE_CH CONTROL CONTROLFI CONTROLFIL CONTROLFIL
CONTROLFI OPEN_RESETL VERS
OPEN_MODE
---------- --------- --------- ---------- --------- ----------
--------- -----------
------ ---------- ------- --------- ---------- ----------
--------- ----------- ----
----------
1513710746 TNT1      23-JUN-00          1 23-JUN-00          0
        ARCHIVELOG
237300     197270 CURRENT 23-JUN-00        604     237330
29-JUN-00 NOT ALLOWED 23-J
READ WRITE
1 row selected.
SVRMGR>

When I talk to the NT folks they told me that when the service
starts my account logs in again and is not mapping the network
drives.  One of the admins coded a bat file that ran as a login
type script for the profile of my account.  The bat file
contained the "net use" command to map the network drive.
However, when we started the service again the login of the
account when starting the service would not execute this portion
of the profile(login).  The drive was not mapped.

I there any way to do what I am trying to accomplish.  It seems
that NT being a "network" operating system, that Oracle on NT
should be able to read/write network disk drives.

One other questions is can you refer me to good reference
material for coding bat files and scripts in NT/dos and a
reference on NT/dos commands.

Thanks in advance!  Pete Snyder
and we said...
Don't use network drives for database files!  Its not safe.  NT
is an OS that can use a network but network disks don't give us
the "direct" writing that we need to be assured data we write
gets to the disk.  Buy another disk for your machine, don't use
a network.  You'll just be asking for trouble.  Also, you'll
make it so that your database will be unavailable much more
often -- you now need 2 machines to always be up, not just 1.

Do not do this.

We do support some network drive solutions (eg: the NetApp
server for example) but they are special cases and are certified
to work correctly.

There is a way to get it to see the drives -- you'll need to do
this for things like UTL_FILE and such.  I hesitate to tell you
how (you really should not do this - what does another disk
cost?  A couple hundred bucks -- get another disk, please).

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:241814624807,%7BUTL%5C_FILE%7D%20and%20%7BNETWORK%7D
for why it is currently not working...
June 29, 2000 Rajashekar -- Thanks for the question regarding "IMPORTING OF DATA", version 8.0.5
You Asked
Dear Tom,

1)I have data to be uploaded from
SQL-SERVER
ACCESS
ACII Text File
To oracle Data base 8.0.5 on solaries system using scripting.
Please help me out to do that.

2)i will have to do it periodically based on the data updation
in the sql server.

Can do both the points 1 & 2. Please help me out !!!!

Excpecting your earliest reply.

Regards
Raj
and we said...
SQLLDR is the tool you want to use.  Here is a small example of
a control file (with embedded data-- the data can be in another
file if you want) that loads up a table:

LOAD DATA
INFILE *
INTO TABLE DEPT
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(DEPTNO, DNAME, LOC)
BEGINDATA
12,RESEARCH,"SARATOGA"
10,"ACCOUNTING",CLEVELAND
11,"ART",SALEM
13,FINANCE,"BOSTON"
21,"SALES",PHILA.
22,"SALES",ROCHESTER
42,"INT'L","SAN FRAN"

See
http://technet.oracle.com/doc/server.804/a58244/part2.htm#435958
for more info.
June 29, 2000 Deepa -- Thanks for the question regarding "@ > whenever sqlerror EXIT", version v8.0
You Asked
Hi Tom,
    Can we use > whenever sqlerror EXIT within PL/SQL
block.If yes, How....

    Thankx....
     Deepa....
and we said...
No, but you do not need to.

If an error happens in a block, that error will be turned into
an exception.  If your plsql block catches and handles that
exception then it is no longer an error.  If on the other hand,
it lets the exception propagate OUT of the block, that will be
an error raised to sqlplus and sqlplus will "exit".

So, if you have:

ops$tkyte@DEV8I.WORLD> whenever sqlerror exit
ops$tkyte@DEV8I.WORLD> begin
  2  if ( to_number('a') > 5 ) then null; end if;
  3  end;
  4  /
begin
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number
conversion error
ORA-06512: at line 2

Disconnected from Oracle8i Enterprise Edition Release 8.1.5.0.0
- Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

The very act of getting the error bumps us out of the block and
then out of sqlplus.
June 30, 2000 Olawale -- Thanks for the question regarding "Deployment -- linking the database with HTML", version 8.0.5
You Asked
Actually I am just about to start or shall I say i just started
using Oracle.
1. How can I link a database with HTML using windowsNT
2. Which specific softwares can I use
3. How am I going to deploy it
4. Using Java but honestly I prefer CGI
and we said...
There are many many ways to do the above.  Here are a couple:

o Oracle WebDB
http://www.oracle.com/tools/webdb/index.html
  It provides:
  Integrated web publishing services for self-service content
  publishing and dynamic data publishing
  An intuitive portal framework for organizing, structuring, and

  customizing corporate information
  A centralized environment for portal deployment, management,
  monitoring, and maintenance

o JDeveloper
http://www.oracle.com/tools/jdeveloper/index.html

  To create java server pages, EJBs, XML integration, servlets
  and much more

o Oracle iAS
http://www.oracle.com/ip/deploy/ias/index.html

  Offers a fairly comprehensive solution in this space as well,
  of particular interest might be the PLSQL module(which
  is used to build this application you are using) or the
  servlets module.
June 30, 2000 Suresh -- Thanks for the question regarding "Where to find the NEXT value of datafile", version 8.1.5
You Asked
I said
Create tablespace temp datafile 'temp.dat' size 20m autoextend
on next 20M maxsize 200M;

I could find SIZE, AUTOEXTEND, MAXSIZE information on
dba_data_files
for 'temp.dat'

I couldn't find the NEXT value on dba_data_files. Could u pl.
tell me where to find that information.

Txs

Suresh.
and we said...
Its in the increment_by column:

ops$tkyte@DEV8I.WORLD> create tablespace testing
  2  datafile '/tmp/testing.dbf'
  3  size 1m reuse autoextend on
  4  next 2m
  5  maxsize 20m
  6  /

Tablespace created.

ops$tkyte@DEV8I.WORLD> begin
  2    print_table( 'select *
  3                    from dba_data_files
  4                   where file_name = ''/tmp/testing.dbf''' );
  5  end;
  6  /
FILE_NAME                     : /tmp/testing.dbf
FILE_ID                       : 35
TABLESPACE_NAME               : TESTING
BYTES                         : 1048576
BLOCKS                        : 128
STATUS                        : AVAILABLE
RELATIVE_FNO                  : 35
AUTOEXTENSIBLE                : YES
MAXBYTES                      : 20971520
MAXBLOCKS                     : 2560
INCREMENT_BY                  : 256
USER_BYTES                    : 1040384
USER_BLOCKS                   : 127
-----------------

PL/SQL procedure successfully completed.

Since my block size is 8k, I can see this is in blocks:

ops$tkyte@DEV8I.WORLD> select 256*8/1024 from dual;

256*8/1024
----------
         2

ops$tkyte@DEV8I.WORLD>
June 30, 2000 Chitra -- Thanks for the question regarding "Describing remote tables", version 8.1.6
You Asked
Hi,
   The most general way to describe a database table
programatically is to write a statement like
'select * from myTable' and the run dbms_describe
on this implicit cursor.
This does not work for remote tables which may
have columns of type LOB - this seems to be a database
restriction.
I am only interested in describing the table,
not in fetching data from it.
I can always go straight to the data dictionary -
like all_tables and all_tab_columns.
But is there a better way to describe remote tables
which may have LOBs in them?
and we said...
Short of actually running the dbms_describe@remote site (eg:
don't run YOUR dbms_describe, run the other databases
dbms_describe) -- there isn't a way to do this other then query
up ALL_TAB_COLUMNS.

The issue as you have discovered is that we refuse to prepare a
query (or create a view) on a SQL statement that references a
remote LOB.

If you want to do this AT the remote site using a
parse/describe, it would look like:

create synonym remote_dbms_sql for sys.dbms_sql@ora8idev;

declare
    l_theCursor     integer default remote_dbms_sql.open_cursor;
    l_query         varchar2(1000)
                    default 'select * from t';
    l_colCnt        number := 0;
    l_descTbl       remote_dbms_sql.desc_tab;
begin

    remote_dbms_sql.parse(  l_theCursor,  l_query,
dbms_sql.native );
    remote_dbms_sql.describe_columns( l_theCursor, l_colCnt,
                                      l_descTbl );

    for i in 1 .. l_colCnt loop
        dbms_output.put_line( '"' ||
                           l_descTbl(i).col_name || '"' );
    end loop;
    remote_dbms_sql.close_cursor(l_theCursor);
end;
/
June 30, 2000 Dilbagh -- Thanks for the question regarding "Replication -- does it generate redo/rollback?", version 8.0.6
You Asked
When performing refreshes(complete or fast). Does replication
creates rollback/redo data. In other words do I have to consider
adding more rollback segments as I add more tables for
replication. Please explain what happens in the process
techincally.
and we said...
Replication is covered under the same exact transactional
protections as everything else.  Work done by replication can be
rolled back in the case of an error.  Work done by replication
can be recovered from archive logs in the event of a media
failure.

Snapshots are governed by the same transactional issues as
"regular" work.

When a snapshot fast refreshes, the equivalent of the following
happens:

  delete from snapshot table
   where hidden_rowid/primary_key_column in
      (select rowid/primary key from snapshot_log_table@master
         where dml_type in ( 'D', 'U' ) );

  insert into snapshot table
   select * from master_table@master
   where rowid/primary key in ( select rowid/primary key
                                from snapshot_log_table@master
                                where dml_type in ('U','I') );

  and the we update the remote snapshot log OR remove the
snapshot log entries if no other snapshot needs them anymore..

That is done as one big transaction and if I have snapshot
groups -- they are done as one really big transaction.  For this
reason, the dbms_snapshot procedure that does the refreshing
allows you to specify a rollback segment name that will be used
during the refresh.  In this fashion, you can tell us to use a
rollback segment that you have sized accordingly (larger then
the rest if need be) to process the refresh in.
Review & Followup
Rating: 5
March 26, 2001
Reviewer: A Reader from USA

Rating: 4
Explanation of rollback vis-a-vis refresh May 29, 2001
Reviewer: Gus Spier from Middleburg, VA
Outstanding!  Excellent explanation of the actions that get recorded in the
rollback segment when refresh is in progress.

June 30, 2000 Phillip -- Thanks for the question regarding "Very large Database - question on max files/max filesize", version 8051
You Asked
Is there a limit to the number of datafiles Oracle can address?

Is there a limit to the size of a datafile (I could have
datafiles
in the region of 30-100 GB)

Are there any limitions to the size of RAW disk Oracle can
address?
and we said...
From the SERVER REFERENCE manual, database limits section:
http://technet.oracle.com/doc/server.804/a58242/ch5.htm#576
o max datafiles / tablespace 1,022.
  max datafiles / database 65533

o max datafile size: O/S dependent, limited by maximum
O/S file size; typically 2^22 or 4M blocks.  This means 32gig
per datafile realistically.

o raw disk is just like a "file" to us.  same restrictions
apply...
June 30, 2000 kofi -- Thanks for the question regarding "Slow query", version Oracle 8.0.5.0.0
You Asked
Hi,

Is there a way to cache a query?
This query joins 4 tables and uses a union.
It is used to select valid contracts so it is used constantly by
all users.  Please let me know if it can be done.

Kofi
and we said...
The database caches data naturally.  We do not cache "queries"
but rather database blocks.

Things to look into:

o can you use a UNION ALL instead of a UNION?  A union of sets X
and Y is the same as:

   X + ( Y-X )

whereas a union all of X and Y is:

   X + Y

A union involves a sort+filter, a union all simply concatenates
the results.

o can you use a materialized view to "preanswer" the question.
If the information in the base tables is relatively static --
this will be workable for you.  We'll have answered the question
off to the side for you and you'll be querying a "prejoined" --
"preunioned" result set.

o use explain plan and such on the query to see if you can find
an alternative (better) plan for the query.  You understand the
nature of the data better then we, you might be able to tune it
somewhat.

Sort of that, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:253415112676,%7BCACHE%7D
for how to cache individual tables however -- the database
normally does a pretty good job of caching frequently used
information so the results from this (caching the table) might
not be astronomical....
June 30, 2000 Dhanesh -- Thanks for the question regarding "Installing Oracle 8i and Developer 2000", version 8.1.5
You Asked
Hi,

I need help in installing Oracle 8i and Developer 2000 in WinNT
4.0 machine. Please note that this is for testing purpose only.
So need to install it in the same machine.

So I need to know -
(1) Procedure to do it
(2) How to configure Developer 2000 to point to Oracle Database
(3) Any additional tips and/or tricks you can recommend

Actually I attempted in installing, the result was that
Developer 2000 (Forms) is not able to connect to the database.

Cheers
Dhanesh Shah
and we said...
Oracle8i is release 8.1.

D2K is based on 8.0.

You can install either first/second -- they will be installed
into separate Oracle Homes. (separate directories).

You will need to use SQL*net to connect D2k to the database as
the products are 2 different versions.

You'll setup and configure the Oracle8i listener using the
configuration files in $ORACLE_HOME\network\admin (oracle home
for the oracle8i instance).  You can use the Oracle Home
Selector tool to set your default Oracle home to the database.
You'll be setting up the listener.ora.  Once you have the sqlnet
listener running, you'll be ready for the next step.

Use the Oracle Home selector now to set the default Oracle Home
to the D2k Oracle home.  You would now setup the tnsnames.ora
file in the oracle_home\net80\admin  (not network\admin,
net80\admin).  You'll have this point to the Oracle8i instance
on your machine.  You can use the tnsping tool to test this
connection.  Now you are ready to run d2k and connect to the 8i
instance.
June 30, 2000 Rissa -- Thanks for the question regarding "User Account -- prioritization", version Oracle 8.1.5
You Asked
Is there a way to tell database to prioritize several accounts
when they log in?
Thanks!
and we said...
Yes, starting in 8.1.5 there is.

See
http://technet.oracle.com/doc/server.815/a68020/ch2.htm#140558
to get started.
June 30, 2000 Michael -- Thanks for the question regarding "Export and ora-155", version Oracle 7.3.2.3.0
You Asked
When running exp from a unix environment and getting ORA-1555
is there any way to use the command(or its equivalant)
'set transaction use rollback segment RBSbig' or do I have to
think about increasing the size of all my rollback segments

Regards,
       Michael
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:275215756923,%7B1555%7D
for a discussion on this error and what causes it.

The solution you attempted, "create one big rollback" segment won't work in any
case since a 1555 is not caused by the transaction that GETS the error -- its
caused by all of the other transactions that have happened.  What you need to do
is make all of your rollback segments larger.  For example, I do a regular
export of a 6 gig image table full of blobs.  I've never hit an ora1555 in my
life.  I have large or many rollback segements though.  In my one instance I
have 6 250meg (1.5 gig total) rollback segments.  It takes a very very long time
for these to wrap around.  In my other instance I have 30 25meg rollback
segments (3/4's of a gig).  The difference between the 2 databases is the one
with few really big rollback segments has mostly fewer concurrent transactions
that do "big transactions".  The other instance has lots of concurrent
transactions that do "small or medium".  I keep lots of PERMANTLY big rollback
segments out there.  I do not attempt to skimp on rollback space (and I never
let them "shrink" to some optimal size -- I let them grow and then manually
shrink them when I want to - when i know i won't be needing that space).

So, its not that the EXPORT needs to be assigned to a big rollback -- its that
you need to let your rollback hang around for a longer period of time.  I would
recommend using recommendation #1 and #4 in the referenced URL:

  1.  Increase size of rollback segment which will reduce the likelihood of
overwriting rollback information that is needed.

  4.  Add additional rollback segments. This will allow the updates etc. to be
spread across more rollback segments thereby reducing the chances of overwriting
required rollback information.

have many large -- permanently allocated rollback segments.
June 30, 2000 Keith -- Thanks for the question regarding "How to get the number of bytes in a LONG RAW column", version 8.04
You Asked
Hi,

I am trying to get the real used amount of space in a table,
but 1 of the columns is using LONG RAW datatype. Is there
anyway to find out the bytes used within this column using
svrmgr or sqlplus? I am using vsize on the other columns.

Thanks
Keith Blair
and we said...
It is only possible if all of your long raws are less then 32k.
Then you can write a function like ( i have a table called image
with a long raw column image ):

scott@8i> create or replace function lrsize( p_rowid in rowid )
                            return number
  2  as
  3      l_size    number;
  4  begin
  5      for x in ( select * from image where rowid = p_rowid )
  6      loop
  7          l_size := utl_raw.length( x.image );
  8      end loop;
  9
 10      if ( l_size is null ) then
 11          raise program_error;
 12      end if;
 13      return l_size;
 14  end;
 15  /

Function created.

scott@8i>
scott@8i> select name, lrsize(rowid) from image;
select name, lrsize(rowid) from image
             *
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error
ORA-06512: at "SCOTT.LRSIZE", line 5
ORA-06512: at line 1

stuff in there exceeds 32k

scott@8i>
scott@8i> delete from image;

1 row deleted.

scott@8i> insert into image ( name, mime_type, img_size, image )
  2  values ( 'test', 'test', 10000, hextoraw( '0000000000' ) );

1 row created.

scott@8i>
scott@8i> select name, lrsize(rowid) from image;

NAME                           LRSIZE(ROWID)
------------------------------ -------------
test                                       5

scott@8i>
scott@8i> rollback;

Rollback complete.

anything less then 32k is OK

I will refer you to
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:231414051079,%7BDBMS%5C_SPACE%7D
however where you'll see how to write a procedure "show_space"
so you can quickly go:

scott@8i> exec show_space( 'IMAGE' );
Free Blocks.............................13
Total Blocks............................64
Total Bytes.............................524288
Unused Blocks...........................43
Unused Bytes............................352256
Last Used Ext FileId....................3
Last Used Ext BlockId...................713

Now I see exactly how many blocks are USED/UNUSED in the table.
June 30, 2000 Tamas -- Thanks for the question regarding "Virtual Database - virtual private database..", version 8.1.6 R2
You Asked
Dear Tom,

on iDevelop 2000 I heard a lot of virtual database in Oracle
8.1.6R2, but on the documentation CD I can not seem to find any
hint on how to do it. Could you route me to some technical paper
on this theme?

Thank you in advance.

Regards,

Tamas
and we said...
do you mean Virtual "private" Database?  See
http://osi.oracle.com/~tkyte/article2/index.html
for info.
June 30, 2000 prashant -- Thanks for the question regarding "LOAD JAVA Erorrs", version 8.1.3
You Asked
Hi,
   We have default ORACLE8I(8.1.6) server installation.
   Following is the JAVA Program.
   import java.sql.*;
   import java.io.*;
   public class DropAny{
        public static void object(String object_type,String
object_name)
        throws SQLException
                    {
                      //connect to oracle using JDBC
                      Connection conn =
DriverManager.getConnection("jdbc:defaul
t:connection:");
                      String sql = "DROP  " + object_type +"
"+object_name;
                      try{
                           Statement stmt =
conn.createStatement();
                           stmt.executeUpdate(sql);
                           stmt.close();
                        }catch (SQLException e)
                        {System.err.println(e.getMessage()); }
                     }
                }
   I am trying to compile and store this DropAny.java program
into
   ORACLE 8i database by following command.
loadjava -u gullakoa/gullakoa@aenc15 -v -r DropAny.java

    It gives me following error.
internal error: unanticipated exception:
java.lang.NoClassDefFoundError: oracle/
aurora/sqljdecl/SqljDecl
java.lang.NoClassDefFoundError: oracle/aurora/sqljdecl/SqljDecl
        at
oracle.aurora.server.tools.loadjava.SourceFileReader.getScanner(S
ourc
eFileReader.java:52)
        at
oracle.aurora.server.tools.loadjava.SourceFileReader.getFirstName
(Sou
rceFileReader.java:61)
        at
oracle.aurora.server.tools.loadjava.LoadJava.noteSource(Compiled
Code
)
        at
oracle.aurora.server.tools.loadjava.LoadJava.processLoadAndCreate
(Com
piled Code)
        at
oracle.aurora.server.tools.loadjava.LoadJava.process(LoadJava.jav
a:11
35)
        at
oracle.aurora.server.tools.loadjava.LoadJavaMain.run(LoadJavaMain
.jav
a:266)
        at
oracle.aurora.server.tools.loadjava.LoadJavaMain.main(LoadJavaMai
n.ja
va:57)
resolver :
loadjava: 1 errors

    What is wrong here? Any help is appreciated.
Thanks,
Prashant Shah
and we said...
It is either (same for NT, just reverse the slashes):

 The loadjava command is really just a unix script
(found in $ORACLE_HOME/bin). This script still relies
on using the classes111.zip to run this script and expects
to find classes111.zip in $ORACLE_HOME/jdbc/lib directory..

 If classes111.zip isn't found in directory
$ORACLE_HOME/jdbc/lib when the loadjava script in invoked,
then the NoClassDefFoundError exception is raised.

OR (same for unix, reverse the slashes and set an environment
variable)

The error message described above occurs because the Windows NT

'loadjava.bat' script is unable to access the 'translator.zip'
file while attempting to load the '.java' file to RDBMS.

The 'translator.zip' file can be located in the following client

PC's folder as :

   c:\ORACLE_HOME\sqlj\lib\translator.zip

Solution Description
--------------------

To correct this problem, perform the following steps:

1) Go to the ENVIRONMENT PANEL as follows :

      START->SETTINGS->CONTROL PANEL->SYSTEM->ENVIRONMENT PANEL

2) Create or update a CLASSPATH variable with the following
value:

      C:\ORACLE_HOME\sqlj\lib\translator.zip

      Note : Replace 'C:\ORACLE_HOME' with your PC's
             'DRIVE LETTER:\ORACLE HOME' folder location.

3) Close and open your Command Prompt window to implement the
new
   CLASSPATH setting.

The 'LOADJAVA' process should work now.
June 30, 2000 Curtis -- Thanks for the question regarding "Differences between Oracle 7.3 and Oracle 8 (NOT the enterprise edition)", version Oracle8 Release 8.0.4.0.0
You Asked
I've worked on Oracle 7.3 before and now I'm working on a
project that has an Oracle 8 database.
However it is not the enterprise edition , doesnt have the
objects option.
So in this case, are there any significant differences between
the Oracle 8 and Oracle 7.3 versions?
I'm worried that I might be under-utilizing the features of the
RDBMS.
and we said...
You'll want to see
http://technet.oracle.com/doc/server.804/a58228/toc.htm
that has the new feature/options of 8.0 spelled out and a
chapter that tells you what features you get with 8.0 and what
options you can license with it (as opposed to what you get and
what you can license with 8.0 EE).

For example (a small list, not exhaustive) you get:

o rman features
o connection pooling/multiplexing
o password management
o LOBS

....
June 30, 2000 Avinash -- Thanks for the question regarding "RE: Ask Tom Submission Logic Tables", version
You Asked
What are logic tables as specified in one of the exam
objectives of Oracle8i PL/SQL OCP paper?

Thanks.
and we said...
Logic Tables just tell us the outcome of a BOOLEAN and/or.  For example:

     AND| TRUE       FALSE         UNKNOWN
     ---|-----------|-------------|-------------
    TRUE| TRUE      | FALSE       | UNKNOWN
   FALSE| FALSE     | FALSE       | FALSE
 UNKNOWN| UNKNOWN   | FALSE       | UNKNOWN

shows that (TRUE and TRUE) is TRUE while (TRUE and FALSE) is FALSE.  The other
logic table is for OR

     OR | TRUE       FALSE         UNKNOWN
     ---|-----------|-------------|-------------
    TRUE| TRUE      | TRUE        | TRUE
   FALSE| TRUE      | FALSE       | UNKNOWN
 UNKNOWN| TRUE      | UNKNOWN     | UNKNOWN

Then there are the set of tables for NOT logic as well...

The above is easily verified via:

ops$tkyte@8i> declare
  2      unknown boolean default NULL;
  3
  4      procedure p_and( msg in varchar2, x in boolean, y in boolean )
  5      is
  6      begin
  7          dbms_output.put( rpad( msg, 30, ' ') );
  8          if ( x and y ) then
  9              dbms_output.put_line( ' is TRUE' );
 10          elsif ( NOT(x and y) ) then
 11              dbms_output.put_line( ' is FALSE' );
 12          else
 13              dbms_output.put_line( ' is UNKNOWN' );
 14          end if;
 15      end;
 16
 17      procedure p_or( msg in varchar2, x in boolean, y in boolean )
 18      is
 19      begin
 20          dbms_output.put( rpad(msg, 30, ' ') );
 21          if ( x or y ) then
 22              dbms_output.put_line( ' is TRUE' );
 23          elsif ( NOT(x or y) ) then
 24              dbms_output.put_line( ' is FALSE' );
 25          else
 26              dbms_output.put_line( ' is UNKNOWN' );
 27          end if;
 28      end;
 29  begin
 30      p_and( 'True and True', true, true );
 31      p_and( 'True and False', true, False );
 32      p_and( 'True and Unknown', true, Unknown );
 33      p_and( 'False and True', false, true );
 34      p_and( 'False and False', false, false );
 35      p_and( 'False and Unknown', false, Unknown );
 36      p_and( 'Unknown and True', Unknown, True );
 37      p_and( 'Unknown and False', Unknown, False );
 38      p_and( 'Unknown and Unknown', Unknown, Unknown );
 39      dbms_output.put_line('----------------------------' );
 40      p_or( 'True or True', true, true );
 41      p_or( 'True or False', true, False );
 42      p_or( 'True or Unknown', true, Unknown );
 43      p_or( 'False or True', false, true );
 44      p_or( 'False or False', false, false );
 45      p_or( 'False or Unknown', false, Unknown );
 46      p_or( 'Unknown or True', Unknown, True );
 47      p_or( 'Unknown or False', Unknown, False );
 48      p_or( 'Unknown or Unknown', Unknown, Unknown );
 49  end;
 50  /
True and True                  is TRUE
True and False                 is FALSE
True and Unknown               is UNKNOWN
False and True                 is FALSE
False and False                is FALSE
False and Unknown              is FALSE
Unknown and True               is UNKNOWN
Unknown and False              is FALSE
Unknown and Unknown            is UNKNOWN
----------------------------
True or True                   is TRUE
True or False                  is TRUE
True or Unknown                is TRUE
False or True                  is TRUE
False or False                 is FALSE
False or Unknown               is UNKNOWN
Unknown or True                is TRUE
Unknown or False               is UNKNOWN
Unknown or Unknown             is UNKNOWN

PL/SQL procedure successfully completed.

follow up to comment below

I have NEVER heard of "programming logic" (nested if then elsif, etc) being
referred to as LOGIC TABLES.

Logic tables, as depicted above, are in fact the correct answer.

Strongly suggest you just goto
http://www.google.com/
and search for logic tables.  You'll see
lots of them and NONE of them are "if then elsif" (which are programming
constructs, not "logic tables")
Review & Followup
Rating: 1
Logic Tables - Misleading Answer April 12, 2001
Reviewer: Mick Rice from Galway, Ireland
Dr Tom,
       Just a comment on this suggested answer on 'logic tables'. I'd suggest
strongly what this person was gettig at/asking about is nested if-then-else (or
elsif) statements which are generally referred to as 'logic tables'. Perhaps
it's not too late to let them know before they fail the exam ;-)


Subject | Article | Last Updated (East coast time)
Variable portion of SGA | article only | Jul 05, 2000 10:31 am
upload the image on webdb | article only | Jul 05, 2000 12:33 pm
Multi-row Update/ Grid using plsql/html | article only | Jul 05, 2000 12:57 pm
Ole Error | article only | Jul 05, 2000 01:29 pm
LOB Location | article only | Jul 05, 2000 01:47 pm
Dropping Own Tables | article only | Jul 05, 2000 06:40 pm
use of cursor variables in Forms 4.5 | article only | Jul 06, 2000 07:54 am
Encription of Stored Procedure in Package Body | article only | Jul 06, 2000 03:16 pm
Problem in Import command | article only | Jul 06, 2000 03:28 pm
ORA-1025: UPI Parameter out of range | article only | Jul 06, 2000 03:50 pm
EXPORT/IMPORT -- from NT to Solaris -- can you? | article only | Jul 06, 2000 08:51 pm
Command to execute unix scripts inside PL/SQL | article only | Jul 06, 2000 08:56 pm
Pro-C retrieval of sql that errored out | article only | Jul 06, 2000 09:05 pm
42 stored procedures using same DATABASE LINK resulting in error | article only | Jul 07, 2000 03:19 pm
How do I join tables in a query that uses the 'connect by' clause? | article only | Jul 07, 2000 03:41 pm
select for update on table with the constraint -- ora 22292 | article only | Jul 07, 2000 03:56 pm
Multiple rows from SP without using OracleTypes | article only | Jul 07, 2000 04:10 pm
row(s) 1 - 17 of 17
July 05, 2000 Anwar -- Thanks for the question regarding "Variable portion of SGA", version 7.3.2
You Asked
Hi Tom!

Can you please explain what is variable & fixed portions of SGA
& the difference between the two?
and we said...
Sure, if we look at the output of a SHOW SGA:

SVRMGR> show sga
Total System Global Area                         93248912
bytes
Fixed Size                                          64912 bytes
Variable Size                                    66887680
bytes
Database Buffers                                 26214400 bytes
Redo Buffers                                        81920 bytes

The Fixed size component is out of your control.  It varies from
release to release and platform to platform.  It contains a
collection of objects that point to other areas inside the rest
of the SGA -- think of it as the "roadmap" to the rest of the
SGA.  It also contains specific variables such as the init.ora
parameter db_block_size and so on (constants basically for the
currently mounted database).

The variable sized component of the SGA, as its name implies,
contains data structures that are variably sizes (eg: things
like "sessions", "processes", "db_files" will affect this
marginally -- things like "shared_pool_size" will large effects
on this).  The variable size of the SGA is the sum of the sizes
of all of these "variably" sized structures (but not block
buffers, they are reported separately).
July 05, 2000 Giorgio -- Thanks for the question regarding "upload the image on webdb", version 2.1
You Asked
Hi Tom!!

I know that when i submit a HTML form with a input type=file my
web server upload the file that there is on client on the
server!!
Where Webdb upload my file when click on submit botton in the my
html form with a input type=file?

thanks!
and we said...
It takes more thn "input type=file", you need to make sure you
put enctype=mulipart/form-data in the form tag as well (else,
webdb will get the NAME of a file -- not the file itself!)

Webdb always puts the uploaded file into a database table. This
table is called wwv_document$ (or wwv_document) and looks like:

web$sb@8i> desc wwv_document$
 Name                          Null?    Type
 ----------------------------- -------- --------------------
 NAME                          NOT NULL VARCHAR2(350)
 MIME_TYPE                              VARCHAR2(48)
 DOC_SIZE                               NUMBER
 CREATOR                       NOT NULL VARCHAR2(30)
 CONTENT                                LONG RAW

Here is a support note with some more info:

Article-ID:         <Note:74343.1>
Platforms:          GENERIC;

You want to upload files into the database using WebDB.  This
feature is most commonly used to upload images and display them
in WebDB.  It is included as a "DEMO" and may be a foundation
for manipulation of a new, more advanced package.

The WEBDB.wwv_testdoc package includes the following procedures:
  *show_form - GUI used to upload the files into the WebDB
               documents table

  *process_upload - the actual procedure that will do the
                    uploading

  *show_all - an html table that displays a list of files loaded

              in the table and links to view each of them

  *process_download - the actual procedure that will do the
                      downloading

================
STEPS TO UPLOAD
================

1.)Go to
http://hostname.domain:port/WebDB/WEBDB.wwv_testdoc.show_form
  WHERE:

  *Hostname.domain = fully qualified hostname of the machine
WebDB is installed
  *Port = the port you have started the WebDB listener

2.)What should the name be: Keep the name "simple". Do not
include blanks or special characters.  Choose the name carefully
since it will be used in the URL to call the file.

3.)Use the "BROWSE" button to find the file on your local file
system.  The full path to the file must be included.

4.)Click the "INSERT" button on the form

  *Success Message: Document has been added to the system as
WEBDB/doc_name

  WHERE:

  doc_name is the name you gave the document on upload

  *If a document in the table already has the name you chose,
you must click the "UPDATE" button to overwrite the existing
file.

5.)To view the file, click the link provided in the success
message or type:
http://hostname.domain:port/WebDB/docs/WEBDB/doc_name
6.)To view all the documents that have been uploaded to the
documents table type:
http://hostname.domain:port/WebDB/WEBDB.wwv_testdoc.show_all
Review
      & Followup

      Rating: 3
We wanted more
      information and examples  July 11, 2001
Reviewer:
      A reader

      Rating: 1
Process upload
      in wwv_testdoc  July 31, 2001
Reviewer:  Roland
      Daane  from Netherlands ans the USA
In the procedure process_upload the document is inserted in the parameter p_doc
of type varchar2.

where is it actually inserted into the long raw column.

Do you maybe have an example of a table and a procedure through which the
document is inserted as a long raw?

thanks.. Roland Daane (r.daane@chello.nl or rdaane@upc.nl)

procedure process_upload
(   /* get document type, document (in varchar) and document name*/
    p_type in varchar2,
    p_doc in varchar2, p_name in varchar2
)
is
    l_mode varchar2(25) default 'added to ';
    l_name varchar2(255) default remove_invalid_chars(p_name);
    l_count number;
begin
    if ( owa_util.get_cgi_env('HTTP_CONTENT_TYPE') not like
                'multipart/form-data;%' )
    then
        raise_application_error(-20666,
                                'Sorry, Only Netscape 2.x/3.x can currently
upload documents');
        return;
    end if;

    select count(*)
    into   l_count
    from   wwv_document
    where  name = p_doc;

    if ( l_count = 0 ) then
        raise_application_error(-20666, 'You uploaded a MISSING document...');
    end if;

    hdr;

    if (l_name is NULL)  then
        l_name := USER || substr(p_doc, instr(p_doc, '/'));
    else
        l_name := USER || '/' || l_name;
    end if;

    if ( p_type = 'Update' ) then
        delete from wwv_document where name = l_name;
        l_mode := 'updated in';
        if ( sql%rowcount > 1 ) then
            htp.bold('You have just deleted an old document');
            htp.br;
        end if;
    end if;

    update wwv_document set name = l_name where name = p_doc;
    commit;
    htp.p('Document has been ' || l_mode || ' the system as ');
    htp.anchor('docs/' || l_name, htf.bold(l_name));
    htp.hr;
    show_the_form;
    footer;
end process_upload;

July 05, 2000 Sanjay -- Thanks for the question regarding
      "Multi-row Update/ Grid using plsql/html", version 4.0.8.1

      You Asked
Tom,
I would like to build an updatable, multi-row
page. e.g

==============================================
First Name    Last Name        Email
=============================================
Fred           Jones
Davy           Crockett
homer          Simpson

etc..
Each field in every row is updatable(using the HTML
text field or textarea or any other element), with
the rowid as a hidden value. For small# of rows 3
and small# of columns, this is a no-brainer.
But, go beyond 3, and you are dealing with n*n fields
and hence n*n variables(plus more, if you want to maintain
state).
Also, if the user has a requirement that they want to
change the number of rows that they want to see everytime,
then I am in trouble.
Can owa_util.vc_arr solve my problem in any way ?
thanks

      and we said...
Yes, owa_util.vc_arr can (but I would just use my own type).

Here is a very small example using scott/tiger and the DEPT
table.

You will call show_data from the URL like this:

http://yourhost/DCDname/owa/demo_pkg.show_data?p_rows=3
And that would let you see 3 rows at a time.  The do_something
routine gets ARRAYS of data, one element for each line on the
previous page.  It processes these one by one (note the use of
the OLD values to prevent lost updates and the use of
htf.escape_sc to avoid issues with strings that have &, ", <, >
and so on in them)...

create or replace package demo_pkg
as
    type myArray is table of varchar2(4000)
         index by binary_integer;

    procedure show_data( p_rows in number default 2 );

    procedure do_something( p_old_deptno in myArray,
                            p_new_deptno in myArray,
                            p_old_dname  in myArray,
                            p_new_dname  in myArray,
                            p_rows       in number default 2);
end;
/

create or replace package body demo_pkg
as

procedure show_data( p_rows in number default 2 )
is
begin
    htp.formOpen( 'demo_pkg.do_something' );
    htp.formHidden( 'p_rows', p_rows );
    htp.tableOpen;
    for x in ( select htf.escape_sc(deptno) deptno,
                      htf.escape_sc(dname) dname
                 from dept
                where rownum <= p_rows )
    loop
        htp.p( '<tr><td>' );
        htp.formHidden( 'p_old_deptno', x.deptno);
        htp.formText( 'p_new_deptno', cvalue => x.deptno );
        htp.p( '</td><td>' );
        htp.formHidden( 'p_old_dname', x.dname);
        htp.formText( 'p_new_dname', cvalue => x.dname );
        htp.p( '</td></tr>' );
    end loop;
    htp.tableClose;
    htp.formSubmit;
    htp.formClose;
end;

procedure do_something( p_old_deptno in myArray,
                        p_new_deptno in myArray,
                        p_old_dname  in myArray,
                        p_new_dname  in myArray,
                        p_rows       in number default 2 )
is
begin
    for i in 1 .. p_old_deptno.count
    loop
        update dept
           set deptno = p_new_deptno(i),
               dname  = p_new_dname(i)
         where deptno = p_old_deptno(i)
           and dname  = p_old_dname(i);

        htp.bold( 'update to dept ' || p_old_deptno(i));
        if ( sql%rowcount = 0 )
        then
            htp.bold( ' failed, someone else changed it' );
        else
            htp.bold( ' succeeded...' );
        end if;
        htp.br;
    end loop;
    show_data(p_rows);
end;

end;
/

July 05, 2000 Gauri -- Thanks for the question regarding "Ole
      Error", version 5.0

      You Asked
Can you tell me the error message corresponding to the ole error
code 0x8002000e? Where can I refer to Ole errors?

      and we said...
this is extracted from a support note:

Common HRESULT error codes

Objective

This section describes the most common error codes that a COM
object will return, but it does not provide an extensive list of
all the error codes available. For a complete listing of all the
errors, see the standard specification. (Microsoft owns that
one)

HRESULT layout

The return value of the COM Cartridge API functions is a HRESULT
value. This is not a handle to anything, but is merely a 32-bit
value with several fields encoded in the value.  The parts of an
HRESULT are shown below.

HRESULTs are 32 bit values layed out as follows:

 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
+-+-+-+-+-+---------------------+-------------------------------+

|S|R|C|N|r|    Facility         |               Code
|
+-+-+-+-+-+---------------------+-------------------------------+

  where

      S - Severity - indicates success/fail

          0 - Success
          1 - Fail (COERROR)

      R - reserved portion of the facility code, corresponds to
NT's second severity bit.

      C - reserved portion of the facility code, corresponds to
NT's C field.

      N - reserved portion of the facility code. Used to
indicate a mapped NT status value.

      r - reserved portion of the facility code. Reserved for
internal use. Used to indicate HRESULT values that are not
status  values, but are instead message ids for display strings.

      Facility - is the facility code

      Code - is the facility's status code

HRESULT error codes

(0x80020008)

     Bad variable type

Cause: The datatype of a PL/SQL value passed as a method
parameter did not match the Microsoft Visual Basic data type of
the method parameter, or a NULL value was passed as a method
parameter.

Action: Ensure that any local variables used as method
parameters are of the appropriate datatype and are set to a
value other than NULL.

(0x80020006)

     Unknown name

Cause: The specified property or method name was not found for
the specified object.

Action: Check that calls to Invoke, SetProperty or GetProperty
has valid method and property names.

(0x800401f3)

     Invalid class string

Cause: The specified ProgID is not registered as an OLE object
in the registry of the local computer.

Action: Check that the object you are trying to create is
installed on your computer. Check the ProgID parameter to the
CreateObject API call.

(0x80080005)

     Server execution failed

Cause: The specified OLE object is registered as a local OLE
server (.EXE file), but the .EXE file could not be found or
started.

Action: Reinstall the OLE object on your computer or correct the
registry entry of the OLE object.

(0x8007007e)

     The specified module could not be found

Cause: The specified OLE object is registered as an in-process
OLE server (.DLL file), but the .DLL file could not be found or
loaded.

Action: Reinstall the OLE object on your computer or correct the
registry entry of the OLE object.

(0x80020005)

     Type mismatch

Cause: The datatype of a PL/SQL local variable used to store a
returned property value or a method return value did not match
the Visual Basic data type of the property or method return
value.

Action: Ensure that the local variable is of the appropriate
datatype. Or, the return value of a property or a method was
requested, but it does not return a value.

(0x80020004)

     Parameter not found

Cause: A named parameter was specified before a positional
parameter.

Action: Ensure that all named parameters are specified after all
positional parameters.

(0x8002000E)

     Invalid number of parameters

Cause: Wrong number of parameters were passed to method.

Action: Check the numbers of parameters passed to the method.
Check calls to InitArg, SetArg and SetPtrArg. Make sure the
number of parameters are the same as in the documentation.

(0x80004001)

     Not implemented

Cause: You called a method that wasn't supported

Action: Don't use this method.

(0x8007000E)

     Out of memory

Cause: There was not enough free memory available.

Action: Close some applications and try again. Check documented
minimum amount of memory required. Increase virtual memory size.

(0x80070057)

     One or more arguments are invalid

Cause: One or more of the arguments to a method was semantically
invalid.

Action: Check all arguments added before calling Invoke.

(0x80004005)

     Unspecified error

Cause: Unknown

Action: Contact your software vendor.

(0x8000FFFF)

     Catastrophic failure

Cause: Unknown.

Action: Contact the OLE object software vendor.

July 05, 2000 Lindsay -- Thanks for the question regarding "LOB
      Location", version 8i

      You Asked
Is it important to have LOBs located in a different tablespace
than the rest of the data?

What are the performance and/or space issues?

Thanks

      and we said...
It is not "important".  It is an option, a choice to be made,
but it is not important to separate them.

A LOB consists of three pieces (talking about non-trivial lobs,
lobs > 4k, which are stored out of line).  There is

o the lob locator.  always stored in the row (in the table).
Its a pointer.

o the lob index.  organizes all of the chunks of a lob.  Its in
its own segment separate from the table.  that means a full scan
of the table will not read this data (only when you dereference
the lob will it read this data).

o the lob data itself.  these are all of the chunks pointed to
by the lob index.  These are stored in their own segment.

The lob index and lob segment may reside in their own tablespace
separate from the data.  You might do this to track storage,
review IO hits (we can record IO by file or tablespace -- if you
want to know how many reads/writes to a lob segment are
happening you would have to put it into its own tablespace).
You might do this to spread IO out.  You might do this because
you like to use uniformally sized extents in tablespaces but
would like to use different sized extents for your lob segment
vs your table segment.  You might do this to spread IO out
across more devices.

So, there are reasons you might want to but its not "do or die"
July 05, 2000 Rajesh -- Thanks for the question regarding
      "Dropping Own Tables", version Oracle 8.1.5

      You Asked
Hi Tom,

I have following questions.

Operating System : Windows NT4.0
Database : Oracle 8.1.5.

1] Is there a way where i can give oracle users read only access
to all the objects in his schema or to create a read only user.
The oracle user should be given the permissions to execute
"select" queries only.The oracle user should not be able to drop
his objects (tables/views/synonyms) and he should be able to
view all the objects when he executes "select * from tab".

2] Is there a way to time out incorrect joins and long queries.

3] Is there a way to get statistics on what the oracle user is
querying.

Thanks in advance.

Rajesh

      and we said...
In Oracle8i, release 8.1 and up -- the answer to #1 is yes.  You
could create a trigger such as:

tkyte@ORACLE8I> create or replace trigger ddl_trigger
  2  before create or alter or drop on DATABASE
  3  begin
  4      if ( user in ( 'SCOTT', 'HOTEL', 'PEOPLE' ) )
  5      then
  6          raise_application_error( -20001,
                        'You are not allowed to DROP' );
  7      end if;
  8  end;
  9  /

Trigger created.

tkyte@ORACLE8I>

Now, when scott logs in and tries to do stuff:

scott@ORACLE8I> drop table emp;
drop table emp
*
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-20001: You are not allowed to DROP
ORA-06512: at line 4

scott@ORACLE8I> create table t ( x int );
create table t ( x int )
*
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-20001: You are not allowed to DROP
ORA-06512: at line 4

scott@ORACLE8I> alter table emp add ( x int );
alter table emp add ( x int )
*
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-20001: You are not allowed to DROP
ORA-06512: at line 4

He will not be able to.  Please see the SQL reference manual and
the  application developers guide for more information on this
new type of trigger..

As for #2, the answer is also yes -- using resource profiles.
See

http://technet.oracle.com/doc/server.815/a67772/users.htm#1148
for more info on that feature.

As for #3, I'm not sure what you are asking for -- you can see
what SQL a user is executing by joining v$session with
v$sqlarea.  You can use auditing to determine what objects they
are querying.  You can use sql_trace+tkprof to see exactly what
a session is doing.

July 06, 2000 Kevin -- Thanks for the question regarding "use
      of cursor variables in Forms 4.5", version 1.0

      You Asked
I knew I could use cursor variables for store procedures on the
server (Oracle 8/8i). Now, I am
considering using cursor variables on the client. So first
question is - can
I do it using Forms 4.5?

In a program unit, say function My_Function_A returns the cursor
variable
and My_Procedure_ B fetches the data and inserts data to another
table. (Of
course, you can use one procedure instead.) The reason for doing
it is that
there are six input combinations on the user input block. Can
someone review
the code and give me some hint on syntax so that it can work on
the client
application as well. I hope to call this procedure in
when-new-block-instance trigger. If I am using Forms 4.5 and I
can't cursor
varialbes, is there work-arround? -- better than creating six
cursors for six
input combinations. Also, I like to get some hints to start
with.
e.g. if the detail block should be a base table.

Any help will be greatly appreciated!

With PL/SQL (2.3 and higher) I would write something like this
(all in one.)

CREATE OR REPLACE PROCEDURE Show_Charges
  (p_Input IN number) AS

  TYPE t_Records IS REF CURSOR;

  v_CursorVar t_Records;

  /* Variables to hold the output. Just show one in here. /
  v_Amount      tbraccd.tbraccd_amount%TYPE;

BEGIN
  -- Based on the input parameters, open the cursor variable.

IF p_Input = 1 THEN
    OPEN v_CursorVar FOR
      SELECT statement

ELSIF p_Input = 2 THEN
    OPEN v_CursorVar FOR
      SELECT statement
.. .. ..

ELSE
    /* Wrong value passed as input - raise an error */
  RAISE_APPLICATION_ERROR(-20000, 'Input must be 1 - 6');
END IF;

/* Fetch loop. */
  LOOP
      FETCH v_CursorVar INTO
        v_Amount;
      EXIT WHEN v_CursorVar%NOTFOUND;

      INSERT INTO table_1 (amount_paid)
        VALUES (v_Amount);

      END IF;
  END LOOP;

  CLOSE v_CursorVar;

  COMMIT;
END Show_Charges;

Thanks and regards,

Kevin

      and we said...
You cannot use cursor variables in forms 4.5.  You can call
stored procedures that use them (stored in the server) but not
on the client.  That was added in forms 5.0.

There is no way I'd want to do this processing on the client
anyway -- even in 5.0 and up -- i would want a stored procedure
to fetch and insert.  I would not want to bring each row back to
the client and iterate row by row over it just to send them
back.

What I would do is use either dbms_sql (in 8.0 or before or if I
did not know the number of bind variables) or execute immediate
and do a simple "INSERT INTO .... SELECT ... FROM WHERE ....".
If I had no need for bind variables -- I would just use
forms_ddl.  For example:

...
begin
  if p_input = 1 then
     theQuery := 'insert into T select * from T2 where ...';
  elsif p_input = 2 then
     theQuery := 'insert into T select * from T3 where ...';
  ....

  end if;

  forms_ddl( theQuery );
  commit;
end;

That is much more efficient then single row fetching/inserting.

If you really believe you must fetch the rows back to the form
for whatever reason, use record groups.  See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:270615625768
for an example.

July 06, 2000 Azan -- Thanks for the question regarding
      "Encription of Stored Procedure in Package Body", version 8i

      You Asked
Is there any way to encript procedure or function in package
body so that we cannot read it from Schema Manager?

How to check what and number of stored procedures running as
background process?

What is the different between synonym and view?
When/what condition synonym or view is best to apply?

      and we said...
There is a program called "wrap" that will create an unreadable
(by people) version of a procedure that can be loaded into the
database.  See

http://technet.oracle.com/doc/oracle8i_816/appdev.816/a77069/c_wrap.htm#1859

For #2, you would join v$session to v$sqlarea by
address/sql_adress.  that'll show you what session is running
what sql.

For #3, a synonym is a symbolic link.  A view is a stored query
-- it can have a predicate, involve more then one table and so
on.  You never need to use a synonym, they are mostly for
convienence.  You would use a view to store a complex query so
that the end user does not have to enter it or to enforce some
security (to restrict the visible rows for example...)

July 06, 2000 Mohamed -- Thanks for the question regarding
      "Problem in Import command", version Oracle8 Enterprise Edition Release
      8.0.4.0.0 - Production

      You Asked
Hi Tom,

1.Can the input file to an import command have an extension
other than .dmp ?

2.When I used the Oracel 7.3 export file import_can_for_gavs.sql
with imp80 command,i received the following error.

IMP-00037: character set marker unknown

What is the problem? Is there a reason other than the file being
a corrupt one? Pl. clarify me soon.

regards,
rafi.

      and we said...
1) yes it can.

2) the most common causes of this are:

- it is not a file created by EXP.

- you ftp'ed this file and did it in "text" mode.  that changes
the file (changes ascii 10's into 13+10 or removes 13's).

- the file was created with a LATER release of exp -- eg: it is
a v8.0 exp file.  You must use the same or earlier release of
exp (you can use the v7 export tool against v8 if this is the
case).

July 06, 2000 Alessandro -- Thanks for the question regarding
      "ORA-1025: UPI Parameter out of range", version version 8.0.5

      You Asked
Within a Pro-C code we try to fetch a cursor (which have a row
size about of 2300 bytes) into an array. The problem is that if
we try to set the array size to 40000 Oracle returns Error 1025
after the first fetch. If the array size is set to 30000 no
error occurs. Is there a limit to the dimension of the array? If
yes which is that, otherwise, why the 1025 error occurs?

      and we said...
Yes, the reasonable limit is 32767.  Values over this will fail.

I would like to point out that there is definitely "too much of
a good thing" at work here.  I have never found array sizes over
about 100 elements to be more effecient then array sizes at or
less then 100.  In fact, I've often found the exact opposite to
be the case -- that an array size set too large runs *slower*
after a while.  You might seriously consider making that
somewhat smaller -- if you do the math your array is about 66meg
at 30,000 entries.  Thats about 65.8meg bigger then it should be.
July 06, 2000 Reji
      -- Thanks for the question regarding "EXPORT/IMPORT -- from NT to Solaris
      -- can you?", version 8.1.6

      You Asked
Tom:
    Two qns related to exp/imp.

    Can I export a schema ( user and all the objects including
    data ) from an NT based DB and import that into a Solaris
    Based DB - same version of oracle.   When I tried this I am
    getting char set conversion error.

    Is there a way that I can export a schema ( objects/data )
    to a ascii ( pipe delimitted file )?

    My goal is to export some data from one NT DB to a Solaris
    DB.

    Any help is really appreciated.

    Reji

      and we said...
The answer to #1 is most definitely yes.  You are probably
ftp'ing the file and have forgotten to say "binary" inside of
ftp.  .dmp files are binary data -- make sure the file size on
Solaris is the same as the file size on NT (betcha its smaller
as ftp changed all "0x0D 0x0A" pairs into simply 0x0A.

See
http://osi.oracle.com/~tkyte/flat/index.html
for #2.
July 06, 2000 Calvin -- Thanks for the question regarding
      "Command to execute unix scripts inside PL/SQL", version 7.3.4

      You Asked
Hi Tom,

Can you please provide me a way to execute a shell script
inside a pl/sql package? The unix script is to ftp the
os file generated from utl_file package to a remote site.

Thx,

CK

      and we said...
see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:150612348067
for some ideas on how to do this.

You'll want to do a "man netrc" in unix to see how to automate
an ftp in a script -- you cannot pass login/password to ftp but
you can use a .netrc file to do that.

July 06, 2000 Jeff -- Thanks for the question regarding "Pro-C
      retrieval of sql that errored out", version 2.2.4.0.0

      You Asked
I'm sorry to ask this, but I know I have seen this, but
there is so much documentation in Oracle I can't seem to find
it.

I have an application written with Pro-c.
I would like to have an error handler which can get the
 "failing sql" to put in an error message.
Can you point me to the right way here?

Thanks
Jeff
p.s. e-mail reply also helps. Thanks
jeff.kish@ait-mmii.com

      and we said...
Here is an example of how to do that.

See

http://technet.oracle.com/doc/precomp2x/PC_22/ch09.htm#toc124
for all of the details...

#include <stdio.h>
#include <string.h>

#include <oraca.h>
EXEC ORACLE OPTION (ORACA=YES);

static char *   USERID = "/";

#define SQLCA_INIT
EXEC SQL INCLUDE sqlca;

static void sqlerror_hard()
{
    EXEC SQL WHENEVER SQLERROR CONTINUE;

    printf("\nORACLE error detected:");
    printf("\n% .70s \n", sqlca.sqlerrm.sqlerrmc);

    printf( "Last SQL statement: %.*s\n",
             oraca.orastxt.orastxtl, oraca.orastxt.orastxtc);

    EXEC SQL ROLLBACK WORK RELEASE;
    exit(1);
}

static void process()
{
varchar data[255];

    EXEC SQL WHENEVER SQLERROR DO sqlerror_hard();
    EXEC SQL ALTER SESSION SET SQL_TRACE=TRUE;

    /* this will fail when we run it */

    EXEC SQL DECLARE C CURSOR FOR SELECT foo FROM dual;

    EXEC SQL OPEN C;
    EXEC SQL FETCH C INTO :data;
    EXEC SQL CLOSE C;

    printf( "%.*s\n", data.len, data.arr );
}

main( argc, argv )
int argc;
char *  argv[];
{
char   oracleid[50];

    strcpy( oracleid, USERID );
    EXEC SQL WHENEVER SQLERROR DO sqlerror_hard();
    EXEC SQL CONNECT :oracleid;

    oraca.orastxtf = 3; /* always save the SQL statement */

    printf("\nConnected to ORACLE as user: %s\n\n", oracleid);

    process();

    /* Disconnect from ORACLE. */
    EXEC SQL COMMIT WORK RELEASE;
    exit(0);
}
July 07, 2000 Sateesh Kumar -- Thanks for the question
      regarding "42 stored procedures using same DATABASE LINK resulting in
      error", version 8.1.5

      You Asked
Hi,
Currently the unix kernel parameters for share memory and
semaphores are
shmmax = 536870912
shmseg =200
shmmin =1
shmmni=700
semmns=800
semmni=400
semmnu=400
semms=200

The Oracle sga parameters are
Fixed size =64912
Variable size =149094400
database buffers =16777216
Redo buffers = 180224

currently the parameters are
process=100
transactions=126(Default)
distributed_transactions =10

The problem here is we have an pro*c applicaiton which creates
42 childs and each child connects to oracle and calls stored
procedures and along with this we have other pro*c which
continously updates the database.

The porcedure called by all the child processes is the same with
different parameters.
In the porcedure we take data from other database using a
database link when there is some incorrect data in the current
database.
So at the point of this error all the procedures ie 42 were
using the db link to get data from other database and inturn
resulted in errors as shown below

Error encountered while execution at :2000/07/07 09:38:15 for
symbol IBM
ORA-02042: too many distributed transactions
Error encountered while execution at :2000/07/07 09:38:15 for
symbol .IXIC
ORA-02042: too many distributed transactions
Error encountered while execution at :2000/07/07 09:38:16 for
symbol INFY
ORA-02042: too many distributed transactions
Error encountered while execution at :2000/07/07 09:38:17 for
symbol BRW

---The above list goes on for all the stored procedures-----

Now is there any problem if all the procedures uses db links. Do
we have to increse processes, transactions, distributed
transactios, shared pool size. If we have to increase the number
of preocesses whether we have to change the unix kernel
parameters

Any recommendations/suggestions ...

      and we said...
$ oerr ora 2042

02042, 00000, "too many distributed transactions"

*Cause: the distributed transaction table is full, because too
many  distributed transactions are active.

*Action: increase the INIT.ORA "distributed_transactions" or run
fewer transactions.  If you are sure you don't have too many
concurrent distributed transactions, this indicates an internal
error and support should be notified.  Instance shutdown/restart
would be a work-around.

----------------------------------------------

the default value is very small:

ops$tkyte@DEV8I.WORLD> show parameter distributed

NAME                           TYPE    VALUE
------------------------------ ------- --------------------
distributed_transactions       integer 10

thats on Solaris (it OS dependent and a function of the init.ora
parameter TRANSACTIONS).

See the server reference manual for more details on this
parameter.

July 07, 2000 Aarti -- Thanks for the question regarding "How
      do I join tables in a query that uses the 'connect by' clause?", version
      8.1.6

      You Asked
I have a Hierarchical Tree/DAG structure. The relationship info.
is kept in one table
and the detailed info is kept in the other table, i.e.

>select * from obj_rel;

parent_id    child_id
========================
Null    0
0    1
0    2
1    3
1    4
3    7
3    8
4    9
2    5
2    6
5    10
6    11

>select * from obj_detail;

obj_id    obj_name    obj_descr        leaf_node_flag
================================================================

0    Departments    This is tree root    N
1    Management    This is Mgmt subtree    N
2    Engineering    This is Engg. subtree    N
3    Sales        This is Sales subtree    N
4    Marketing    This is Mkt subtree    N
5    Development    This is Dev subtree    N
6    Deployment    This is Sales subtree    N
7    Pre-Sales    This is Sales subtree    Y
8    Post-Sales    This is Sales subtree    Y
9    Buss Dev    This is Buss Dev st     Y
10    ..        ..            ..
11    ..        ..            ..

Now I want to write a query that gets me the level, child_id,
parent_id, parent's obj_name
and child's obj_name. I can achive this by writing the following
query.

select (level-1) "LEVEL",
       child_id, parent_id,
       (select obj_name from obj_detial c where c.obj_ID =
cs.parent_id) parent_name,
       (select obj_name from obj_detail c where c.obj_ID =
cs.child_id) child_name
from obj_rel cs
connect by prior child_id = parent_id
start with parent_id = 0 ;

But I am trying to write this query in a trigger body and I am
getting a syntax error,
which means that Oracle does not support nested selects in a
select statement in a trigger body. So my
question is, is there some other way of writing the same query?
How do I join tables
in a query that uses a connect by clause? Oracle will not allow
me to join tables if
I am using a connect by clause. Is there a workaround?

Tom, you had answered one of my previous questions and I was
hoping to get an answer
for this one.

Thanks in advance.
Aart Patil

      and we said...
There is sometimes a lag between the SQL the you can enter in
straight from the command line and the SQL you can put in PLSQL
(the PLSQL sql parser might not recognize all of the
latest/greatest).  For example, the above error would be raised
with the TO_LOB call as well.

your issue is that you can run a query like:

tkyte@THINK1.US.ORACLE.COM> select (level-1) "LEVEL",
  2         child_id, parent_id,
  3         (select obj_name from obj_detail c where c.obj_ID =
  4  cs.parent_id) parent_name,
  5         (select obj_name from obj_detail c where c.obj_ID =
  6  cs.child_id) child_name
  7  from obj_rel cs
  8  connect by prior child_id = parent_id
  9  start with parent_id = 0 ;

     LEVEL   CHILD_ID  PARENT_ID PARENT_NAME
CHILD_NAME
---------- ---------- ---------- -------------------------
-------------------------
         0          1          0 name-0
name-1
         1          3          1 name-1
name-3
[snip]

11 rows selected.

in sqlplus but when you put it in plsql:

tkyte@THINK1.US.ORACLE.COM>
tkyte@THINK1.US.ORACLE.COM> begin
  2     for x in
  3     ( select (level-1) "LEVEL", child_id, parent_id,
  4              (select obj_name
  5                 from obj_detail c
  6                where c.obj_ID = cs.parent_id) parent_name,
  7              (select obj_name
  8                 from obj_detail c
  9                where c.obj_ID = cs.child_id) child_name
 10         from obj_rel cs
 11      connect by prior child_id = parent_id
 12        start with parent_id = 0  )
 13     loop
 14         null;
 15     end loop;
 16  end;
 17  /
            (select obj_name
             *
ERROR at line 4:
ORA-06550: line 4, column 14:
PLS-00103: Encountered the symbol "SELECT" when expecting one of
the following:
( - + mod not null others <an identifier>
<a double-quoted delimited-identifier> <a bind variable> avg
count current exists max min prior sql stddev sum variance
execute forall time timestamp interval date
<a string literal with character set specification>
<a number> <a single-quoted SQL string>

#It does not work.  The easiest solution is a view:

tkyte@THINK1.US.ORACLE.COM>
tkyte@THINK1.US.ORACLE.COM> create or replace view V
  2  as
  3  select (level-1) "LEVEL",
  4         child_id, parent_id,
  5         (select obj_name from obj_detail c where c.obj_ID =
  6  cs.parent_id) parent_name,
  7         (select obj_name from obj_detail c where c.obj_ID =
  8  cs.child_id) child_name
  9  from obj_rel cs
 10  connect by prior child_id = parent_id
 11  start with parent_id = 0 ;

View created.

tkyte@THINK1.US.ORACLE.COM>
tkyte@THINK1.US.ORACLE.COM> begin
  2      for x in ( select * from V ) loop
  3          null;
  4      end loop;
  5  end;
  6  /

PL/SQL procedure successfully completed.

and it works right away.  the other is to use DYNAMIC SQL as
follows:

tkyte@THINK1.US.ORACLE.COM>
tkyte@THINK1.US.ORACLE.COM> declare
  2      type rc is      ref cursor;
  3      l_cursor rc;
  4
  5      cursor c1 is select 1 lvl,
  6                          child_id,
  7                          parent_id,
  8                          obj_name parent_name,
  9                          obj_name child_name
 10                     from obj_rel, obj_detail;
 11      l_rec     c1%rowtype;
 12  begin
 13      open l_cursor for '
 14            select (level-1) "LEVEL",
 15                   child_id, parent_id,
 16         (select obj_name from obj_detail c where c.obj_ID =
 17                                    cs.parent_id)
parent_name,
 18         (select obj_name from obj_detail c where c.obj_ID =
 19                                    cs.child_id) child_name
 20              from obj_rel cs
 21           connect by prior child_id = parent_id
 22             start with parent_id = 0 ';
 23      loop
 24          fetch l_cursor into l_rec;
 25          exit when l_cursor%notfound;
 26      end loop;
 27      close l_cursor;
 28  end;
 29  /

PL/SQL procedure successfully completed.

tkyte@THINK1.US.ORACLE.COM>

That works by hiding the syntax the plsql parser doesn't
understand from plsql and letting the kernal do it.  The cursor
C1 I have above is what I call a "template" cursor.  I just
create a query that references all of the tables I'm interested
in (no joins or anything) and then select out the columns in the
right order.  Its the easiest (laziest ;)  way to create a
record type to fetch into from the ref cursor....

July 07, 2000 giorgio -- Thanks for the question regarding
      "select for update on table with the constraint -- ora 22292", version 2.1

      You Asked
Hi Tom!!

I write a PLSQL procedure that write in a blob column and I open
this blob:

DBMS_LOB.OPEN(Dest_loc1,DBMS_LOB.LOB_READWRITE);

for open this blob I must execute the select .. for update!!

sql_code1 := 'select colonna_immagine from nome_tabella where
clausola='clausula' FOR UPDATE';
execute immediate sql_code1 into blob1;

When I execute my procedure and the nome_tabella don't have the
costraint all ok, but if my table have the primary key
constraint, my procedure returned a sqlcode (ORA-22292)?

Why? There is a solution?

Thanks!!

      and we said...
That is in progress bug #1050327.

The work around is to put a "dummy" update in your procedure
that is, instead of coding:

ops$tkyte@DEV8I.WORLD> create table t ( x int primary key, y
blob );

Table created.

ops$tkyte@DEV8I.WORLD> insert into t values ( 1, empty_blob() );

1 row created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> create or replace procedure p
  2  as
  3          l_blob blob;
  4  begin
  5          execute immediate
  6          'select y from t where x = 1 for update' into
l_blob;
  7
  8          dbms_lob.open( l_blob, dbms_lob.Lob_readwrite );
  9          dbms_lob.close( l_blob );
 10  end;
 11  /

Procedure created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> exec p;
BEGIN p; END;

*
ERROR at line 1:
ORA-22292: Cannot open a LOB in read-write mode without a
transaction
ORA-06512: at "SYS.DBMS_LOB", line 593
ORA-06512: at "OPS$TKYTE.P", line 8
ORA-06512: at line 1

You can:

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> create or replace procedure p
  2  as
  3          l_blob blob;
  4  begin
  5          execute immediate 'update t set x = x where x = 1';
  6          execute immediate
  7          'select y from t where x = 1 for update' into
l_blob;
  8
  9          dbms_lob.open( l_blob, dbms_lob.Lob_readwrite );
 10          dbms_lob.close( l_blob );
 11  end;
 12  /

Procedure created.

ops$tkyte@DEV8I.WORLD> exec p

PL/SQL procedure successfully completed.

July 07, 2000 Kasthuri -- Thanks for the question regarding
      "Multiple rows from SP without using OracleTypes", version 8i

      You Asked
Hi Tom,

 I tried to retrieve a refcursor from a SP using
OracleTypes.CURSOR and it works. But, for this i have to load
the oracle.jdbc.driver which is not agreeable here. i need to
use java.sql and try to retrieve multiple rows using a Stored
proc. Can you suggest something for this. They use weblogics and
arent ready to load the oracle jdbc driver.
is there a way to retrieve multiple records calling a SP from a
java prg without using the OracleType.Cursor and not needing to
load the Oracle.Jdbc.Driver?

Please suggest
Thanks & Regards
J.Kasthuri

      and we said...
The answer is (as always) yes and no.

Here is how you can do it.  Instead of calling a stored
procedure to get a query result, we'll use a query to call a
stored procedure.

Here is a small example.  you MUST create an object type in sql
to represent your result set type.  For example -- i want to be
able to return a result set with X and Y of type number.  I
would:

ops$tkyte@DEV8I.WORLD> create or replace type myScalarType
  2  as object
  3  ( x int,
  4    y int
  5  )
  6  /

Type created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> create or replace type myTableType
  2  as table of myScalarType;
  3  /

Type created.

Now I can create a function that returns that type

ops$tkyte@DEV8I.WORLD> create or replace
  2  function demo_proc2( p_rows_to_make_up in number )
  3  return myTableType
  4  as
  5      l_data             myTableType := myTableType();
  6  begin
  7      for i in 1 .. p_rows_to_make_up
  8      loop
  9          l_data.extend;
 10          l_data(i) := myScalarType( i, i );
 11      end loop;
 12      return l_data;
 13  end;
 14  /

Function created.

and then select * from it

ops$tkyte@DEV8I.WORLD> select *
  2    from the ( select cast( demo_proc2(5) as mytableType )
  3                 from dual );

         X          Y
---------- ----------
         1          1
         2          2
         3          3
         4          4
         5          5

ops$tkyte@DEV8I.WORLD>

In this fashion java never calls a stored procedure -- java
does sql, sql calls the stored procedure and you get a result
set.

Other then that, I am not aware of other methods.


Subject | Article | Last Updated (East coast time)
Incresing size of source$ | article only | Jul 08, 2000 09:29 am
Fine-Grained Acces Control | article only | Jul 08, 2000 09:39 am
Oracle 8 patch -- error on write of some dll's | article only | Jul 08, 2000 10:02 am
select statement that returns limited number of records | article only | Jul 08, 2000 10:13 am
diff b/w oracle service & instance | article only | Jul 09, 2000 10:09 am
Re : Oracle 8.1.5 -- is it oracle8i | article only | Jul 10, 2000 06:29 am
Dynamic Alerts -- using a web page to let someone know about new data. | article only | Jul 10, 2000 06:41 am
Column Encryption | article only | Jul 10, 2000 07:11 am
Is there any data type which I can define and update its value position by position? | article only | Jul 10, 2000 07:14 am
diplaying alert when closing mdi_window | article only | Jul 10, 2000 07:43 am
Bind Variables | article only | Jul 10, 2000 03:37 pm
TCL in Database Triggers -- tcl=transaction control like commit/rollback | article only | Jul 10, 2000 04:25 pm
backup database through a stored procedure | article only | Jul 11, 2000 08:51 am
transportable tablespace -- feature not enabled. | article only | Jul 11, 2000 08:55 am
Re your answer to Ted Chyn "generate sql for sqlldr" | article only | Jul 11, 2000 08:59 am
Exact differences in the Standard edition and enterprise edition | article only | Jul 11, 2000 09:05 am
Rollback segment switching | article only | Jul 11, 2000 10:05 am
Using email to acknowledge receipt of data submitted via a form -- v7.3 database | article only | Jul 11, 2000 10:18 am
ERRORLEVEL -- cmd script processing on NT with SQLPlus | article only | Jul 11, 2000 08:44 pm
Space | article only | Jul 11, 2000 09:01 pm
Date Arithmetic | article only | Jul 11, 2000 09:35 pm
How to estimate size for an Index Organised table | article only | Jul 12, 2000 07:47 am
calcule space required for tables and indexes | article only | Jul 12, 2000 07:47 am
Delete duplicate rows, committing in a trigger. | article only | Jul 12, 2000 07:56 am
1023 character barrier in UTL_FILE.PUT_LINE | article only | Jul 12, 2000 08:22 am
Oracle Enterprise Manager - SQL Text -- how to get it myself in sqlplus | article only | Jul 12, 2000 08:56 am
Problem using ODMA (Oracle Migratation Assistant) for 8.0.5 to 8.1.6 | article only | Jul 12, 2000 12:46 pm
ActiveX | article only | Jul 12, 2000 01:25 pm
FORMS ON WEB | article only | Jul 12, 2000 02:06 pm
Oracle on other platforms | article only | Jul 12, 2000 02:53 pm
How to find the shadow processes in Unix? | article only | Jul 12, 2000 03:00 pm
Can Sqlloader load data where the fieldnames are mentioned in the first line? | article only | Jul 12, 2000 03:41 pm
inserting data values with puctuation like single quote character | article only | Jul 12, 2000 04:53 pm
Summary Tables/materialized Views/OCI | article only | Jul 13, 2000 08:40 am
sorting userobjects by dependencies | article only | Jul 13, 2000 09:02 am
Clustering and Partions | article only | Jul 13, 2000 09:07 am
Query of an LOV ! | article only | Jul 13, 2000 10:02 am
Single SQL statement to calculate running total. | article only | Jul 13, 2000 11:43 am
Creating a Database for Report Generations | article only | Jul 13, 2000 12:52 pm
v$ table and shell scripts using svrmgrl | article only | Jul 13, 2000 02:52 pm
Changing Intenal Password -- on windows NT with 7.3 | article only | Jul 14, 2000 11:24 am
running a cron job to pick up all databases and put output to 1 file | article only | Jul 14, 2000 11:43 am
sequence - how to do an IDENTITY type | article only | Jul 14, 2000 01:00 pm
Import/Export -- why does it use rollback | article only | Jul 14, 2000 01:05 pm
Index Clarificatin. -- why primary key | unique, why not a unique index. | article only | Jul 14, 2000 01:35 pm
Using joins in connect by?? | article only | Jul 14, 2000 01:49 pm
Cumulative Frequency | article only | Jul 14, 2000 03:00 pm
Converting CLOB to varchar2 | article only | Jul 14, 2000 03:32 pm
JDBC Autocommit | article only | Jul 14, 2000 06:37 pm
Passing A Ref Cursor OR VARRAY into PL/SQL block | article only | Jul 14, 2000 06:59 pm
row(s) 1 - 50 of 50
July 08, 2000 -- Thanks for the question regarding "Incresing size of source$", version 8.1.6
You Asked
Before creating a new DB instance and in anticipation of large
number of big stored procedures,
I'd would like to increase the initial and next values so that
the source$ table does not get into
hundreds of extents.
Should I modify the source sql.bsq script or
alter the table's next value by ALTER TABLE SYS.SOURCE$ STORAGE
(NEXT 30M) after
the DB instance has been created ?

Thanks
and we said...
It is most straight forward (and allowable) to modify sql.bsq.

I would not be overly concerned about hundreds of extents
though.  My source$ is in 535 extents.  Its *not* a big deal
whatsoever.  I never plan on truncating or dropping this table
-- and those are the only operations that will be affected by
tons of extents in a dictionary managed tablespace (well full
scans can be if your extent sizes are not multiples of your
multiblock read count but I don't full scan this table
frequently and the impact is marginal).
July 08, 2000 Paul -- Thanks for the question regarding "Fine-Grained Acces Control", version 8.1.5
You Asked
Hi Tom,

We are working with WebDB Forms and need to restrict the data
viewed in a particular table depending on the user profile.

For example, we consult in the Educational Sector and need to
restrict access to data to a particular Homeroom Teacher. While
the data for all the homeroom teachers is in the database we
only want the homeroom teacher that logged onto Oracle, via
Webdb to access student data in the table that is assigned to
their homeroom.

We where told that "Fine Grained Access Control" should handle
this but we can not fine very much information on the subject
that will help us to incorporate it.

Any help would be appreciated.

Regards
Paul McLean
and we said...
Check out:
http://osi.oracle.com/~tkyte/article2/index.html
for more info.
July 08, 2000 Murtaza -- Thanks for the question regarding "Oracle 8 patch -- error on write of some dll's", version 8.0.5
You Asked
Hi Tom

I downloaded patch 80526 for the Oracle 8 database 8.0.5.0.0.
from Metaling. I am running setup and get Software Asset Manager
and select oracle 8 patch. Upon starting to install, it gives me
write error when copying ora805dll from the patch directory to
Orant/bin directory

What could be the reason

Thanking you in advance
Best Regards
Murtaza
and we said...
This is support note <Note:1067888.6> on this subject

Problem Description:
====================

You are attempting to install Oracle products on Windows NT and
you encounter errors that stop the install.  This is most likely
to occur during an upgrade or a patch installation.  It should
not happen on a clean install.

For example, during an upgrade, you may get a 'write error
occurred while trying to copy' on one or more of the following
DLL's:

CORE35.dll, CORE40.DLL, OCIw32.DLL, ORA804.dll, ORA805.dll,
NTS80.dll, etc.

This is not a comprehensive list of DLL's that may be referenced
by this or similar errors.

Alternatively, you may get a message that the 'Required Support
Files are in use' and that you need to 'Stop all running Oracle
Services' before attempting  to install.

However, you verify that all Oracle services are stopped, and
you may have even set them all to manual and rebooted the
machine, but you still get the same error message.

Problem Explanation:
====================

Most likely a 3rd party utility or Operating System utility has
one or more Oracle DLL's in use.

Solutions:
==========

Solution Description
--------------------
1. Make sure that you have verified that all Oracle Services are

   stopped.
2. Make sure all third party software services that access
   Oracle are also stopped.
3. Remove the Oracle home path from the System Environment
   Variables:
   a. Open Control Panel.
   b. Double click "System" icon.
   c. Click the "Environment" tab.
   d. Click on the "Path" variable.
      Modify it by removing the Oracle home from the path.
   e. restart
4. Attempt your patch install again.

Explanation
-----------
An application is accessing these dll files and by removing this
variable, the application is no longer able to locate these
files.

Solution Description:
=====================

Likely processes or services that have caused problems include
the SNMP service or MSDTC (Microsoft Distributed Transaction
Coordinator) service in the Windows NT Control Panel ->
Services.  If either of these Services exist and is running,
it should be stopped before proceeding with the Oracle
installation.

Also, check for services related to tools such as Compaq Insight
Manager.  Insight Manager is known to have caused problems with
the Oracle install as well.  Shut it down and stop Insight
Manager services before proceeding with the Oracle install.

If none of these services exist, or if you still have the same
problem after stopping the services, then you will need to look
for other running Services or Processes which may have some type
of lock on an Oracle DLL.  Look through the Processes list in
the Windows NT Task Manager for likely candidates such as
Backup software or Antivirus software.

If this still does not resolve the problem, you may need to
resort to using a utility such as TLIST, which comes on the
Windows NT 4.0 Resource Kit.  By running TLIST with the Process
name or PID of processes listed in the Windows NT Task Manager,
you will get a list of all DLL's the process is accessing.
Run TLIST against each Process in the Task Manager until you
find which process has Oracle DLL's in use.

In a worst case scenario, you may be able to just rename the DLL
in question and continue on, allowing the Installer to copy a
new version into the "ORACLE_HOME\BIN" directory.

NOTE:
=====

Tlist is available as part of the Windows NT Resource Kit.  You
may also be able to find it at other internet sources:

Use TLIST from a Windows NT Command prompt:

C:\> tlist <process_name>
or
C:\> tlist <PID>

For further usage, type

C:\> tlist /?

Caution:

Before stopping services at random or killing a process through
the Task Manager, you should have some idea of what the service
or process does, and hopefully some idea of how to shut it down
gracefully.  If you are not sure, you may want to contact the
Application Vendor or Microsoft for more information.

Solution Explanation:
=====================

Shutting down all processes or services that are using Oracle
DLL's allows the install program access to the DLL's.
July 08, 2000 Girish -- Thanks for the question regarding "select statement that returns limited number of records", version 8i
You Asked
Hi Tom!
We have a table called T_BLOODGROUPS in which we have records of

individuals with their blood groups.

If we query the table with SELECT * FROM T_BLOODGROUPS WHERE
BLOODGROUP = 'O+ve', we get all records matching the where
condition. We would, however, like to restrict the number of
records returned to 10 only.

Also, we will specify the ROWNUM to start with. The query must
return exactly 10 records matching the where clause whose
ROWNUMs are greater than the one that we specify.

Could you please tell us if it is possible to write such a query
and if it is, could you give us the query? If it is not possible
through a query but through a procedure, we would like to have
the procedure.

Thanks,
Girish
and we said...
You can do this using rownum and inline views.  In general to
get rows N through M of a result set -- you can see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:62012348055
You can use a simplified version of that query to just limit the
number of rows to M.
July 09, 2000 Syed -- Thanks for the question regarding "diff b/w oracle service & instance", version oracle 8.1.5
You Asked
hey
What is the difference b/w oracle instance and oracle services

thanx
A.Mannan
and we said...
See
http://technet.oracle.com/doc/server.815/a68020/ch2.htm#140388
for a detailed explaination.

In short, an Oracle instance is a collect of background
processes/threads (dbwr, reco, smon, pmon, etc...) and a memory
segment (SGA).  It is more or less a physical thing.  An
instance will mount at most 1 database at a time -- a database
might be mounted by many instances (parallel server).

A service on the other hand is a logical thing.  A single
database might have many service names assigned to it, on the
other hand -- a service might span many databases.

(on NT, services are the device by which we start and stop the
database as well.  They aren't an Oracle thing but an OS thing
at that point)
July 10, 2000 Vince Crismer -- Thanks for the question regarding "Re : Oracle 8.1.5 -- is it oracle8i", version 8.1.5
You Asked
Greetings,

Hi there. I just want to know if Oracle 8.1.5 considered as
Oracle 8i and if it has an Intermedia? Thanks.

- Vince Villena
and we said...
Oracle8i is the marketing name for the database release 8.1.
So, yes -- 8.1.5 is Oracle8i.

interMedia is available with 8.1.5.

See
http://technet.oracle.com/doc/server.815/a68020/toc.htm
for a document that describes the features of Oracle8i.
July 10, 2000 Sanjay -- Thanks for the question regarding "Dynamic Alerts -- using a web page to let someone know about new data.", version 4.0.8.1
You Asked
Tom,
How can we implement alerts in web applications. For e.g
consider a situation where a user is processing
a queue (list of questions waiting to be answered) and
needs to be notified when a new question arrives in his
inbox. The notification could be say a popup box
saying "New Question notification". Is there a way we
can implement this using PL/SQL ( or in conjunction
with Java, since threads are available in Java ?).
thanks
sanjay
and we said...
What we've done in the past is to use a META REFRESH tag on an
HTML window.  Your application, when you went to the "home" page
of it, would use javascript to open another window -- probably
with no decoration (sort of like an "ad" popup you see at
various sites).  The page displayed on this window would have:

<HTML><HEAD>
<META HTTP-EQUIV="Refresh"
                CONTENT="60;URL=my_procedure?session_id=123">
<TITLE>Alerts</TITLE>
</HEAD><BODY>
..... any incoming info would be here.  every 60 seconds the
page refreshes with any existing|new alerts
...

My_procedure would be a plsql routine or whatever you use to
code your "cgi" applications.  It will be invoked every 60
seconds and would look for new data.
July 10, 2000 Lakshman -- Thanks for the question regarding "Column Encryption", version 7.3
You Asked
Tom,
I have a table(Utable) which maintains appliation Uname(Username) and
Pwd(Password) as columns .Now I enter these columns from application Developer
2000.When I select back this table from SQL prompt
 Select * from Utable;
I should get the column Pwd as encrypted(Display only **** )

Please find a Solution for this and let me know.

Laxman
and we said...
I would never store passwords as is in the database.  In 7.3 there are no
encryption capabilities builtin (8.1.6 adds these).  Even then, I would never
store a password in the database.  I would do like Oracle (and unix and lots
of other things) does and store a one-way digest of the password.

For more info see:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:95412348059
....
July 10, 2000 Ying -- Thanks for the question regarding "Is there any data type which I can define and update its value position by position?", version Oracle8.0.5
You Asked
Hi Tom,
My issue is to update the news feed to the database where the
news feed is not complete most of the time. I would like to
design such that instead of define different number of columns
for different type of news, I would like to just define a column
of data type varchars. Whenever there are news comming in, I
will insert into this column. Sometimes the news feed is not
complete in the sense that there may 6 lines out of 10(variable)
received at this time. The next 4 lines will arrive then. Then
the jsp program will just select this column and display. So my
query is:
Is it possible to insert 6 lines into this column at first and
when the next 4 lines arrive, I would now where to append to eg.
line# 7 in this case?

Is there any data type where I konw the last position I
updated/inserted? Or it there any Oracle utility I can use?

Pls advise. Thank you.

Regards,
Hwee
and we said...
I would not use varchar2 as this will limit you to 4000
characters/news items and thats probably not enough.  I would
use a CLOB (character lob).  CLOB's have full piecewise
read/write access (so yes, you can append to the end of a lob --
in fact you can treat a lob much like a FILE with random io
capabilities).

For more info about lobs, see the application developers guide
(available on technet.oracle.com if you do not have a copy).
You'll be interested in the dbms_job package and or the jdbc
developers guide (for streaming blobs) as well.  I myself like
the dbms_lob package for most operations.
July 10, 2000 mubeen -- Thanks for the question regarding "diplaying alert when closing mdi_window", version 8.0
You Asked
sir

I would like to know is there any way to prevent the end user
from closing the application by clicking on close button of
mdi_window. Or at least can I display an alert like " This will
end ur session ".  bcauze at the end of one application session
I want to do some other operation.

thanks for ur help

mubeen
and we said...
You can use a KEY-EXIT trigger at the form level with a call to
exit_form() if you want to actually leave the form.

For example:

if ( show_alert( 'CONFIRM_EXIT' ) = ALERT_BUTTON1 )
then
        exit_form;
end if;

where CONFIRM_EXIT is an alert with the standard OK|Cancel
buttons and a message to the effect "you will be exiting forms".
July 10, 2000 Ivan -- Thanks for the question regarding "Bind Variables", version 8.1.6
You Asked
Instead of using literals
e.g
select firstname,surname from employee where id=1234

I need to use bind variables in order to avoid re parsing the
statement

e.g
SQL> variable employee_number_ws number
SQL> select firstname,surname from employee where
id=:employee_number_ws

My question is where is the value to be used in the variable
specified?
and we said...
Well, it depends on the environment -- in sqlplus you would:

SQL> variable e number
SQL> exec :e := 1234;
SQL> select * from emp where empno = :e;

Now, you should note that in SQLPLUS, using a bind variable
won't buy you very much.  The reason is that you are still
dynamically executing the "exec :e := 1234;" -- that statement,
which is really "begin :e := 1234; end;" will be parsed,
compiled and executed.  The SELECT * will be reused over and
over.

In a "real" programming environment, I would have access to
cursors and statements and I would be able to PREPARE a statment
once and then set various bind variables on it and execute it
over and over.  This is where bind variables come into play.  If
you specify the 3/4gl you are going to be using -- we can show
you how to bind in that language perhaps...
Review & Followup
Rating: 4
Using Bind Variables in ASP March 15, 2001
Reviewer: Martin Zangger from Copenhagen, Denmark
I would appreciate very much the answer specified according to ASP.

TIA mz@krak.dk

Rating: 3
Bind Variable in 3/4gl May 18, 2001
Reviewer: Charanjiv from New Delhi, India
I have been looking at usage of bind variables in this site, one thing i didnt
find and a lot of developers question us (dba's) about is how to use them in
3/4gls. We are basically developing in Java / EJB / VC++. any pointers towards
that wud be helpful

July 10, 2000 G. R. -- Thanks for the question regarding "TCL in Database Triggers -- tcl=transaction control like commit/rollback", version Oracle 8i
You Asked
We know that we cannot use TCL (Commit, Rollback) in database
triggers.  Then what is the possible way to commit the
transaction.  For instance I have a row level trigger that fires
before update on EMP table and it inserts the old record in
EMP_AUDIT table, I want the transactions to be committed
whenever the trigger fires.  How can I do that???
and we said...
Well, I will argue that you do not want the transaction to be
committed but rather that you would like to have a NEW
transaction -- independent from the parent transaction --
execute and commit.  In this fashion you can audit attempts to
modify data even if the attempts subsequently fail.

Since you are using 8i (release 8.1) you have access to a
feature called autonomous transactions -- See
http://osi.oracle.com/~tkyte/autonomous/index.html
for a paper I wrote on this feature.  Specifically -- it gives
you the ability to do what you ask (or rather what I described
above).  You can create a sub-transaction that is independent of
the parent and perform a commit/rollback in it -- even from a
trigger.
Review & Followup
Rating: 5
March 14, 2002
Reviewer: Ghulam Rasool
Tom has given me the solution, I was looking for.  Thanks TOM

July 11, 2000 Kaiquan -- Thanks for the question regarding "backup database through a stored procedure", version Oracle 8.1.6
You Asked
Dear sir,

I am now using Oracle8.1.6 database. My OAS is 4.0.8.
Please tell me how to create a stored procedure which can be
executed every a day to backup the whole database.

Thank you very much!
Best regards

John Chen
and we said...
Well, while you could feasibly do it, it would not be a "normal"
way to do it.  You need to do a couple of things during a backup
that PLSQL is not adept at doing (like copying large files,
interacting with tape devices and such).

You could write a java stored procedure I suppose to do that,
java has more abilities in this particular arena.

The real answer is to use Oracle Enterprise Manager and Recovery
Manager (RMAN) to schedule RMAN to perform backups.  See
http://technet.oracle.com/doc/oracle8i_816/server.816/index.htm
the backup and recovery section for more information.
July 11, 2000 Kenneth -- Thanks for the question regarding "transportable tablespace -- feature not enabled.", version 8i
You Asked
Dear Tom,

You rightly  answered that 8.0.3 was upgrade to 8.0.5 and to in
order to have ORA_KGLR7_DEPENDICIES to work u0800030.sql must be
run.

When I executed  it , it is running for more than 1 day , infact
it is still in progress. Performance has degraded. What is the
rescue  in such cases when these U...  scripts take so long.

2.  According to oracle8i doc for creating a transportable
tablespace oracle
enterprise is required, which i guess we have.

I also gave the command given in the doc. But it gives me an
error :

"Feature not enabled".

When i use this

Command:
exp user/pwd transport_tablespace=Y tablespaces=<name>
constraints=n
grants=y triggers=n

it fails .Where could i have gone wrong?

Thanks for all the prevouis help and tips provided.
Kenneth
and we said...
1 -- that script should be run in a "pristine" environment.  You
should shutdown, startup and limit connections (enable
restricted session), run the proper upgrade scripts and then
open the database for all.

It is currently locked -- you must have other sessions
attempting to access these objects.

2 -- select * from v$option will show you what you have and what
you do not.  If these features are not enabled, you do not have
that version installed.  A select on my v$option shows:

ops$tkyte@DEV8I.WORLD> l
  1  select * from v$option
  2*
ops$tkyte@DEV8I.WORLD> /

PARAMETER                                VALUE
---------------------------------------- ----------
Partitioning                             TRUE
Objects                                  TRUE
Parallel Server                          FALSE
Advanced replication                     TRUE
Bit-mapped indexes                       TRUE
Connection multiplexing                  TRUE
Connection pooling                       TRUE
Database queuing                         TRUE
Incremental backup and recovery          TRUE
Instead-of triggers                      TRUE
Parallel backup and recovery             TRUE
Parallel execution                       TRUE
Parallel load                            TRUE
Point-in-time tablespace recovery        TRUE
Fine-grained access control              TRUE
N-Tier authentication/authorization      TRUE
Function-based indexes                   TRUE
Plan Stability                           TRUE
Online Index Build                       TRUE
Coalesce Index                           TRUE
Managed Standby                          TRUE
Materialized view rewrite                TRUE
Materialized view warehouse refresh      TRUE
Database resource manager                TRUE
Spatial                                  TRUE
Visual Information Retrieval             TRUE
Export transportable tablespaces         TRUE
Transparent Application Failover         TRUE
Fast-Start Fault Recovery                TRUE
Sample Scan                              TRUE
Duplexed backups                         TRUE
Java                                     TRUE

32 rows selected.

ops$tkyte@DEV8I.WORLD>

Additionally, the sqlplus banner will tell you whether you have
EE or not:

$ sqlplus /

SQL*Plus: Release 8.1.5.0.0 - Production on Tue Jul 11 08:53:21
2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to:
Oracle8i Enterprise Edition Release 8.1.5.0.0 - Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

ops$tkyte@DEV8I.WORLD>
July 11, 2000 Stuart -- Thanks for the question regarding "Re your answer to Ted Chyn "generate sql for sqlldr"", version Oracle7 Server 7.3.4.5.0
You Asked
Hello from the UK!

I am a big fan of your column - I print off your answers and
read
them on the way to/from work on the bus!

I have a query about your script in reply to Ted Chyn, in which
you generate SQL*Load instructions and data from a database to
reload (in the event of a database problem).

In spooling the data, you use two queries of the
user_tab_columns
table - the first to get the first c-1 columns, pipe-separated,
and the second to get the last column (without a pipe).

You use the pipe as a separator as this is unlikely to occur
in the data (unlike a comma, which could be part of an address
field, for example).

Could you not achieve the same effect simply by using
set colsep '|'
select * from $X
/

Or have I missed something?
Keep up the good work!

Stuart Smith
PS Are you really one person, or is "Tom" a pseudonym for a
whole team of experts!
and we said...
I used a pipe right in the query to "compress" the output.  For
example:

scott@DEV8I.WORLD> set colsep |
scott@DEV8I.WORLD> select * from dept;

    DEPTNO|DNAME         |LOC
----------|--------------|-------------
        10|ACCOUNTING    |NEW YORK
        20|RESEARCH      |DALLAS
        30|SALES         |CHICAGO
        40|OPERATIONS    |BOSTON

scott@DEV8I.WORLD> select deptno||'|'||dname||'|'||loc from
dept;

DEPTNO||'|'||DNAME||'|'||LOC
------------------------------------------------------------
10|ACCOUNTING|NEW YORK
20|RESEARCH|DALLAS
30|SALES|CHICAGO
40|OPERATIONS|BOSTON

I did not like the idea of having all of that embedded
whitespace.  It (my method) does impose another restriction in
that the max width of a given row is 4000 bytes in 8.0 and up
and 2000 bytes in 7.x and before.

Tom is one person -- I ask others for help with some questions
(especially Oracle Apps questions) but answer most all of them
myself.
July 11, 2000 Vishwanathan -- Thanks for the question regarding "Exact differences in the Standard edition and enterprise edition", version 8.1.6
You Asked
I have 3 questions

Q1 What are the differences in the Oracle8i Standard Edition
(v8.1.6) and Oracle8i enterprise edition (v8.1.6)?

Q2) If one wants to upgdade from Standard edition to enterprise
editionhow is the upgradation done?

Q3) Can one use the Oracle advanced security option with Oracle
standard edition ? If so how?

Regards
Vishi
and we said...
for 1, please see:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/ch4.htm#73594
it covers what FEATURES (features come with, no extra license)
you get in STANDARD vs EE.

it covers what OPTIONS (options are separately licensed -- they
do not just "come with") you may obtain with STANDARD vs EE.

for 2, you must contact your sales representative.  You would
purchase the upgraded software and then do an upgrade on your
system.

For 3, Advanced Security is available as an option with the
Enterprise Edition but not the Standard Edition.
July 11, 2000 -- Thanks for the question regarding "Rollback segment switching", version 8.1.6
You Asked
Solaris 2.6
Oralce 8.1.6

When runngin the initjvm.sql, I noticed that rollback segments
were full.
From the alert.log, it looks like when 1 rollback segment is
full, Oracle switches to another .
RBS are used up.
Is this normal behaviour of RBS ?
Anything lost or damages done ?
We have 4 rbs. What happens when the last one is full. Does it
stop there? Or it wraps around ?

'Thread 1 cannot allocate new log, sequence 44' means log
records are created faster than the log writer can
switch logfiles ?

ORA-1650: unable to extend rollback segment RBS04 by 16 in
  tablespace RBS

Failure to extend rollback segment 5 because of 1650 condition
FULL status of rollback segment 5 set.
Mon Jul 10 13:28:27 2000
Thread 1 cannot allocate new log, sequence 44
Checkpoint not complete
  Current log# 1 seq# 43 mem# 0:
/u02/oradata/tst8161/redo01a.dbf
  Current log# 1 seq# 43 mem# 1:
/u03/oradata/tst8161/redo01b.dbf
Thread 1 advanced to log sequence 44
  Current log# 2 seq# 44 mem# 0:
/u02/oradata/tst8161/redo02a.dbf
  Current log# 2 seq# 44 mem# 1:
/u03/oradata/tst8161/redo02b.dbf
Mon Jul 10 13:28:36 2000
FULL status of rollback segment 5 cleared.
Mon Jul 10 13:30:03 2000
ORA-1650: unable to extend rollback segment RBS02 by 16 in
  tablespace RBS

Failure to extend rollback segment 3 because of 1650 condition
FULL status of rollback segment 3 set.
FULL status of rollback segment 3 cleared.
Mon Jul 10 13:31:46 2000
Thread 1 advanced to log sequence 45
Current log# 3 seq# 45 mem# 0: /u02/oradata/tst8161/redo03a.dbf
 Current log# 3 seq# 45 mem# 1: /u03/oradata/tst8161/redo03b.dbf
Mon Jul 10 13:32:25 2000
ORA-1650: unable to extend rollback segment RBS03 by 16 in
  tablespace RBS

Failure to extend rollback segment 4 because of 1650 condition
FULL status of rollback segment 4 set.
Mon Jul 10 13:32:56 2000
Thread 1 advanced to log sequence 46
  Current log# 1 seq# 46 mem# 0:
/u02/oradata/tst8161/redo01a.dbf
  Current log# 1 seq# 46 mem# 1:
/u03/oradata/tst8161/redo01b.dbf
Mon Jul 10 13:33:05 2000
FULL status of rollback segment 4 cleared.
Mon Jul 10 13:35:09 2000
Thread 1 advanced to log sequence 47
  Current log# 2 seq# 47 mem# 0:
/u02/oradata/tst8161/redo02a.dbf
  Current log# 2 seq# 47 mem# 1: /u03/oradata/tst8161
/redo02b.dbf
Mon Jul 10 13:35:25 2000
ORA-1650: unable to extend rollback segment RBS04 by 16 in
  tablespace RBS

Failure to extend rollback segment 5 because of 1650 condition
FULL status of rollback segment 5 set.

Thank you.
and we said...
You have 2 issues you want to correct here.  Issue one is:

'Thread 1 cannot allocate new log, sequence 44' .  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:69012348056
for the cause and the solution.

The other more troubling error (troubling because it prevents
things from taking place whereas the cannot allocate new log
just means they take longer to complete) is the
ORA-1650: unable to extend rollback segment RBS02 by 16
errors.  That means whatever operation was being done at that
point in time failed and was rolled back (if you got these
during the run of initjvm -- it failed, you'll need to rerun it
after correcting).

Having sufficient rollback is critical for the database.
Don't shortchange it.

Start with at least a couple (5 say) rollback segments whose
initial=next=1m and minextents=25, maxextents=150.  I
like to put each rollback segment into its own tablespace with
its OWN autoextensible datafile.  This allows each rollback
segment to grow when needed (if the OS has room) and allows me
to shrink any of the rollback segments back down to 25megs when
I want to and shrink the corresponding datafile as well (i do
this before backups for example).  In this fashion, I let the
rollback grow upto 150m (but no more -- really really huge
transactions will still fail but I want them to -- you might
not).

We do not switch to a new rollback segment when one fills up
(that describes our behaviour with redo, not undo).  We fail the
transaction that was taking place and roll it back.  This is an
error you really don't want to see.
July 11, 2000 Kum-Sung -- Thanks for the question regarding "Using email to acknowledge receipt of data submitted via a form -- v7.3 database", version Forms 5.0, Reports 3.0
You Asked
Dear Sir:

I am building a 3-tiered, web-based database application using
Oracle 7.3.4 as the backend, Developer 2000 forms (version 5.0)
as the front end, and Oracle Web Applications Server (OWAS 3.0)
as the middle tier. The database is on a Unix Box (Data General)
while the OWAS is on an NT box.

Our facility operators would use the deployed web form to submit
environmental data to us via the Internet.  For each submission
received, I would like the application to automatically generate
and send an email to the customer with an attached copy of the
data received, much like what Amazon.com would do after you have
successfully placed an order. We use GroupWise here for email.

How do I implement this functionality in Oracle?  Please advise.
 Thanks.
and we said...
In 7.3, the solutions are limited.  There are at least 3 I can
think of right away (and have used all 3 at various points).  By
far, the easiest method is:

1) use a stored procedure to write an OS file.  This OS file is
the email.  have a cron job run every N minutes to "push" the
queue (deliver any files that appear in this directory and then
get rid of them).

2) more complex but more 'immediate'.  If you set up a cgi-bin
script that can do an email on the OAS side -- such that if you
had a form:

<form action=do_mail>
<input type=text name=to>
<input type=text name=subj>
<input type=text name=body>
<input type=submit>
</form>

it would work (and it would send "mail" to TO with a subject
SUBJ and a body of BODY).  You could write this cgi-bin in perl,
shell, C, anything you wanted.

Now, you could write a stored procedure that executed:

resp := utl_http.request(
'HTTP://hostname/cgi-bin/do_mail?to=tkyte%40us.oracle.com&subj=Hi
%20There&body=How%20are%20you%3F' );

That would send the email for you by running the cgi-bin script.

Here is a small URLENCODE routine you can use to get all of the
right escape characters for a URL:

create or replace function urlencode( p_str in varchar2 ) return
varchar2
as
    l_tmp   varchar2(6000);
    l_len   number default length(p_str);
    l_hex   varchar2(16) default '0123456789ABCDEF';
    l_num   number;
    l_bad   varchar2(100) default ' >%}\~];?@&<#{|^[`/:=$+''"'
|| chr(10);
    l_char  char(1);
begin
    if ( p_str is NULL ) then
        return NULL;
    end if;

    for i in 1 .. length(p_str) loop
        l_char :=  substr(p_str,i,1);
        if ( instr( l_bad, l_char ) > 0 )
        then
            l_num := ascii( l_char );
            l_tmp := l_tmp || '%' ||
                substr(l_hex, mod(trunc(l_num/16),16)+1, 1 ) ||
                substr(l_hex, mod(l_num,   16)+1, 1 );
        else
            l_tmp := l_tmp || l_char;
        end if;
    end loop;

    return l_tmp;
end;
/

3) use database pipes to create a "pipe" daemon in C that can
send mail as well. See
http://osi.oracle.com/~tkyte/plex/index.html
for more info on that concept.
July 11, 2000 Kevin -- Thanks for the question regarding "ERRORLEVEL -- cmd script processing on NT with SQLPlus", version ORACLE 8.1.5.0
You Asked
How to set the ERRORLEVEL code in PL/SQL to notify abnormal
condition on Windows NT?
Here I am going to describe what I want to know.
I make a script as follows that would run on Windows NT.
1)@echo off
2)echo PL/SQL module ITD_DOWNLOAD_GEN_BAT.GET_FILE_INFO starting
3)%ORACLE_HOME%\bin\sqlplus -s MY_UID/MY_PWD E:MY_CODE\TEMP.SQL
4)IF %ERRORLEVEL%==0 GOTO :NEXTONE
5)echo Error condition raised. Peocessing STOPPED abnormally
6) GOTO :NEXTTWO
7):NEXTONE
8) echo PROCESS END NEXT STEP started
9) execute next step ...
10):NEXTTWO
11)...

where \TEMP.SQL has "EXECUTE my_loading;"
I made PL/SQL program, my_loading. In this my_loading program, I
want to issue ERRORLEVEL when my processing would go to
exception routine. Also when I detact some bad condition in my
program, I want to return ERRORLEVEL non zero value to termiante
my processing. Here, the treminating means do not execute next
step.
Thnaks.
and we said...
If you use the "whenever sqlerror exit 1" directive at the head
of your script -- any exceptions not handled by your code will
cause SQLPlus to exit with an error.  We can use that.

I wrote a small test.cmd script:

@echo off

sqlplus scott/tiger@ora8i.us.oracle.com @test1.sql
if %ERRORLEVEL%==0 goto :NextOne

echo Error Detected.  test1.sql
goto :END

:NextOne

sqlplus scott/tiger@ora8i.us.oracle.com @test2.sql

if %ERRORLEVEL%==0 goto :NextOne2

echo Error Detected. test2.sql
goto :END

:NextOne2

echo Exiting all successful
exit

:End
echo exiting with error condition
=========================================================

test1.sql was simply:

whenever sqlerror exit 1
exec null;
exit

=========================================================
it was designed to succeed.  test2.sql was designed to fail:

whenever sqlerror exit 1
exec raise_application_error( -20002, 'Simulated failure' );
exit

When I ran this -- i saw:

C:\Documents and Settings\Thomas Kyte\Desktop>test

SQL*Plus: Release 8.1.6.0.0 - Production on Tue Jul 11 20:44:01
2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to:
Oracle8i Enterprise Edition Release 8.1.5.0.0 - Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

PL/SQL procedure successfully completed.

Disconnected from Oracle8i Enterprise Edition Release 8.1.5.0.0
- Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

SQL*Plus: Release 8.1.6.0.0 - Production on Tue Jul 11 20:44:07
2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to:
Oracle8i Enterprise Edition Release 8.1.5.0.0 - Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

BEGIN raise_application_error( -20002, 'Simulated failure' );
END;

*
ERROR at line 1:
ORA-20002: Simulated failure
ORA-06512: at line 1

Disconnected from Oracle8i Enterprise Edition Release 8.1.5.0.0
- Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production
Error Detected. test2.sql
exiting with error condition
July 11, 2000 Arthur -- Thanks for the question regarding "Space", version 8.1.5
You Asked
Tom,

I am looking for some ways to report on the amount of user/free
space in the tables, tablespaces and datafiles.  I want to
monitor
this and perhaps keep history to view growing trends.

What types of queries and from which dictionary objects would
show me the space data I am looking for?  There are so many
different ways of looking at space.........

Thanks,

Arthur
and we said...
Your right -- there are many ways to look at this.

There is allocated space, space allocate to an object (and it
might be using it, it might not be)

There is space actually used....  Or was used at some point (we
call the blocks that have been used but may or may not be used
currently "under the high water mark (HWM) for the table".

There is free space.  This one is easy.

There is the amount of space YOUR data takes (versus the amount
of space the database needs to hold it).

I like to use dbms_space (see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
for a good example of how to use that) to find out:

o how much space is allocated to a segment
o how much space it is actually using under the HWM
o how many blocks it has on the freelists (they may or may not
be empty -- the only thing we know for sure is their pctused
allows them to be on the freelist)
o how many blocks have been allocated but never used.

Thats a really good start.  Combine that with some data from
dba_free_space and you'll have a good collection of stats over
time.
July 11, 2000 Nancy -- Thanks for the question regarding "Date Arithmetic", version 7.3.2.2
You Asked
Just wanted to know the best way of subtracting 100
years from a date field.  We have some records that have the
year
as 2098, 2099 which should be 1998, 1999.   We need the month
and
day to remain the same.

If it is necessary to calculate the number of days in one
hundred
is there a formula to handle leap years accurately.
and we said...
I would do an update like I have below:

ops$tkyte@8i> create table t ( date_field date );

Table created.

ops$tkyte@8i>
ops$tkyte@8i> insert into t values
  2  ( sysdate );
ops$tkyte@8i> insert into t values
  2  ( add_months(sysdate,98*12) );
ops$tkyte@8i> insert into t values
  2  ( to_date('31-dec-2049', 'dd-mon-yyyy' ));
ops$tkyte@8i> insert into t values
  2  ( to_date('01-jan-2050', 'dd-mon-yyyy' ));
ops$tkyte@8i> insert into t values
  2  ( to_date('30-dec-1949', 'dd-mon-yyyy' ));
ops$tkyte@8i> insert into t values
  2  ( to_date('02-jan-1950', 'dd-mon-yyyy' ));

ops$tkyte@8i> select to_char( date_field, 'dd-mon-yyyy' )
  2    from t;

TO_CHAR(DAT
-----------
11-jul-2000
11-jul-2098
31-dec-2049
01-jan-2050
30-dec-1949
02-jan-1950

6 rows selected.

ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> update T
  2     set date_field =
  3    to_date( '19'||to_char(date_field,'yymmdd'), 'yyyymmdd' )
  4   where date_field > to_date( '2030', 'YYYY' );

3 rows updated.

ops$tkyte@8i>
ops$tkyte@8i> select to_char( date_field, 'dd-mon-yyyy' )
  2    from t;

TO_CHAR(DAT
-----------
11-jul-2000
11-jul-1998
31-dec-1949
01-jan-1950
30-dec-1949
02-jan-1950

6 rows selected.

That gets all dates after 2030 and makes their century be 19...
July 12, 2000 anil -- Thanks for the question regarding "How to estimate size for an Index Organised table", version 8i
You Asked
Hello,

I am looking for the steps to follow to estimate the Index
organised table. Can you please tell me how to use Oracle
Estimation formulae in respect with index organised table.

Thank you

Anil
and we said...
There are no really good sizing formula's for This.  The last
published guestimate was in 7.3.  Since then, they've stopped
publishing a "method" for sizing these objects.  Too many
variables, they are found to be widely innaccurate in practice.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:302216525000
for my guidelines on doing this.
July 12, 2000 -- Thanks for the question regarding "calcule space required for tables and indexes", version 8.1.6
You Asked
how to calculate space required for tables and indexes ?
and we said...
The only accurate method of doing this in my experience is to
load a representative percentage of the data into sample tables
and analyze them to find their actual space usage.

I recommend loading representative records somewhere in the
range of 0.1% (for really large tables -- 100,000,000 records or
more), 1% for medium sized tables or 10% for small tables.
Then, analyze the table and see how many blocks it took to
contain that much data, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
for a guide to doing that.  Then multiply by the
appropriate factor.  This works for pretty much any object you
would want to create.

There are formula, that may or may not be accurate depending on
your circumstances, that can give you a "ball park" estimate
that may be wildly inaccurate.  The reasons they may be
inaccurate are

o different block sizes will give you different results as rows
are chained on smaller blocks and so on.

o you size numbers correctly as numbers are stored in a packed
format (not binary) in Oracle and hence the number 999 takes
more room then the number 1,000,000,000 to store.

o block overhead varies according to your storage clause and
other table level parameters.

o there are lots of different table types -- heap, index
organized, hash, hash cluster, clustered and so on.  Each has
their own nuances that the "formula" don't take into
consideration.

They have stopped publishing these formula in the docs in the
8.x timeframe.  You can refer to the 7.3 docs
http://technet.oracle.com/doc/server73x/SAD73/apA.htm#toc201
but remember to adjust for differences...
July 12, 2000 murthy -- Thanks for the question regarding "Delete duplicate rows, committing in a trigger.", version oracle 8.0
You Asked
1) Can we disable index while creating a primary key when new
table is created

2) how to delete duplicate rows from given table by using ROWNUM

3)why commit cannot be given in Trigger's in oracle 8 and why it
is not stored in compiled form
and we said...
1) what do you mean by #1?  elaborate on what you mean by that
please, it is not clear.

2) you cannot use rownum to delete duplicate rows.  You can use
rowid to help you.  say you have a table T with structure:

ask_tom@OSI1.WORLD> create table t
  2  ( x int, y int, z int );

Table created.

The datatype is not relevant, the columns could be of any
type

ask_tom@OSI1.WORLD> insert into t values
  2  (1,1,1);
ask_tom@OSI1.WORLD> insert into t values
  2  (1,1,1);
ask_tom@OSI1.WORLD> insert into t values
  2  (1,1,1);
ask_tom@OSI1.WORLD> insert into t values
  2  (1,2,1);

ask_tom@OSI1.WORLD> delete from T
  2   where rowid <> ( select max(rowid) from T t2
  3                     where t.x = t2.x
  4                       and t.y = t2.y
  5                       and t.z = t2.z );

2 rows deleted.

ask_tom@OSI1.WORLD> select * from t;

         X          Y          Z
---------- ---------- ----------
         1          1          1
         1          2          1

will remove all but 1 row for duplicate X,Y,Z entries.

3) Triggers are stored in compiled form.  That is erroneous.  In
7.2 and before, they were not stored permanently in a compiled
form but rather were compiled the first time they were executed.
 That was years ago.....

Committing in a trigger is not allowed because a trigger is part
of a larger transaction.  Say you could have a ROW trigger that
could commit and you execute something like:

   update  T set x = x+1;

Now, that update will update every single row (or not) as an
atomic operation.  If we allowed you to commit in the row
trigger -- then you might commit HALF of the update, get an
error on the other HALF and end up with a HALF updated table.
That just goes against the entire concept of an atomic
transaction.  Identical cases arise for all 4 trigger types --
where the transactional consistency of the database would be
totally destroyed if you committed.

In Oracle8i, release 8.1, we implemented a new feature called
autonomous transactions.  These in effect allow you to commit in
a trigger if you desire but what you are committing is a "child"
sub-transaction -- not the current transaction.  See
http://osi.oracle.com/~tkyte/autonomous/index.html
for more information on that new feature.
Review & Followup
Rating: 5
October 02, 2003
Reviewer: Jayson from Canada
Great help.  The answer to question #2 was exactly what I needed to delete some
duplicate rows at work. Thanks.

July 12, 2000 Radhakrishnan -- Thanks for the question regarding "1023 character barrier in UTL_FILE.PUT_LINE", version 8.0.4
You Asked
Is there any method to break the 1023 character barrier in
UTL_FILE.PUT_LINE in Oracle 8.0.4
and we said...
Only to upgrade to 8.0.5 where the fopen routine has an
additional parameter MAX_LINESIZE which can be set upto 32k in
size.

Prior to 8.0.5, the limit is very much fixed in size.
July 12, 2000 Ravinder -- Thanks for the question regarding "Oracle Enterprise Manager - SQL Text -- how to get it myself in sqlplus", version 8.1.6.1.2
You Asked
Hi Tom,

I have seen something which is very much surprising and worrying
as well.

I am doing a heavy load and monitoring it through Instance
Manager from OEM Console.

Surprise
is that the SQL shown by OEM for the particular session is
different than what I am seeing at SQL*Plus. I am using the
follwoing Command for getting the SQL*Text
select t.sql_text SQL
from   v$sqltext t,
       v$session s,
       v$process p
where  p.addr=s.paddr
and    t.hash_value=s.sql_hash_value
and    s.sid = &sid
order by t.piece

I dont think it has something wrong or it can give some
different result.
and we said...
You are joining by hash_value but thats not correct.  You should
join by address.  You do not need to involve v$process at all.
Here is a script I use to show me whos logged in and what they
are doing:

column status format a10
set feedback off
set serveroutput on

select username, sid, serial#, process, status
from v$session
where username is not null
/

column username format a20
column sql_text format a55 word_wrapped

set serveroutput on size 1000000
declare
    x number;
begin
    for x in
    ( select username||'('||sid||','||serial#||
                ') ospid = ' ||  process ||
                ' program = ' || program username,
             to_char(LOGON_TIME,' Day HH24:MI') logon_time,
             to_char(sysdate,' Day HH24:MI') current_time,
             sql_address, LAST_CALL_ET
        from v$session
       where status = 'ACTIVE'
         and rawtohex(sql_address) <> '00'
         and username is not null order by last_call_et )
    loop
        for y in ( select max(decode(piece,0,sql_text,null)) ||
                          max(decode(piece,1,sql_text,null)) ||
                          max(decode(piece,2,sql_text,null)) ||
                          max(decode(piece,3,sql_text,null))
                               sql_text
                     from v$sqltext_with_newlines
                    where address = x.sql_address
                      and piece < 4)
        loop
            if ( y.sql_text not like '%listener.get_cmd%' and
                 y.sql_text not like '%RAWTOHEX(SQL_ADDRESS)%')
            then
                dbms_output.put_line( '--------------------' );
                dbms_output.put_line( x.username );
                dbms_output.put_line( x.logon_time || ' ' ||
                                      x.current_time||
                                      ' last et = ' ||
                                      x.LAST_CALL_ET);
                dbms_output.put_line(
                          substr( y.sql_text, 1, 250 ) );
            end if;
        end loop;
    end loop;
end;
/

column username format a15 word_wrapped
column module format a15 word_wrapped
column action format a15 word_wrapped
column client_info format a30 word_wrapped

select username||'('||sid||','||serial#||')' username,
       module,
       action,
       client_info
from v$session
where module||action||client_info is not null;
July 12, 2000 David -- Thanks for the question regarding "Problem using ODMA (Oracle Migratation Assistant) for 8.0.5 to 8.1.6", version 8.1.6
You Asked
I have 8.1.6 installed running AIX 4.3.2.  On the same UNIX box,
i have 8.0.5, 8.0.6, and 8.1.6.  I want to run the odma from
8.1.6 ORACLE_HOME to convert my 8.0.5 to 8.1.6.  I login to UNIX
under my 8.0.5 settings.  I go to the 8.1.6 bin dir and run
odma.  It finds my 8.0.5 to convert, but keeps dying during the
migration either because it cannot startup Oracle in restricted
mode or with control file errors.  I guess I am confused to
which oracle settings for ORACLE_HOME ect I should be using and
why it keeps coming up if errors with the shutdown/startup/
control files.  I have an 8.0.6 listner running for all my 8.0.5
and 8.0.6 sids.  I have tried different combos on UNIX settings,
but I hit the same problems.  This is my first time trying the
mig tool, in the past I have always just started from scratch
and exported/imported into a new DB, but I would like to get
this to work.

Any ideas on the exact method and under which settings to
convert the 8.0.5 to 8.1.6?

thank you,

Dave
and we said...
You need to log in with your 8.1.6 Oracle_home setup -- not the
8.0.5.

It should be noted -- ODMA is mandatory for migrating a v7.x
database to 8.1.  For an 8.0.5/8.0.6 instance direct migration
can be done, no ODMA need be involved if you so choose.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76957/migupgra.htm#13277
for this fact and follow the link in there for the directions to
upgrade.

You might want to review the entire:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76957/toc.htm
Migration Guide to get more info.
July 12, 2000 Catalin -- Thanks for the question regarding "ActiveX", version 6.0.5.0.2
You Asked
Hello again,
I have two problems:

1.I want to insert an ActiveX object and open it in one form.
For example I want to create a Wang object (Windows) for scan
some document.
I create a application with this object in Visual Fox and for
open this object I write
this code : Wang.openscan (objectName.Property)
2. I want to insert an image into a table and I don't know how

Please help me.

Thank you for your help
Catalin Dinu
and we said...
See chapter 6 or 7 titled "Taking Advantage of Open
Architecture" in Oracle Developer Guidelines for Building
Applications

which you can get from
http://technet.oracle.com/docs/products/forms/doc_index.htm
this is a cut and paste from the online forms help:

<quote>
Form Builder provides support for ActiveX controls.  ActiveX
controls are reusable components that can be embedded in your
Form Builder Application.  Form Builder acts as an ActiveX
control container.

The ActiveX Control item type creates a container for your
ActiveX control.  An ActiveX control is not a separate
application, but a server that plugs into an ActiveX container.
It is recommended that you use ActiveX controls in blocks with
the Single Record property set to Yes.  The Single Record
property is not applicable to multiple record blocks.  It is
advised that you set the Single Record property to Yes, because
single records are immediately initialized when Forms Runtime
starts up.  For multiple records, each record is not initialized
until you navigate to the record.  Without initialization, the
ActiveX control item is empty, giving the impression that no
ActiveX control is available.

Each ActiveX control exposes a set of properties, methods, and
events.  Properties define the ActiveX control's physical and
logical attributes, methods define actions that the ActiveX
control can perform, and  events denote some change in status in
the ActiveX control.  A client application manipulates an
ActiveX control by writing values to and obtaining values from
its properties, invoking methods that are used to get and set
properties, and intercepting and acting on events.

ActiveX controls are a special type of dynamic library.  A
single ActiveX file that is distributed with the .OCX extension
can contain more than one class of ActiveX objects.
ActiveX controls are not a variety of VBX.  VBX controls
function strictly in 16-bit applications; they do not function
in a 32-bit environment.  ActiveX controls can provide you with
functionality similar to VBX controls in a 32-bit environment.
A significant amount of effort is required to develop your own
ActiveX controls or OLE servers, therefore it is recommended
that you use ActiveX controls and OLE servers developed and
distributed by third party vendors.  Documentation that
accompanies the ActiveX controls and OLE servers contain
information on properties, methods, and events.
</quote>

As for how to insert an image inot a table, what you do is
create a block on a table with a LONG RAW column.  You would use
the READ_IMAGE_FILE() builtin to load the image into the block
and when you "save" -- it'll be saved into the database.
Review & Followup
Rating: 2
ActiveX Technology doenot care from Oracle July 19, 2001
Reviewer: Thillina from COL Sri Lanka
I think your answer only giving an easy clue to findout it from Forms Help. But
in this forum people are seeking for an answer which is from expert. Not a
answer like a kiddies answer like "findout it from Oracle Help". I think you
didn't consider about his question that much. It's very sad your application
intergration with windows components.

July 12, 2000 Sankalp -- Thanks for the question regarding "FORMS ON WEB", version 2.1
You Asked
Dear Tom,
a)What all support I need to deploy my form on web.
Please send me step-by-step approach.

b)How can I implement SMS (Short mesaging system) through
forms.I need to send a mesage to customers mobile from my form.

c)How can I access a web site (eg www.hotmail.com) from my form

d)Is there any site which gives good tipe on developer/2000.
This is apart from U.

Thanks in advance
SANKALP
and we said...
a) Basically, you will get the forms server (see
http://www.oracle.com/tools/forms/index.html
for more info).  You would get it, install it, configure it and
you are done.

b) I don't know.  I'm not familar with that particular protocol.
 Forms has tools (ora_ffi for example) to call any  DLL, it has
OCX/ActiveX integration and so on.  Lots of ways to do it -- I
just don't know how you talk to SMS.

c) If you would like the text of the page, there is a builtin in
the database called UTL_HTTP.  If you just want to display the
page, the HOST builtin will work great as well.  Additionally,
you can get a web "ocx" control as well.

d)
http://technet.oracle.com/
is a good place for that.
Review & Followup
Rating: 2
SMS September 08, 2002
Reviewer: Abdel Ghani Al Masri from middle east -Jordan
-to send sms, you should buy messages from a telecommunication company, or there
is another way which is to buy an activex from a company which have some deal
with telecommunication companies in the world, for example you can go to
www.simplewire.com to get an activex and then buying messages from them, you
should buy, it is not free

July 12, 2000 Charles -- Thanks for the question regarding "Oracle on other platforms", version 8.0.5
You Asked
Hi Tom,
I currently run oracle 8.0.5 on UNIX 10.20.  What other
platforms does Oracle support NT/LINUX?  Where can I get
information on Oracle for other platforms besides UNIX.
We are trying to reduce the cost on server's so I have the task
of looking into this.  We are starting to create a more web
based server with ASP (Active Service Pages).  Alot of databases
are being created and I would like to have a dedicated server
just for these.  Can you point me in the right direction.

Thanks
Chuck
and we said...
Well, Oracle runs on just about any platform you want -- NT yes,
Windows 2000 yes, Linux (which is really just yet another Unix)
yes, Aix, HP/UX, OS/390, and so on.

Pretty much any information you read about Oracle applies to all
platforms -- any platform.
Review & Followup
Rating: 3
In the installation 8.1.6 a cinder screen... September 18, 2001
Reviewer: marcos from BRAZIL
Hi tom,
I do not install the Oracle Enterprise Edition 8.1.6 for linux Intel.
My system operation is Rad Hat 6.0 and kernel 2.2.17 and variables environment
as following:
ORACLE_BASE=/disk2/oracle8/m01/app/oracle
ORACLE_HOME=$ORACLE_BASE/product/8.1.6
ORACLE_SID=ora8
ORACLE_TERM=vt100

and
umask is set as 022

When I run runInstaller is returned a cinder screen and  nothing anymore... I do
not know to do, except CTRL-C.
Thanks.

July 12, 2000 -- Thanks for the question regarding "How to find the shadow processes in Unix?", version 8.1.6
You Asked
Solaris 2.6
Oracle 8.1.6

I have a Net 8 connection from a PC program to an Oracle
instance.
Is   process 4742 in
oracle  4742     1  0 10:40:59 ?        1:34 oracletestdb01
(LOCAL=NO)

the shadow process ?

If not, how do we identifiy shadow processes from Unix ?

ps -ef|grep oracle
  oracle  4729     1  0 10:36:13 ?        0:00 ora_pmon_testdb01
  oracle  5097  4707  0 14:17:45 pts/1    0:00 -ksh
  oracle   894     1  0   Jul 06 ?        0:01
/u01/oracle/product/8.1.6/bin/tns
lsnr listener816 -inherit
  oracle  4737     1  0 10:36:16 ?        0:01 ora_smon_testdb01
  oracle  4739     1  0 10:36:17 ?        0:00 ora_reco_testdb01
  oracle  4735     1  0 10:36:16 ?        0:05 ora_ckpt_testdb01
  oracle  4742     1  0 10:40:59 ?        1:34 oracletestdb01
(LOCAL=NO)
  oracle  4707  4705  0 10:31:14 pts/1    0:01 -ksh
  oracle  4731     1  0 10:36:15 ?        0:01 ora_dbw0_testdb01
  oracle  4733     1  0 10:36:16 ?        0:01 ora_lgwr_testdb01

Thanks.
and we said...
Yes that is *a* shadow (dedicate server) process.  If you want
to find your shadow process:

ops$tkyte@8i> select spid from v$session, v$process where
addr=paddr and audsid=userenv('sessionid');

SPID
---------
14567
ops$tkyte@8i> !ps 14567
   PID TT       S  TIME COMMAND
 14567 ?        S  0:01 oracleora8i
(DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq)))

You can use that to find the dedicated server for a given user
as well:

ops$tkyte@8i> select spid from v$session, v$process where addr =
paddr and v$session.username = 'SCOTT';

SPID
---------
14599

ops$tkyte@8i> !ps 14599
   PID TT       S  TIME COMMAND
 14599 ?        S  0:00 oracleora8i (LOCAL=NO)

ops$tkyte@8i>

thats the shadow process for the user SCOTT.
July 12, 2000 Richard -- Thanks for the question regarding "Can Sqlloader load data where the fieldnames are mentioned in the first line?", version Oracle 8.1.6i/NT or Linux
You Asked
Can I load data with sqlloader which looks like this:

File persons.txt:

number|name|city
12346|richard|zirndorf
54543|jack|austin

It would be great to use a control file which does
not need to have the fieldnames explicitly listed,
because there are a lot of field in some of my tables.

Thanks for your help
Richard
and we said...
SQLLDR cannot do that directly, however, with a very small shell
script on linux (and if you get "head" for NT, part of the
resource toolkit -- this'll work in a similar fashion on NT) we
can make it work.  Consider for example:

#!/bin/csh

if ( "$1" == "" || "$2" == "" || "$3" == "" ) then
    echo usage load user/pass table file
    exit
endif

cat <<EOF > temp.ctl
LOAD DATA
INTO TABLE $2
REPLACE
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
(
EOF
head -1 $3 | sed 's/|/,/g' >> temp.ctl
echo ')' >> temp.ctl

sqlldr userid=$1 data=$3 control=temp.ctl skip=1
=========================================================

When I run that script:

$ load.sh scott/tiger t test.dat

it generated a ctl file like:

$ cat temp.ctl
LOAD DATA
INTO TABLE t
REPLACE
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
(
num,name,city
)

for me and then loaded the data.
July 12, 2000 Sing -- Thanks for the question regarding "inserting data values with puctuation like single quote character ", version 8.0.6
You Asked
Tom,

I have a table xyz that has columns
c1 - number
c2 varchar(8)

How can I insert data values 1 and O'Brian in the
fields c1 and c2 respectively?

Thanks
S
and we said...
The best answer is:  use bind variables.  Bind variable are SO
important.

You would prepare (in whatever language you are using) a
statement like:

  insert into xyz (c1, c2) values ( :c1, :c2 );

You would execute this statement over and over with different
BIND values.  Now, you don't have to compile the statement each
time, we use shared sql, and your program runs inserts maybe 10
times faster.....

If you tell me your language, I can probably find an example of
binding for you.

If you don't like that advice (and believe -- its really
IMPORTANT to use bind variables), you can:

  insert into xyz (c1, c2 ) values ( 1023, 'O''Brian' );

2 quotes = 1 quote in a quoted string.
July 13, 2000 Sankalp -- Thanks for the question regarding "Summary Tables/materialized Views/OCI", version 8i
You Asked
Hi,
A)
In Oracle 8i, there is a new concept introduced - Materialized
Views.
They are also called as Summary Tables.
Well,
Summary tables(ST) are similar to Views except for the fact that
-

# ST occupy space,
# Can be rewritten by the optimizer (step 1)
# Also, they are updatable(like Snapshots)

I think I am right upto here.

my question is : are these ST similar to PLAN_TABLE?
If i drop a ST, and at the same time, the end-user or some
application queries
info from it, what will happen??

Where will it bring the data from , when the object itself is
non-existing??
I hope u followed my question.

B)

Also, can u throw some light on OCI. How is it different from
RPCs and Pro*C.
As far as OCI stuff is concerned, please do not send me URLs. I
have already
checked technet(OTN).
I want in simple language, why, where, how OCI is used.

thanks,
SANKALP.
and we said...
are materialized views like a plan_table.  No, a plan_table is
something we store the results of an explain plan into.  A
materialized view is an "answer" we have pre-stored.  If you
drop a materialized view, while someone is querying it, you will
wait (or timeout).  Its like a real table (it is a real table).
If you drop the table while no one is using it and then someone
goes to use it -- the optimizer will see its not there and will
not rewrite the query to reference it.

OCI is a call level interface.  It has the same functionality as
Pro*C (in Oracle8i release 8.1, pro*c is now for the first time
a layer on top of OCI).  OCI is simply a C api where as pro*c is
a more declarative thing.  OCI is like "jdbc".
July 13, 2000 Shaun -- Thanks for the question regarding "sorting userobjects by dependencies", version 7.3.4.x
You Asked
I am having a devil of a time trying to wrap my mind around how
to create a select statement that will return a list of all
invalid objects ordered by their dependencies.

We have a lot of standalone procedures in our database (I know
they should be put into packages... It's a long story).  I am
trying to create a procedure to recompile all the objects that
have been made INVALID.  I want to compile them in order of
their dependencies.  I created a function that gets a list of
invalid objects and then tries to compile their parents using
recursion.  Unfortunately when I have a large number of invalid
objects I run out of cursors in the database.  Therefore I am
trying to get an ordered list straight away so I don't have to
use recursion.  Is this kind of select statement even possible?

Thanks in advance
Shaun Mallory
and we said...
answer:

dbms_utility.compile_schema()

will do that for you.
July 13, 2000 Arun -- Thanks for the question regarding "Clustering and Partions", version 8i - 8.1.5, 8.1.6
You Asked
Can I partition a clustered table ? and if yes then how , and
which step shild i perform first, clustering or partioning.
and we said...
See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c09parti.htm#430185
"Rules for Partitioning Tables and Indexes "

a cluster cannot be partitioned.
July 13, 2000 -- Thanks for the question regarding "Query of an LOV !", version 8.0
You Asked
Hello sir,

Front end will be forms5.0. The query U sent is not displaying
the related parts. let me try to explain again.

PARTS_MASTER
---------
PARTNO             VARCHAR2(17)
SUPERSEDED_PARTNO   VARCHAR2(17)
QTY                NUMBER(4)

Sample input values are :
PARTNO   SUPERSEDED_PARTNO ....
-----   ------------
ABC      DEF
DEF      GHI
GHI

123      456
456      789
789
.
.
Here partno is primary key.  whenever user selects a partno and
if its qty is not available then an lov containing its related
superseded parts(related parts) should be displayed.  Here the
entries in 2nd column will be present in 1st column.

ex:
--
If a user selects part 'ABC' & its qty is not available then one
lov with values 'DEF','GHI' should be displayed.  If he selects
'DEF' or 'GHI' and think quantity is not available for selected
part then all other related parts should be displayed in lov.

similarly if he selects 456.. then '123','789' should be
displayed. and if he selects '789'  then '123','456' should be
displayed.

I hope it will be done

many thanks..
and we said...
the query is:

ask_tom@OSI1.WORLD> select distinct partno
  2    from parts
  3   where partno <> :x
  4   start with partno in ( select superseded_partno
  5                            from parts
  6                           where partno = :x
  7                           union all
  8                          select partno
  9                            from parts
 10                           where superseded_partno = :x )
 11  connect by prior superseded_partno = partno
 12  /

then.  if you plug ABC into :x (as shown below) the result is
DEF, GHI.  If you plus 456into :x (see below), the result is
123, 789.

ask_tom@OSI1.WORLD> create table parts( partno varchar2(3),
  2                      superseded_partno varchar2(3) );

Table created.

ask_tom@OSI1.WORLD>
ask_tom@OSI1.WORLD> insert into parts values ( 'abc', 'def' );

1 row created.

ask_tom@OSI1.WORLD> insert into parts values ( 'def', 'ghi' );

1 row created.

ask_tom@OSI1.WORLD> insert into parts values ( 'ghi',  NULL );

1 row created.

ask_tom@OSI1.WORLD>
ask_tom@OSI1.WORLD> insert into parts values ( '123', '456' );

1 row created.

ask_tom@OSI1.WORLD> insert into parts values ( '456', '789' );

1 row created.

ask_tom@OSI1.WORLD> insert into parts values ( '789', NULL );

1 row created.

ask_tom@OSI1.WORLD>
ask_tom@OSI1.WORLD> variable x varchar2(3)
ask_tom@OSI1.WORLD>
ask_tom@OSI1.WORLD> exec :x := 'abc'

PL/SQL procedure successfully completed.

ask_tom@OSI1.WORLD>
ask_tom@OSI1.WORLD> select distinct partno
  2    from parts
  3   where partno <> :x
  4   start with partno in ( select superseded_partno
  5                            from parts
  6                           where partno = :x
  7                           union all
  8                          select partno
  9                            from parts
 10                           where superseded_partno = :x )
 11  connect by prior superseded_partno = partno
 12  /

PAR
---
def
ghi

ask_tom@OSI1.WORLD> exec :x := '123'

PL/SQL procedure successfully completed.

ask_tom@OSI1.WORLD> /

PAR
---
456
789

ask_tom@OSI1.WORLD> exec :x := '456'

PL/SQL procedure successfully completed.

ask_tom@OSI1.WORLD> /

PAR
---
123
789
Review & Followup
Rating: 5
May 17, 2002
Reviewer: Helena Markova from Bratislava, Slovakia

July 13, 2000 amit -- Thanks for the question regarding "Single SQL statement to calculate running total.", version 8.0.6.0.0
You Asked
I have a table with 2 columns.
year and expenditure.

with data
Year         Expenditure
1998        20000
1999        25000
2000        30000

I want a sql statement which will give me running total for
expenditure

e.g.

1998        20000
1999        45000
2000        75000

I would appreciate any kind of help.

thanks.
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:305416600201,%7BRUNNING%7D%20and%20%7BTOTAL%7D
...
July 13, 2000 Prashant -- Thanks for the question regarding "Creating a Database for Report Generations", version 8.1.5
You Asked
hi
We have online Web auction site running Oracle8.1.5 db on
WINNT4.0 servicepack5 .We have only database production database
currently.
There is reqt for comprehensive report generation for business
development purpose.
I want to know how should I go about it.

1. Should I create separate DSS database for this purpose on the
machine where production db is running and configure replication
between these two databases?
2.Should I allow report generation on production database
itself.Will that not slow down the performance?
3.Can you suggest any optimal solution for this.

Regards
and we said...
The answer is -- it depends.

o is there excess capacity on the existing database?
o are the structures in that database suitable for querying?
o would the additional workload bog down the machine (i cannot
answer that -- too many variables).

if you opt to not run the reports on the production machine, you

might consider a standby database.  In Oracle8i, the standby
database can be brought up in a read only mode.  What you could
do is from 9-5 (or whatever schedule you like) have the report
database open for reporting.  From 5pm - 9am the next day, its
in recovery mode -- applying whatever logs you have accumulated
from the production machine.  This particular solution

o does not impact the performance of the production machine
whatsoever
o gives you a possible failover site
o is pretty easy to setup and use.
July 13, 2000 sing -- Thanks for the question regarding "v$ table and shell scripts using svrmgrl", version 8.0.6
You Asked
Tom,

My script works fine with all data dictionary tables
like dba_tables.....etc but not with v$ tables.
Can you please help?

Sing

My script:
---------
=====================================================
#!/usr/bin/ksh

ORACLE_SID=orcl1;
export ORACLE_SID;
echo The database you are running is $ORACLE_SID;
svrmgrl -s <<EOF
connect internal
select * from v$archive_dest
exit;
EOF
======================================================
Result:
-------
The database you are running is orcl1

Oracle Server Manager Release 3.0.6.0.0 - Production

(c) Copyright 1999, Oracle Corporation.  All Rights Reserved.

Oracle8 Enterprise Edition Release 8.0.6.0.0 - Production
PL/SQL Release 8.0.6.0.0 - Production

SVRMGR> Connected.
SVRMGR>      2> select * from v
              *
ORA-00942: table or view does not exist
SVRMGR>      2> EOF
*
ORA-00900: invalid SQL statement
SVRMGR>
Server Manager complete.
and we said...
escape the $ (which is SHELL special character) with a \

it should be:

#!/usr/bin/ksh

ORACLE_SID=orcl1;
export ORACLE_SID;
echo The database you are running is $ORACLE_SID;
svrmgrl -s <<EOF
connect internal
select * from v\$archive_dest
exit;
EOF

Else the ksh will look for an environment variable $archive_dest
to substitute in there...
July 14, 2000 Murtaza -- Thanks for the question regarding "Changing Intenal Password -- on windows NT with 7.3", version 7.3.2.2.1
You Asked
Hi Tom,

I have Oracle 7.3.2.2.1 Workgroup Server for Windows NT and
would like to change the internal password. Can you please
kindly assist me.

Thanking you in advance

Regards

Murtaza
and we said...
How To Change The "Connect Internal Password" On A Version 7.3.4
Installation  of Oracle on NT 4.0 Using The Command Line
"ORAPWD73.EXE":

Perform the following steps:

1. In the \orant\database directory:

   Check for a file named "PWDsidname.ORA file,if it exists
rename the file.     This file may be hidden,use the Windows
Explorer View/Option 'show all    files' to see the file.  The
part of the file name 'sidname' is the name    of your sid, so
if sid is orcl then the file name will be PWDORCL.ORA.

2. Change directory to \orant\bin and execute file
"ORAPWD73.EXE".

   Help is given on its usage.  Following is an example command
line:

       ORAPWD73 FILE=D:\ORANT\DATABASE\PWDsidname.ORA
PASSWORD=newpassword

   This will create a PWDsidname.ORA file in the above stated
directory.

3. Change directory to the \orant\database directory and edit
the file "STRTsidname.CMD".  Change the section "-usrpwd
OLDPASSWORD to the NEWPASSWORD given in Step 2.

4. At this point the internal password has been changed and you
should be  able to connect internal with the new password.
July 14, 2000 Tom -- Thanks for the question regarding "running a cron job to pick up all databases and put output to 1 file", version ORacle 7.3.4
You Asked
I have 10 databases running on "Unix AIX 4" I have scripts that
I can run manually which put the output to a file. I would like
to have one entry in the cronjob to be able to run my sql script
on every instance and output to be appended to 1 file.

The other option is to have 10 cron jobs running and have 10
output files, but I am not sure the best way to have each job
pick up its own instance.
and we said...
In your "master" script -- all they need to do is set the
ORACLE_HOME and ORACLE_SID before calling each of the 10
scripts.

For example:

ORACLE_HOME=/d01/oracle
ORACLE_SID=sid1
export ORACLE_HOME
export ORACLE_SID
script1

ORACLE_HOME=/d02/oracle
ORACLE_SID=sid3
export ORACLE_HOME
export ORACLE_SID
script2

(and so on...)

Just use a script to set the correct full environment for each
instance and then run the specific script for that instance.
July 14, 2000 -- Thanks for the question regarding "sequence - how to do an IDENTITY type", version 7.3 personal for w95
You Asked
Hello !

In MSSQL I have table created

 CREATE TABLE Tabela (
        Key                  int IDENTITY,
        Data                 varchar(20) NULL,
        PRIMARY KEY (Key)
 )

I would like to create same table in Oracle, but I don't know
how to put "SEQUENCE" on attribute Key.

Thanks,

Lovro
and we said...
create sequence tablea_key_seq;

create or replace trigger tablea_bifer
before insert on tablea for each row
begin
   select tablea_key_seq.nextval into :new.key from dual;
end;
/

will do it.
July 14, 2000 ananta -- Thanks for the question regarding "Import/Export -- why does it use rollback", version 7.3.4
You Asked
My question is "Why should EXPORT use rollback segments in
oracle ?" and is there any way to improve the slow export other
than using direct path and increasing the roll back segments.

Thanks

Murthy
and we said...
Export uses rollback segments to construct read consistent views
of data as do all queries in Oracle.

Export will not generate rollback but it will utilize it.

Are you getting some specific error?  If so, please repost the
question with more info.

If the error is ORA-1555 see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:376418216351
for some more info.

If you want to increase the performance of your export, direct
is one way - running >1 export in parallel is another.  If you
export schema by schema and run many of them in parallel, it
will go faster (assuming >1 cpu, enough ram, and >1 disk on the
system)
July 14, 2000 Bhaskara -- Thanks for the question regarding "Index Clarificatin. -- why primary key | unique, why not a unique index.", version 8.1.5
You Asked
Hi Tom,

    1. Why does Oracle recommend against using unique indexes to

       enforce uniqueness?
    2. Functionally Is there any differene in using Primary key
       index and User defined Index?

Thanks,
Bhaskara
and we said...
Because a unique index does not imply a UNIQUE constraint or a
primary key.  Some things, like foreign keys, snapshots and so
on demand a unique or primary key constraint.  The
unique/primary key constraint may use a unique (or non-unique)
index to enforce this business rule.  If you just use an Unique
index -- not a constraint -- we have less information and cannot
use that unique index in as many cases.

Functionally -- there is great difference between a primary key
constraint and a unique index.  I cannot reference a unique
index in a foriegn key.  I cannot replicate a table without a
primary key.  I cannot defer a unique index like I could with a
primary key (defer the constraint check until commit time).  And
so on...
July 14, 2000 Somnath -- Thanks for the question regarding "Using joins in connect by??", version 7.3
You Asked
For a report I am creating I need to get the levels from the
colleague table,which contains the user_id and Key_mgr_id ,and
the persons first and last names.
I can use connect by to get the levels but cannot get the first
and last names as with connect by I cannot join the tables.Could
you help me out?
I have given the structures of the tables below

SQL> desc person
 Name                            Null?    Type
 ------------------------------- -------- ----
 PERSON_ID                       NOT NULL NUMBER(6)
 FIRST_NAME                               VARCHAR2(25)
 PERSON_PREFIX                            VARCHAR2(4)
 PERSON_TYPE_ID                           NUMBER(2)
 MIDDLE_INITIAL                           CHAR(1)
 LAST_NAME                                VARCHAR2(25)
 TITLE_DESC                               VARCHAR2(70)
 FAX_NUMBER                               VARCHAR2(20)
 PHONE_NUMBER                             VARCHAR2(20)
 EMAIL                                    VARCHAR2(60)
 FLAG_DELETED                             NUMBER(1)
 USER_CREATE                              VARCHAR2(20)
 DATE_CREATE                              DATE
 USER_MODIFY                              VARCHAR2(20)
 DATE_MODIFY                              DATE
 ADDRESS_ID                               NUMBER(38)
 SALUTATION                               VARCHAR2(10)
 CELL_PHONE_NUMBER                        VARCHAR2(20)

SQL> desc user_info
 Name                            Null?    Type
 ------------------------------- -------- ----
 USER_ID                         NOT NULL VARCHAR2(20)
 PERSON_ID                                NUMBER(6)
 PASSWORD                                 VARCHAR2(20)
SQL> desc colleague;
 Name                            Null?    Type
 ------------------------------- -------- ----
 USER_ID                         NOT NULL VARCHAR2(20)
 SSN                                      VARCHAR2(11)
 DEPT_ID                                  VARCHAR2(6)
 HOME_PHONE                               VARCHAR2(20)
 EMP_STATUS_ID                            VARCHAR2(2)
 START_DT                                 DATE
 COMMENTS                                 VARCHAR2(50)
 ADDRESS_1                                VARCHAR2(30)
 ADDRESS_2                                VARCHAR2(30)
 TERM_DT                                  DATE
 CITY                                     VARCHAR2(30)
 STATE_PROV_CD                            CHAR(2)
 USER_MODIFY                              VARCHAR2(20)
 ZIP                                      VARCHAR2(10)
 DATE_MODIFY                              DATE
 KEY_MGR_ID                               VARCHAR2(20)
 SUPERVISOR_ID                            VARCHAR2(20)
 COUNTRY                                  VARCHAR2(20)
 IMAGE_NAME                               VARCHAR2(20)
and we said...
We can use an inline view to do this.  If I have your tables
right -- here is an example based on the SCOTT.EMP table:

scott@ORA734.WORLD> create table colleague
  2  as
  3  select empno user_id, mgr  key_mgr_id
  4    from emp;

Table created.

scott@ORA734.WORLD>
scott@ORA734.WORLD> create table user_info
  2  as
  3  select empno user_id, empno person_id
  4    from emp;

Table created.

scott@ORA734.WORLD>
scott@ORA734.WORLD> create table person
  2  as
  3  select empno person_id, ename last_name
  4    from emp;

Table created.

scott@ORA734.WORLD>
scott@ORA734.WORLD> column emp_lname format a15
scott@ORA734.WORLD> select lpad( ' ',l*2,' ')|| C.last_name
emp_lname, E.last_name Mgr_Lname, A.*
  2  from ( select colleague.* , level l, rownum r
  3           from colleague
  4          start with key_mgr_id is null
  5        connect by prior user_id = key_mgr_id ) A,
  6       user_info B,
  7       person c,
  8       user_info D,
  9       person E
 10  where a.user_id = b.user_id
 11    and b.person_id = c.person_id
 12    and a.key_mgr_id = d.user_id(+)
 13    and d.person_id = e.person_id(+)
 14  order by r
 15  /

EMP_LNAME       MGR_L    USER_ID KEY_MGR_ID  L   R
--------------- ----- ---------- ---------- -- ---
  KING                      7839             1   1
    JONES       KING        7566       7839  2   2
      SCOTT     JONES       7788       7566  3   3
        ADAMS   SCOTT       7876       7788  4   4
      FORD      JONES       7902       7566  3   5
        SMITH   FORD        7369       7902  4   6
    BLAKE       KING        7698       7839  2   7
      ALLEN     BLAKE       7499       7698  3   8
      WARD      BLAKE       7521       7698  3   9
      MARTIN    BLAKE       7654       7698  3  10
      TURNER    BLAKE       7844       7698  3  11
      JAMES     BLAKE       7900       7698  3  12
    CLARK       KING        7782       7839  2  13
      MILLER    CLARK       7934       7782  3  14

14 rows selected.

scott@ORA734.WORLD>
Review & Followup
Rating: 3
What if the relationship can not be established with a single table December 17, 2002
Reviewer: Subhro from Houston, TX USA
Hi Tom,
   How to handle the following situation...

   Table A
   --------
   id
   assembly

   Table B
   --------
   parent_id
   component

  and the link is A.id=B.parent_id, but connection has to be on aseembly and
component. a component may be an assembly in itself.

how to handle this...

Thanks and Regards...

July 14, 2000 Mike -- Thanks for the question regarding "Cumulative Frequency", version 8.1.6
You Asked
Do you have any examples of how to create a cumulative frequency

in SQL*Plus?  I can calculate the frequency; but I don't know
how to add the frequency to the next row.  This is what I have
so far:

select a.host Host, count(a.host) Count, (count(a.host)/t.total)
* 100 Frequency
from apache_log a, (select count(host) total from apache_log) t
group by a.host, t.total
order by 3 desc

Thanks
Mike
and we said...
Well, since you have 8.1.6 we can use some new analytic
functions to do this.  Consider this example.  I made up an
apache log from the owners in all_objects (just needed lots of
records with a string in it to play with).  Then I queried:

scott@ORA816.US.ORACLE.COM> /*
DOC>drop table apache_log;
DOC>
DOC>create table apache_log
DOC>as
DOC>select owner host from all_objects;
DOC>*/

scott@ORA816.US.ORACLE.COM> select host, my_count,
                round( (cum_count/tot_count)*100, 2 ) cum_freq
  2  from ( SELECT host, count(*) my_count,
  3                sum(count(*)) OVER
  4                    ( ORDER BY host
  5                      ROWS BETWEEN UNBOUNDED PRECEDING
  6                               AND CURRENT ROW) AS cum_count,
  7                sum(count(*)) over
  8                     ( order by host
  9                       rows between unbounded preceding
 10                                and unbounded following)
                   as tot_count
 11           FROM apache_log
 12          group by host );

HOST                             MY_COUNT   CUM_FREQ
------------------------------ ---------- ----------
PUBLIC                               9209      50.79
SCOTT                                   6      50.83
SYS                                  8914      99.99
SYSTEM                                  1        100

scott@ORA816.US.ORACLE.COM>

qed ;)

see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76989/functio2.htm#80856
and search for "analytic" functions for more info.
Review & Followup
Rating: 5
hi September 03, 2003
Reviewer: A reader
Tom,

In the order by clause in the analytic expressions , am I correct in saying that
for first_value(relative_fno) block_id is not necessary and for
first_value(block_id) relative_fno need not be there.

i.e. the query would look like

set verify off
define TNAME=&1
define CHUNKS=&2

select a.grp,
       dbms_rowid.rowid_create( 1, b.data_object_id, a.lo_fno, a.lo_block, 0 )
  min_rid,
       dbms_rowid.rowid_create( 1, b.data_object_id, a.hi_fno, a.hi_block, 10000
) max_rid
  from (
          select distinct grp,
                 first_value(relative_fno) over
                                              (partition by grp order by
relative_fno
                                                 rows between unbounded
preceding and unbounded following) lo_fno,
                 first_value(block_id) over
                                              (partition by grp order by
block_id
                                                 rows between unbounded
preceding and unbounded following) lo_block,
                 last_value(relative_fno) over
                                              (partition by grp order by
relative_fno
                                                 rows between unbounded
preceding and unbounded following) hi_fno,
                 last_value(block_id+blocks-1) over
                                              (partition by grp order by
block_id
                                                 rows between unbounded
preceding and unbounded following) hi_block,
                 sum(blocks) over (partition by grp) sum_blocks
          from (
                  select relative_fno,
                         block_id,
                         blocks,
                         trunc((sum(blocks) over (order by relative_fno,
block_id)-0.01) / (sum(blocks) over ()/&CHUNKS)) grp
                  from dba_extents
                  where segment_name = upper('&TNAME')
                    and owner = user
                  order by block_id
               )
       )a,
       (
          select data_object_id
           from user_objects
            where object_name = upper('&TNAME')
       )b
/

thanks
amit

July 14, 2000 Marvin -- Thanks for the question regarding "Converting CLOB to varchar2", version 8.1.5
You Asked
How do you convert a clob to a varchar2?

Marvin Chaffin.
and we said...
select dbms_lob.substr( clob_column, 4000, 1 ) from T;

is one very simple way.  You can write plsql and use
dbms_lob.read as well.
July 14, 2000 Reji -- Thanks for the question regarding "JDBC Autocommit ", version 8.1.6
You Asked
Tom:
    I have a JDBC application and I set the autocommit to false
    and doing lot of inserts and do a commit. Is this feature
    guarantees that if I do a rollback after a very large number
    of inserts will rollback all my inserts.  Or what are the
    other parameters ( like size of redolog file etc..) involved
    in this decision?

    TIA
    Reji
and we said...
Turning autocommit off ( a silly design "feature" of the jdbc
standard -- having autocommit on, sorts of removes the
"transaction" from the database) will ensure that all work you
perform up until you commit is able to be rolled back if you
rollback.

Redolog sizing is important for performance but will not hinder
you in this respect.

Rollback segment sizing is perhaps more important.  You need to
ensure they are large enough to hold your rollback information.
July 14, 2000 Wayne -- Thanks for the question regarding "Passing A Ref Cursor OR VARRAY into PL/SQL block", version 8.1.5
You Asked
Tom,

I have an object in a java program which I need to save in the
database
This object contains info that will be put in the main row of
this item,
plus it can contain one or more subelements which can also
contain sub
elements.  I would like to be able to pass all this info in at
once
and process within a stored procedure.  Is this possible?

thanks,

wayne
and we said...
Yes it is.  You would use an Oracle Object Type to accomplish
this.  You would probably want to use JPublisher to create the
mapping for you.

See
http://technet.oracle.com/doc/java.815/a64685/oraext5.htm#1039456
for more info/examples.


Subject | Article | Last Updated (East coast time)
Space usage of tables | article only | Jul 15, 2000 08:22 am
DataBase Copying | article only | Jul 15, 2000 08:28 am
Is select empno, ename, mgrno, ... from emp degrade performance than select * from emp; | article only | Jul 15, 2000 08:32 am
shared memory -- configuring on solaris for v7.3 database. | article only | Jul 15, 2000 08:38 am
SqlPlus Questions -- how many triggers can a table have | article only | Jul 16, 2000 08:54 am
Can I have Oracle 8 with Parallel Server and Oracle Apps Server on the same servers | article only | Jul 16, 2000 09:00 am
basic replication | article only | Jul 17, 2000 07:02 am
datatype conversion --- dbms_output and a LONG column | article only | Jul 17, 2000 07:07 am
maintain a session -- in the web. | article only | Jul 17, 2000 07:13 am
Table Definition | article only | Jul 17, 2000 07:20 am
SQL EXECUTE IMMEDIATE -- pro*c | article only | Jul 17, 2000 03:50 pm
Replication from SQL Server | article only | Jul 17, 2000 04:06 pm
We are migrating from Oracle 7.3.3 to Oracle 8i | article only | Jul 17, 2000 08:50 pm
How can I find Max sessions | article only | Jul 17, 2000 08:51 pm
Qn on disabling or hiding a record in d2k for multirecords | article only | Jul 19, 2000 07:46 am
Reports queing | article only | Jul 19, 2000 08:07 am
Sending Mail -- from reports. | article only | Jul 19, 2000 08:11 am
Shifting Of Schema from one tablespace to another | article only | Jul 19, 2000 08:14 am
Modifying data within function | article only | Jul 19, 2000 09:12 am
Committing/multitable form in multiuser environment. | article only | Jul 19, 2000 09:21 am
when all_tab_columns and user_tab_columns get updated? | article only | Jul 19, 2000 09:58 am
Create table with date appended | article only | Jul 19, 2000 10:30 am
Standby Database | article only | Jul 19, 2000 10:34 am
about a strange query | article only | Jul 19, 2000 11:00 am
Tuning the Query | article only | Jul 19, 2000 12:19 pm
Tuning Query | article only | Jul 19, 2000 12:23 pm
Space Estimation For Schema Objects | article only | Jul 19, 2000 12:29 pm
using uploaded images in dynamically generated pages | article only | Jul 19, 2000 12:42 pm
Sql Statement for Counting between 1/2 hr period | article only | Jul 19, 2000 01:01 pm
Chinese capabilities in Oracle8i | article only | Jul 19, 2000 04:28 pm
Using database link or new connect | article only | Jul 20, 2000 09:31 am
Concatenated Index | article only | Jul 20, 2000 10:20 am
Intranet development -- what tools does Oracle have | article only | Jul 20, 2000 03:14 pm
Default system accounts and passwords on Solaris? | article only | Jul 20, 2000 03:37 pm
Returning resultsets from functions without defining a table type? | article only | Jul 20, 2000 03:40 pm
Oracle 8.1.6 or Oracle 8.0.6: when migrating from earlier versions | article only | Jul 20, 2000 09:06 pm
Can I simulate OPS using a single server? | article only | Jul 21, 2000 07:31 am
Executing a Oracle stored procedure in MS SQLServer 7.0 | article only | Jul 21, 2000 07:47 am
Using a Recordset in a Loop Statement | article only | Jul 21, 2000 08:20 am
Long datatype is SQL*Plus -- how to move or copy a LONG field. | article only | Jul 21, 2000 08:23 am
Database Roles | article only | Jul 21, 2000 09:24 am
Date checking in DB Constraints | article only | Jul 21, 2000 09:26 am
Tablespace Coalesce | article only | Jul 21, 2000 09:40 am
Date format | article only | Jul 21, 2000 11:55 am
Custom datatypes | article only | Jul 21, 2000 02:04 pm
row(s) 1 - 45 of 45
July 15, 2000 Yong -- Thanks for the question regarding "Space usage of tables", version 8i
You Asked
Hi, Tom,

Recently on an Oracle mailing list, another person and I
exchanged some messages on calculating space usage of a table.
My suggestion is the same as in your article published in the
latest issue of Oracle magazine. But I need your help to answer
some other questions he has. (My answer to his last question is
No) Any comment is appreciated.

Yong Huang

Surya Rao wrote:

I am trying to get the actual usage for some large tables. I
tried two approaches.

Approach-1
==========
select count(distinct(substr(rowid,1,8))) col1 from
xle_instrument;

col1 * db_block_size (2048) = 38215680 bytes

Approach-2
==========
select sum(bytes) from dba_extents where
segment_name='XLE_INSTRUMENT'
and segment_type='TABLE'

gives -->  49756160

Almost a 22% discrepancy. Any ideas why?????

Am I right that the 22% is ABOVE the HWM?????

Surya

Yong Huang wrote:

analyze table mytab compute statistics;

select num_rows * avg_row_len from user_tables where table_name
= 'MYTAB';

This gives you the *actual* usage of the table. Your suggested
approaches give you the allocated space, always greater than or
equal to the actual usage.

I also suspect that your first approach, although ingenious, is
Oracle version-dependent because of different construct of
rowid's.

Yong Huang
yong321@yahoo.com

Surya wrote:

 Does the above include block and segment headers?

 The above is close to my approach#1 when I tried out both.

Surya
and we said...
Approach 1 above is somewhat flawed.  Its from v7 and it is
trying to count blocks that are being used by looking at the
rowid and counting distinct blocks.  The problems with this
approach is:

1) a row can migrate.  My rowid might say I'm on block 5 but
really just a pointer to me is on block 5.  I'm really on block
55 (and there might be NO rowid with block 55 in it).  So, this
could be off by alot.  These blocks would be uncounted.

2) a row can chain blocks.  There is nothing saying a row is
contained entirely on one block.  A row might be on 2, 3, or
hundreds (longs and long raws) of blocks.  These other blocks
might not have any "head row pieces" on them meaning there will
be no rowids that have this block in it.  These blocks would go
uncounted.

So, with approach 1, you can get the MINIMUM number of blocks
that might contain data -- but you will never get the MAXIMUM
number of blocks that might contain data.

Approach 2 shows how much space is physically ALLOCATED to the
table.  This is used space + free space.  The 22% difference may
or may not be above the HWM, there is not enough information to
know truely as we simply counted blocks that have HEAD row
pieces on them -- not all blocks that either currently contain
data or have contained some data at some point in time.

The analyze table will tell you exactly how many blocks are
above and below the HWM.

The select num_rows*avg_row_len will tell you how much space
YOUR data consumes (minus block overhead, pctfree and so on --
its telling you how much space your raw data takes.  Subtract
that from space used gives you how much overhead we have
introduced for block management, pctfree and so on).

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
for yet another way to get all of this good information without
much overhead (no analyze, no full scans and so on)
July 15, 2000 Krishna -- Thanks for the question regarding "DataBase Copying", version 7.3.4
You Asked
Hi,

My Question is, I have a a datbase of around 15GB in size.
I want to create one more test database with the same
table structures as the master database and with some
selected data from the master database.the issue is,
i only have some limited privileges
on the master database to do this.i am not supposed to load the
server on which the master database is reciding.

expecting a reply at the earliest.

Bye
and we said...
You'll need enough privs to create a database (and thats alot)
or have someone do it for you.

Then, you might use exp ... rows=n owner=SOME_SCHEMA to get a
structural extract (DDL, triggers, procedures) of a schema and
import that into your test database.

Then, you can use the sqlplus copy command to extract the data
you like (subsets if you want.  the copy command can include a
where clause).  See
http://osi.oracle.com/~tkyte/Misc/MoveLongs.html
for a quick example of the sqlplus copy command.  The sqlplus
guide has more info.
July 15, 2000 Ravi -- Thanks for the question regarding "Is select empno, ename, mgrno, ... from emp degrade performance than select * from emp;", version 8.0.4.4
You Asked
Which of the following is good from the performance point.

1) select * from emp

2) select empno, ename, sal, mgrno, ..... <all_columns> from
emp;

Why?

With warm regards
Ravi
and we said...
I've never noticed a difference.  The select * from emp might
take marginally longer to PARSE then with explicit columns but
it will be so minute as to not be noticed.

I ran a couple of tests on some tables.  It was basically a tie
over time.  The select * would win one time and the select c1,
c2, c3, would win the next.  They are fairly equivalent.

Now, that aside, select * can be dangerous.  You cannot depend
on the order of the columns over time (so your bind list could
change on you).  You cannot depend on the number of columns
(someone might add one and you don't have a bind variable to
fetch into).  "select * from t1, t2" can be really bad if
someone adds a like named column to t2 that already exists in t1
(ambigous column names). And so on.

I would avoid the "select *" if you can unless you are using
purely dynamic sql (in which case you don't care about the
issues above as you are discovering at runtime the number, name
and type of select'ed columns)
July 15, 2000 razvan -- Thanks for the question regarding "shared memory -- configuring on solaris for v7.3 database.", version 7.3.2
You Asked
hello tom,

can you explain me what is the connection between shared memory,
messages,semaphores and a database in general? i mean i have a
sun with 512m memory, i tried to install oracle 7.3 and give me
an error like this:"unable to install shared memory".How can i
resolv this situation?
i put in /etc/system some entries from sun suport like:
forceload:sys/shmsys
forceload:sys/msgsys
forceload:sys/semsys
but didn t work.
please explain me at least in theoretically way.

please help me.

with respect
razvan
and we said...
See
http://technet.oracle.com/doc/solaris/server.734/A58795_01/env3.htm#index0121
which is chapter 3 of the install guide for Oracle7.3 on
Solaris.  Basically, you must configure the Solaris kernel to
support larger shared memory segments then it does by default.

All of the above is explained in the install guide for Solaris
which is available for 7.3 in its entirety at:
http://technet.oracle.com/doc/solaris/server.734/A58795_01/toc.htm
....
July 16, 2000 Ramakrishnan -- Thanks for the question regarding "SqlPlus Questions -- how many triggers can a table have", version Oracle8i
You Asked
Tell me the Maximum Number of Triggers can be attached to a
table in Oracle8i.
and we said...
There is no limit other then practical limits.  For example:

ops$tkyte@DEV8I.WORLD> create table t ( x int );

Table created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> begin
  2   for i in 1 .. 1000 loop
  3    execute immediate 'create or replace trigger t' || i || '
  4                       before insert on t
  5                       begin null; end;';
  6          end loop;
  7  end;
  8  /

PL/SQL procedure successfully completed.

ops$tkyte@DEV8I.WORLD>

shows that I can successfully create a table with 1,000 triggers
on it.  However

ops$tkyte@DEV8I.WORLD> set timing on
ops$tkyte@DEV8I.WORLD> insert into t values ( 1 );

1 row created.

Elapsed: 00:00:01.03
ops$tkyte@DEV8I.WORLD> /

1 row created.

Elapsed: 00:00:00.37

it now takes some amount of time to execute these 1,000
triggers...

ops$tkyte@DEV8I.WORLD> drop table t;

Table dropped.

Elapsed: 00:00:18.60

and lots of extra time to drop the table due to the enormous
amount of triggers...

ops$tkyte@DEV8I.WORLD> create table t ( x int );

Table created.

Elapsed: 00:00:00.07
ops$tkyte@DEV8I.WORLD> insert into t values ( 1 );

1 row created.

Elapsed: 00:00:00.01
ops$tkyte@DEV8I.WORLD> /

1 row created.

Elapsed: 00:00:00.00
ops$tkyte@DEV8I.WORLD>
As compared to a table without triggers...

So, there are no hard limits -- only practical ones.
July 16, 2000 Basid -- Thanks for the question regarding "Can I have Oracle 8 with Parallel Server and Oracle Apps Server on the same servers", version 8.1.5
You Asked
Dear Tom,
I want to install Oracle 8.1.5 with parallel server option on a
cluster with 2 nodes running windows N.T server 4.0. Can I also
Install Oracle Application Server on the same cluster so that it
also works as a database server and Apps server. If possible
does the application which is to be developed for this
configuration has to be web enabled, since I want all the
programs to be stored on an apps server and clients should
communicate through the apps server to the database.
The clients to be used for this installation are IBM comptible
P.C's with Windows 98 O/S.
Looking forward for your technical help.
Thanks.

Regards
Basid.
and we said...
You can install the app server onto the same machine with the
datbase -- yes.  You need make sure there are sufficient
resources for both.  If you are doing this for availability
(OPS), you might want to install the app server on both machines
as well and keep the configurations in sync (in the event the
machine with the app server fails -- you need an app server
failover machine as well)

If you are using a tool since as D2K -- then your applications
will be web enabled (or client server as you wish)
automatically.  If you use some other method -- then yes, you
typically will have to build them to be "web enabled".
July 17, 2000 Kenneth -- Thanks for the question regarding "basic replication", version 7.3.2
You Asked
Dear Tom ,
Thanks a million for the reply to my query

the query was as follows

If basic replication creates only read only tables( which are
actually views ) .
At the most I will be able to query the replicated database
. since no updates,insert , delete are possible

If my primary database crashes then this replicated is of no use
Cause even an export will actually generate read only tables
which can't be used to create a  production database.

Is there any way in which i can replicate a database where even
small changes ( like changes made to functions etc. ,   new
tables added ) can be incorporated automatically.

Can u throw some light?
Kenneth

You replied

Well, in basic replication -- the data is actually copied --
there are "real" tables out there (with extra columns -- in 7.3
the rowid of the master row at the master site).  The views are
used to "hide" this extra column.  So, in the event of a total
failure -- you can get to these "real" tables if need be in the
event of an emergency.

#####

in the last statment above . HOw will these "real" tables be
created from these views .Do i have to take an export.
even if i do, then i will have views not the actual tables
how will the views map to the "real" tables.
Kindly reply

Kenneth
and we said...
This is for 7.3.  I created a snapshot:

create snapshot test
refresh fast
as
select * from test@test1;

There is nothing else in this schema other then the snapshot and
the database link.  Looking at what gets created:

OBJECT_TYPE   OBJECT_NAME
------------  ------------------------------
DATABASE LINK TEST1.WORLD
INDEX         I_SNAP$_TEST
TABLE         SNAP$_TEST
VIEW          MVIEW$_TEST
VIEW          TEST

So, the VIEW TEST is what you typically use.  Its definition is:

test_1@ORA734.WORLD> select text
  2  from user_views
  3  where view_name = 'TEST';

TEXT
----------------------------------------------------------------
select "EMPNO","ENAME","JOB","MGR","HIREDATE","SAL","COMM","DEPT
NO" from "TEST_1"."SNAP$_TEST" with read only

We can see that this view is based on the real table
"TEST_1"."SNAP$_TEST".  If we look at that table:

test_1@ORA734.WORLD> desc snap$_test
 Name                            Null?    Type
 ------------------------------- -------- ----
 EMPNO                           NOT NULL NUMBER(4)
 ENAME                                    VARCHAR2(10)
 JOB                                      VARCHAR2(9)
 MGR                                      NUMBER(4)
 HIREDATE                                 DATE
 SAL                                      NUMBER(7,2)
 COMM                                     NUMBER(7,2)
 DEPTNO                                   NUMBER(2)
 M_ROW$$                                  VARCHAR2(18)

we can see that is has one extra column and that is the ROWID of
the row from the master site.  This is used for the refresh.  We
see that there is an index on this table and that index is on
the M_ROW$$ table.

So, lets say that our master site "goes away".  We still have
the data (current as of the last refresh) in the table
SNAP$_TEST.  Its just a "regular" table and in the event of this
emergency -- we can use it (its just a table after all).  You'll
never want this to refresh againt (so modify the snapshot
settings to make sure it doesn't).  You would probably want to
copy the data out of here ultimately so you can drop the
snapshot and get back to having just a "real" table instead of a
snapshot.
July 17, 2000 sandeep -- Thanks for the question regarding "datatype conversion --- dbms_output and a LONG column", version 8.0.5
You Asked
how can I convert a long value to varchar2 and get it printed by
using dbms_output.put_line?
and we said...
There are 2 issues here:

1) printing strings > 255 bytes with dbms_output
2) dealing with longs in plsql.

For the first issue see:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:146412348066
for methods of overcoming the 255 byte limit.

For the second issue there are 2 subcases.  If the long is
always 32k or less, PLSQL can directly use them.  You can just
select them out in a cursor for loop or a select ... into (where
the target variable is declared as a LONG in plsql).  If the
longs might be >32, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:55212348054
for an example of how to read a long a piece at a time in
PLSQL.
July 17, 2000 chen -- Thanks for the question regarding "maintain a session -- in the web.", version Oracle 8.1.6
You Asked
Dear sir,

Please tell me how to maintain a web session in pl/sql.How to
create a session id for every login visitor?

Thank you very much!

Best regards

John Chen
and we said...
You'll need something in the middle to maintain a session.  HTTP
by its very nature is stateless - each "page" is a "new session"
to the web server.  You'll need to use something to help that
out if you truely want sessions.

It is my opinion however that the lack of a session is typically
a good thing.  It might be a minor extra bit of work on your
part (usually a very very small bit of work) to maintain the
needed state variables but the extra scaling you can get out of
your server can be incredible.

If you are using OAS, see the docs for information about
"session enabling" your application.  In this mode, a session
will be retained for you on the server and your browser will be
reunited with this session from call to call.  See
http://www.olab.com/doc/books/plsql/pl_trans.htm
for info on this feature.

Other options are to use servlets or some other middle tier
implementation of session.
July 17, 2000 Mohamed -- Thanks for the question regarding "Table Definition", version Oracle8 Enterprise Edition Release 8.0.4.0.0 - Production / SQL*Plus: Release 3.3.4.0.0 - Production
You Asked
Hi Tom,

I have two quetions.

1. How to view the definition ("create table statement") of
tables in a database? Which data dictionary table is used for
this?

2. How to execute a set of SQL statements (esp. create table
statement) in a single text file in SQL Plus?

This is very urgent.
Pl. reply immediately.

thanks and regards,
rafi.
and we said...
The create table statement is not maintained but rather bits and
pieces of it are stored as structured information in the data
dictionary.  The columns and their datatypes for example can be
found in USER_TAB_COLUMNS.  The constraints can be found in
USER_CONSTRAINTS.  The storage parameters in USER_TAB_COLUMNS.

If you want to see a "create table" statement -- you can use the
 EXP/IMP tools.  Lets say I wanted to see the create table
statement for the SCOTT.EMP table:

$ exp userid=scott/tiger tables=emp rows=n

Export: Release 8.1.5.0.0 - Production on Mon Jul 17 07:23:09
2000
(c) Copyright 1999 Oracle Corporation.  All rights reserved.
Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 -
Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production
Export done in US7ASCII character set and US7ASCII NCHAR
character set
Note: table data (rows) will not be exported

About to export specified tables via Conventional Path ...
. . exporting table                            EMP
Export terminated successfully without warnings.

Now, in order to see the table definition -- I have 2 ways.
One is SHOW=Y and the other is INDEXFILE=filename.  Show=Y gives
me the following output:

$ imp userid=scott/tiger full=y show=y

Import: Release 8.1.5.0.0 - Production on Mon Jul 17 07:23:20
2000
(c) Copyright 1999 Oracle Corporation.  All rights reserved.
Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 -
Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

Export file created by EXPORT:V08.01.05 via conventional path
import done in US7ASCII character set and US7ASCII NCHAR
character set
. importing SCOTT's objects into SCOTT
 "CREATE TABLE "EMP" ("EMPNO" NUMBER(4, 0) NOT NULL ENABLE,
"ENAME" VARCHAR2("
 "10), "JOB" VARCHAR2(9), "MGR" NUMBER(4, 0), "HIREDATE" DATE,
"SAL" NUMBER(7"
 ", 2), "COMM" NUMBER(7, 2), "DEPTNO" NUMBER(2, 0))  PCTFREE 10
PCTUSED 40 IN"
 "ITRANS 1 MAXTRANS 255 LOGGING STORAGE(INITIAL 16384)
TABLESPACE "UTILS""
 "GRANT SELECT ON "EMP" TO PUBLIC"
 "CREATE INDEX "EMP_IDX" ON "EMP" ("JOB" , "SAL" )  PCTFREE 10
INITRANS 2 MAX"
 "TRANS 255 STORAGE(INITIAL 524288) TABLESPACE "UTILS" LOGGING"
 "CREATE INDEX "DEPT_IDX" ON "EMP" ("DEPTNO" )  PCTFREE 10
INITRANS 2 MAXTRAN"
 "S 255 STORAGE(INITIAL 524288) TABLESPACE "UTILS" LOGGING"
 "CREATE TRIGGER "SCOTT".after_ins_upd_on_emp"
 "before insert or update"
 "on scott.emp"
 "for each row"
 ""
 "begin"
 "   :new.ename := upper(:new.ename);"
 "end;"
 "ALTER TRIGGER "AFTER_INS_UPD_ON_EMP"  ENABLE"
 "ALTER TABLE "EMP" ENABLE CONSTRAINT "EMP_VALID_JOB""
 "ALTER TABLE "EMP" ENABLE CONSTRAINT "EMP_PK""
 "ALTER TABLE "EMP" ENABLE CONSTRAINT "EMP_NAME_I""
 "ALTER TABLE "EMP" ENABLE CONSTRAINT "EMP_FK_TO_DEPT""
Import terminated successfully without warnings.

As you can see -- I can see all of the DDL I need to execute
to recreate the EMP table exactly.  The problem is however that
I cannot "run" this DDL -- just read it.  If I want DDL to run
-- I can use INDEXFILE=filename:

$ imp userid=scott/tiger full=y indexfile=stdout

Import: Release 8.1.5.0.0 - Production on Mon Jul 17 07:23:43
2000
(c) Copyright 1999 Oracle Corporation.  All rights reserved.
Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 -
Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

Export file created by EXPORT:V08.01.05 via conventional path
import done in US7ASCII character set and US7ASCII NCHAR
character set
REM  CREATE TABLE "SCOTT"."EMP" ("EMPNO" NUMBER(4, 0) NOT NULL
ENABLE,
REM  "ENAME" VARCHAR2(10), "JOB" VARCHAR2(9), "MGR" NUMBER(4,
0),
REM  "HIREDATE" DATE, "SAL" NUMBER(7, 2), "COMM" NUMBER(7, 2),
"DEPTNO"
REM  NUMBER(2, 0)) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
LOGGING
REM  STORAGE(INITIAL 16384) TABLESPACE "UTILS" ;
CONNECT SCOTT;
CREATE INDEX "SCOTT"."EMP_IDX" ON "EMP" ("JOB" , "SAL" ) PCTFREE
10
INITRANS 2 MAXTRANS 255 STORAGE(INITIAL 524288) TABLESPACE
"UTILS" LOGGING ;
CREATE INDEX "SCOTT"."DEPT_IDX" ON "EMP" ("DEPTNO" ) PCTFREE 10
INITRANS 2
MAXTRANS 255 STORAGE(INITIAL 524288) TABLESPACE "UTILS" LOGGING
;
REM  ALTER TABLE "SCOTT"."EMP" ADD CONSTRAINT "EMP_VALID_JOB"
CHECK (job
REM  in ('CLERK','SALESMAN','MANAGER','ANALYST','PRESIDENT'))
ENABLE
REM  NOVALIDATE ;
REM  ALTER TABLE "SCOTT"."EMP" ADD CONSTRAINT "EMP_PK" PRIMARY
KEY
REM  ("EMPNO") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
REM  STORAGE(INITIAL 524288) TABLESPACE "UTILS" ENABLE
NOVALIDATE ;
REM  ALTER TABLE "SCOTT"."EMP" ADD CONSTRAINT "EMP_NAME_I"
UNIQUE
REM  ("ENAME") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
REM  STORAGE(INITIAL 524288) TABLESPACE "UTILS" ENABLE
NOVALIDATE ;
REM  ALTER TABLE "SCOTT"."EMP" ADD CONSTRAINT "EMP_FK_TO_DEPT"
FOREIGN KEY
REM  ("DEPTNO") REFERENCES "DEPT" ("DEPTNO") ENABLE NOVALIDATE ;
REM  ALTER TABLE "SCOTT"."EMP" ENABLE CONSTRAINT "EMP_VALID_JOB"
;
REM  ALTER TABLE "SCOTT"."EMP" ENABLE CONSTRAINT "EMP_PK" ;
REM  ALTER TABLE "SCOTT"."EMP" ENABLE CONSTRAINT "EMP_NAME_I" ;

Import terminated successfully without warnings.
REM  ALTER TABLE "SCOTT"."EMP" ENABLE CONSTRAINT
"EMP_FK_TO_DEPT" ;

that created a script for me where most of the DDL is
commented out but its really easy to remove the REM statements
and have a script that is immediately runnable.  Notice that is
only creates "objects" -- not the trigger as the show=y did.
Actually -- this is OK since if you have the .DMP file from
export -- you can just import that into another schema to get
everything created for you (no need for a sqlplus script -- you
have the dmp file -- its can do it for you).

As for #2, how to execute a set of sql statements -- simply
create a script file that looks like:

create table t1 ( x int );
create table t2 ( x int );
.... (other statements)
create table t3 ( x int );

And then in sqlplus you will:

SQL> @name_of_that_file.sql

and it'll just run for you .
July 17, 2000 Mahomed -- Thanks for the question regarding "SQL EXECUTE IMMEDIATE -- pro*c", version 2.2.4.0.0
You Asked
I would like to obtain info into a host variable for a named
table dynamically.
How best can I do that ? Can I use EXECUTE IMMEDIATE statement?

e.g   SELECT count(*) into :count
      from a_table
      where .....

where a_table would be variable.
and we said...
You need to use a bit of dynamic sql for that.  It would look
like this:

main( argc, argv )
int argc;
char *  argv[];
{
char        oracleid[50] = "scott/tiger";

varchar     sql[255];
int         cnt;

    EXEC SQL WHENEVER SQLERROR DO sqlerror_hard();
    EXEC SQL CONNECT :oracleid;

    sprintf( sql.arr, "select count(*) from %s", "emp" );
    sql.len = strlen(sql.arr);

    EXEC SQL PREPARE S FROM :sql;
    EXEC SQL DECLARE C CURSOR FOR S;
    EXEC SQL OPEN C;
    EXEC SQL FETCH C INTO :cnt;
    EXEC SQL CLOSE C;

    printf( "%d rows...\n", cnt );
}

Execute immediate works with bind variables.  If you want to use
that, we can but we'll have to use PLSQL...

For example:

main( argc, argv )
int argc;
char *  argv[];
{
char        oracleid[50] = "scott/tiger";

varchar     sql[255];
int         cnt;

    EXEC SQL WHENEVER SQLERROR DO sqlerror_hard();
    EXEC SQL CONNECT :oracleid;

    sprintf( sql.arr, "begin select count(*) into :cnt from %s;
end;", "emp" );
    sql.len = strlen(sql.arr);

    EXEC SQL PREPARE S FROM :sql;
    EXEC SQL EXECUTE S USING :cnt;

    printf( "%d rows...\n", cnt );
}
Review & Followup
Rating: 5
March 25, 2002
Reviewer: Leonhard Knauer-Mademann from germany (Bavaria)
Total hit, excacly what i was looking for.
Thank you Tom, you are doing a real great job.

July 17, 2000 Ravinder -- Thanks for the question regarding "Replication from SQL Server", version 8.1.6
You Asked
Hi Tom,

I have never worked on SQL Server. and now I wants to replicate
a few tables from SQL Server Database into Oracle Database.
I am aleady having the same set of Tables in my Oracle Database,
which I wants to replicate

Question is Can I do this ?? and if yes how ?

Thanks

Ravi
and we said...
You can create a FULL REFRESH, read only snapshot of the data
into Oracle from SQLServer.

You can create a CHANGES ONLY or FAST refresh read only snapshot
from Oracle into SQLServer.

This is done via the transparent gateway to SQLServer.  Once you
have the transparent gateway, SQLServer will appear to be an
Oracle data source which you can query in real time via a
database link or you can use snapshots to copy data in either
direction.

See:

Oracle Heterogeneous Services Concepts
http://technet.oracle.com/doc/oracle8i_816/server.816/a76960/hs_conce.htm#2426
in the

Oracle8i Distributed Database Systems
http://technet.oracle.com/doc/oracle8i_816/server.816/a76960/toc.htm
document. As well
http://www.oracle.com/gateways/
for more info.
July 17, 2000 John -- Thanks for the question regarding "We are migrating from Oracle 7.3.3 to Oracle 8i", version Oracle 7.3.3
You Asked
Hi Tom,
I was hoping you could point me in the right direction. Our
group is scheduled to upgrade to Oracle8 from Oracle7.3.3 very
soon. And I have been asked to ensure that all our Java apps
will function correctly.

My group has developed several Java front end apps which
accesses our Oracle backend via JDBC. We are using an Oracle
lite version with (if this helps)a zipped file named
Oracle111.zip.

We have a fully supported in house DBA group that I feel fully
competent in as far as getting our new datbase set up and
migrated correctly.

Can you provide me with any useful information that I can use to
aid me in this task?

Also, should I feel this confident in my DBA group or should I
take some precautionary measures to ensure a successful upgrade?
and we said...
As with any upgrade, you should prepare for the unexpected.

The DBA should be able to get the database up and running no
problems -- its the application that will have the most
concerns.  Just because the database is up and going does not
mean the application will behave in exactly the same way.

I'd feel very confident in a compentent DBA's ability to migrate
an Oracle7.3 instance to Oracle8i release 2 -- what I'd be
thinking about is how I'm going to exercise all (or at least the
most critical) components of my applications to ensure that they
still function as I believe they should.  There have been
thousands of changes made to Oracle over the last 4 years since
7.3 came out -- at least one of them will impact you in some
way.

So -- the DBA's have the "easy" job.  You should make sure to
have a test environment where they can take a backup of the
existing 7.3 environment (software and all) and practice
migrating the instance -- to get any nuances worked out.  Then,
you would use that instance for some heavy duty testing.  After
that -- there should be no issues with regards to migrating the
production instance.
Review & Followup
Rating: 4
Oracle 8 upgrade from Oracle 7 March 27, 2001
Reviewer: Stan Perkins from Fresno, CA USA
This question and response answered my question perfectly. Thank you very much
Tom for answering the question so concisely AND making these archives available.

July 17, 2000 Ashish -- Thanks for the question regarding "How can I find Max sessions", version 8.1.5
You Asked
Hi Tom,

I wanted to know the max number of session the instance had
without shutting down the database. Is it possible? if yes then
how?
Is licence water mark in alert log corresponds to max session of
the instance before it shut down?

Thanks,

rgds,
ashish
and we said...
A simple "select * from v$license" in sqlplus will give you this
and other tidbits of information about the number of sessions in
your database since its been started.
July 19, 2000 sijo -- Thanks for the question regarding "Qn on disabling or hiding a record in d2k for multirecords", version Forms 5
You Asked
hi Tom,
i want to know is there any way by which
i can disable a record or hide a record depending on some
condition
eg i have a multirecord block of 10 recs
 if a column has a zero value then we have to hide that record.
can we do it by using system.cursor_record or
when-new-record-instance trigger.
thanx in advance
and we said...
You can "disable" (eg: prevent updates to) the record by placing
a "when-new-record-instance" trigger on the BLOCK containing the
multiple records.

For example, lets say you have a block on DEPT.  You can update
records with deptno <= 20.  You can can a trigger such as:

if ( :dept.deptno <= 20 )
then
    set_block_property( 'dept', UPDATE_ALLOWED,
                             PROPERTY_TRUE );
else
    set_block_property( 'dept', UPDATE_ALLOWED,
                             PROPERTY_FALSE );
end if;

On the block (you can use SET_RECORD_PROPERTY,
SET_ITEM_INSTANCE_PROPERTY as well to set visual attributes on
the current record/item to make it more visible to the end user
that this field is "disabled" as you say.  You can even prevent
navigation to this record if you wanted in a similar fashion.
For example:

if ( :dept.deptno <= 20 )
then
   Null;
else
    Next_Record;
end if;

Would cause us to skip to the next record when we entered a
record that was "disabled"
Review & Followup
Rating: 1
I have a similar problem but the solution given will not work for me September 27, 2002
Reviewer: jon from Hartford, CT USA
I have a multi-record block.  Each record contains a group of display items and
a check box (obviously, an input field, but the only one).  Under certain
circumstances, the check box should be disabled.  Is there any way to do this?

July 19, 2000 Rao -- Thanks for the question regarding "Reports queing", version 2.1
You Asked
Tom,

What pupose is Reports Queing from Developer 2000 Tool kit
used??

How to make use of it??

Bye..
and we said...
It allows you to schedule reports to be executed in the
background and monitor their progress.  In this fashion, you do
not have to wait for the report to finish but rather can go
about your work (or go home, or whatever) and review the
finished output at a later date.

See
http://technet.oracle.com/products/reports/
and
http://technet.oracle.com/docs/products/developer/doc_index.htm
for more infomation on the reports server and its use.
July 19, 2000 Omar -- Thanks for the question regarding "Sending Mail -- from reports.", version 6.0
You Asked
How Could I send a report as attached file via an e-mail from
developer environment, or where could I look for an answer.
with respect
and we said...
You would use the DESNAME parameter to reports to do this.

DESNAME (RWBLD60)

DESNAME is the name of the file, printer, or email ID (or
distribution list) to which the report output will be sent. To
send the report output via email, specify the email ID as you do
in your email application (any MAPI-compliant application on
Windows or your native mail application on UNIX). You can
specify multiple usernames by enclosing the names in parentheses
and separating them by commas (e.g., (name, name, . . .name)).
July 19, 2000 Ashish -- Thanks for the question regarding "Shifting Of Schema from one tablespace to another", version 8.0.5
You Asked
I have one schema called 'SCM1' and all the objects of that
schema are on four tablespaces A,B,C,D .Now Is there any way
to shift all objects of schema 'SCM1' to other tablespaces
E,F,G,H in such a way that objects of tablespace A will move
ro tablespace E and so on ...
and we said...
No, not in a direct fashion.

What you would need to do is EXP all of the objects in
tablespace A to one export file.  Then all of B to another (and
then C and D).  Then, you would imp each of the four files
individually, changing the users DEFAULT TABLESPACE in between
each import (and making sure that either tablespaces A-D do not
EXIST in the target database or by making it so they cannot
create objects in tablespaces A-D anymore).

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:47812348053
for more info on exactly how to accomplish this.  In Oracle8i
release 8.1, this is much easier as we can "alter table T move
tablespace Y".
July 19, 2000 Tony -- Thanks for the question regarding "Modifying data within function", version 8.1.6 NT 4
You Asked
I know it isn't allowed to modify data within a stored function.
But I need to update a sequence-table (used by some
applications) and return the increased sequence value. How can I
do this?

(here is some psuedo-code)

create table seqtab
( seqname varchar2(10),
  currval number
);

create function incseq(seq varchar2) return number
as
  nextval number;
  result  number;
begin
  select currval + 1 from seqtab where seqname = seq into
result;
  update seqtab set currval = result where seqname = seq;
  return result;
end;

Crush your brains, please...
Thanks, Tony Cardalda.
and we said...
FUNCTIONS can most certainly modify data.  They can do anything
a PROCEDURE can do.  In fact a function is simply a procedure
that can also return an extra value (sort of like a procedure
with an extra OUT parameter at the end)

But -- don't do that.  PLEASE use a sequence instead.  Its so
much faster, so much more concurrent -- and since you are doing
this in a procedure/function, you don't need to worry about
"portability" since the function can be implemented however you
want in any given database.  PLEASE use a sequence.

The function would look like:

create function incseq( p_seq varchar2 ) return number
as
   l_nextval number;
begin
   execute immediate 'select ' || p_seq || '.nextval
                        from dual' INTO l_nextval;
   return l_nextval;
end;
/

In fact, if you can -- avoid the function ALL TOGETHER and
either use a trigger which will silently assigne the appropriate
nextval or just use

insert into t values ( myseq.nextval, ...other columns.... );

(but if you persist, you can update the table in a function --
you just won't be able to call that function from SQL is all --
you'll need to call it from PLSQL.  If you use a sequence -- you
can call the sequence from SQL via:  "select YOUR_SEQ.NEXTVAL
from dual").  Also, in a multi-user concurrent system you'll
need to REVERSE the order of you UPDATE and SELECT above.  You
need to code:

   update seqtab set currval = currval+1 where seqname = seq
   RETURNING currval into result;

If you do the select and then the update-- two people running
this at the same will get the SAME result.  The update locks the
row and two people will not be able to run this (hence why you
should REALLY use a sequence!!!!)
July 19, 2000 George -- Thanks for the question regarding "Committing/multitable form in multiuser environment.", version DEV.2000 FORM 5
You Asked
Dear sir,

 I am developing a small package where three tables are used for
data entry in a single screen. Since I faced problem with that
 form I simulated the same situation by creating the following
simple tables for testing purpose. I faced the same problem here
 as well. Can you kindly help me?

 This is what I want. The user should should be able to add data
in this screen and should be able to exit after committing or
 cancelling his works.

 My three tables are given here:

 create table T1
 (t1pk number(5) primary key,
 srno1 number(6)
 );
 create table T2
 (t2pk number(5) primary key,
 t1fk number(5) references t1(t1pk),
 srno2 number(6)
 );
 create table T3
 (t2fk number(5) references t2(t2pk),
 srno3 number(6)
 );
 create sequence st1;
 create sequence st2;

 I have made a form for data entry where Table T1 has one record
displayed, T2 and T3 five records each displayed in tabular
 blocks. I increment the sequences st1 and st2 in the pre-insert
trigger of T1 and T2 and assign the values to their respective
 primary keys. The primary keys are disabled as they are
populated by the sequences.

 A POST command is used in the form level On-Clear-Details
trigger before Clear_All_Master_Details command. This is done to
 avoid the 'Do you want to save changes' alert box that appears
when navigating to different records in the T2 table with data
 newly entered or changed in T3 table.

 This form works perfectly OK in a single user environment.
However in multiuser(multisession) environment it creates lock
 problem - I suppose. I tested by running the form 4/5 times as
a single user simultaneously from the same machine. When I try
 to commit the 3rd or 4th running form, it doesn't finish and
come out but keeps waiting with the message 'working...' in the
 message area. This happens some time even before issuing the
commit command when changing to different records in the T2
 table. This form will get OK if the previous running forms are
exitted without committing.

 Now, I know that some records are getting locked and that is
why the problem exists. In my testing I was adding new records
and
 never trying to edit any existing records. I wonder why any
uncommitted records get locked as they are never accessed again
as I
 was always adding new record in the newly running forms. I can
send you the .fmb file if you want it.

 Can you kindly advice me a solution. Thanks in advace.

 I am using form 5 in windows connected to Oracle 8.0.5. on NT.
and we said...
I believe its an issue of unindexed foreign keys.

Take a look at
http://osi.oracle.com/~tkyte/unindex/index.html
and see if that is not the issue.  The problem is probably
becase forms updates by default ALL columns in a block when any
field has changed and hence is updating the primary key of the
parent table which will cause a full table lock on the child
table if the foreign keys are not indexed.

If thats not the issue, please repost the question and just
reference the subject (you don't have to re-input all of the
above)
July 19, 2000 Jeff -- Thanks for the question regarding "when all_tab_columns and user_tab_columns get updated?", version 7.3.4
You Asked
Tom,

When a user modifies a column (makes a varchar2(20) into a
varchar2(25)) structurally, when are these changes reflected
in the all_tab_columns and user_tab_columns views/tables?

Is the update activity immediately reflected in these tables
in a trigger like manner?

Thanks
Jeff Kish
and we said...
The change is made immediately.

DDL like the "alter table modify" is automatically committed (as
most data dictionary changes are to avoid locking the
dictionary).  Hence as soon as you issue the command and it
completes, the base tables (sys tables) are modified right away
and since ALL|USER_TAB_COLUMNS are simply views of the base
tables -- they reflect the changes immediately.
July 19, 2000 Andy -- Thanks for the question regarding "Create table with date appended", version 8.0.5
You Asked
Hi,

 How do I go about appending the current date onto the end of a table name to
make the tablename unique. I have tried the following with no joy:

create table 'temp_project_'||TOCHAR(sysdate,'DD/MM/YYYY')
as
select prj.*
from project prj
where not exists
(  select contact.primarykey from contact where contact.primarykey =
prj.contactkey )
;

Any help I would appreciate

Thankyou

Andy Brown
and we said...
Well I for one would avoid using "temp" tables (inline views work GREAT for this
stuff) but If I had to -- the method I use would vary by language.  Or in your
case above -- I would probably use a permanent table PROJECT and add a column to
it "timestamp" and do

insert into project
select prj.*, SYSDATE from project prj
where not exists ( select contact.primarykey from contact where
contact.primarykey =
prj.contactkey );

and keep all of the data in one table rather then lots of data in different
tables (and then use dbms_job to schedule this insert to run every day at a
fixed time so I don't even have to run a script or anything).

Lets say I was in SQLPLUS and wanted to do the above however.  I would:

ops$tkyte@8.0> column TNAME new_value T
ops$tkyte@8.0> select 'temp_project_' || to_char(sysdate,'DDMMYYYY') tname
  2  from dual
  3  /

TNAME
---------------------
temp_project_19072000

ops$tkyte@8.0> create table &T as select * from dual;
old   1: create table &T as select * from dual
new   1: create table temp_project_19072000 as select * from dual

Table created.

ops$tkyte@8.0>

The column tname new_value statement creates a macro variable whose value will
be the last value of a column called TNAME that was selected.  We then select
TNAME from dual.  We can then create a table using that macro variable.
July 19, 2000 Dix -- Thanks for the question regarding "Standby Database", version 8i (8.1.5)
You Asked
Hi Tom,
I have two similar empty databases with diffrent tablespace
name.
I would like make one as primary and second one as standby.
Is it possible to make minior changes in init.ora files and
setup Stndby Database without creating new database.

Name             d1            d2
Data Tablespace       t1 (100mb)    t2 (100 mb)
Index Tablespace      i1 (75mb)     i2 (75 mb)

Thank you for your time and help.
/dix
and we said...
Thats not how a standby database works.  You will take one of
the databases (the primary), back it up, restore it elsewhere
and start applying redo logs.  The tablespace names will be the
same since the standby starts as a copy of the primary.  You do
not "create" a standby database as a "database" with the create
database command -- its starts as a backup.

Please see
http://technet.oracle.com/doc/server.815/a67773/standby.htm#12342
for complete details.
July 19, 2000 raghavendra -- Thanks for the question regarding "about a strange query", version 8.0
You Asked
hi tom,
SQL> SELECT * FROM EMP
  2  WHERE DEPTNO IN (SELECT DEPTNO FROM DEPT
  3                   WHERE DEPTNO=10
  4                    AND ENAME='CLARK');

    EMPNO ENAME      JOB             MGR HIREDATE        SAL
 COMM    DEPTNO
--------- ---------- --------- --------- --------- ---------
--------- ---------
     7782 CLARK      MANAGER        7839 09-JUN-81      2450
             10

if you see the above query, i used ename column of emp table
referenced in outer query in the condition of the subquery
referencing only dept table and it is working fine as you see
the output.i was surprised.can you please tell me how this query
is working?
and we said...
Its a correlated subquery.  All of the columns of EMP are
available in the subquery.  The above is similar to the
procedural logic:

   for x in ( select * from EMP )
   loop

      if EXISTS
           ( select NULL from dept
              where deptno = 10
                and X.ENAME = 'CLARK' )
      then
         OUTPUT X;
      else
         discared X;
      end if
   end loop

It is executing the subquery once for each row in EMP and
replacing the reference to ENAME in the subquery with the actual
value of the ENAME for a given row.

This is most typically used in "where <not> exists" type queries
-- not in an IN.  I might use it to code somthing like:

select *
  from T
 where NOT EXISTS ( select NULL
                      from T2
                     where T2.some_column = T.some_column)

The behaviour you see is natural, normal and to be expected (but
surprising the first time you see it ;)

consider:

scott@ORA734.WORLD> select * from dual
  2  where dummy in ( select dummy from all_users  );

D
-
X

it does the same thing....  It selects DUMMY (a column in DUAL
not in all_users) from all_users.
July 19, 2000 Bhavesh -- Thanks for the question regarding "Tuning the Query", version 8.1.5
You Asked
Hi Tom:

Good Morning!

This is regarding tuning the query so that I can avoid the full
table scan..
The simplified version of table is shown below..

Oracle8i>desc tempx
 Name                                                  Null?
Type
 ----------------------------------------------------- --------
------------------------------------
 FAMASCUSTID
NUMBER(3)
 STMTDATE
DATE
 DATEENTERED
DATE

Oracle8i>select * from tempx;

FAMASCUSTID STMTDATE    DATEENTERED

----------- ----------- -----------

         10 01-jan-1997 02-jan-1997

         10 01-jan-1997 18-jul-2000

         10 01-jan-1997 19-jul-2000

         20 01-jan-1998 02-jan-1998

         30 01-jan-1999 02-jan-1999

         20 01-jan-1998 01-jan-2000

         20 01-jan-1997 19-jul-2000

7 rows selected.

The time part of the stmtDate are chooped off...The following
query shows the time part of both DATE columns..

Oracle8i>edit
Wrote file afiedt.buf

  1  select famasCustId, to_char(stmtdate, 'hh24:mi:ss')
stmt_time, to_char(dateEntered,'hh24:mi:ss') date_time
  2* from tempx
Oracle8i>/

FAMASCUSTID STMT_TIM DATE_TIM

----------- -------- --------

         10 00:00:00 00:00:00

         10 00:00:00 14:36:09

         10 00:00:00 14:36:11

         20 00:00:00 00:00:00

         30 00:00:00 00:00:00

         20 00:00:00 00:00:00

         20 00:00:00 14:36:11

7 rows selected.

Now, all I want is find the latest run (max(dateEntered)) for
each group of stmtdate for a given famasCustId in the MOST

EFFIECINT WAY! The table size will grow very fast...It has
already 10,000 records and I want to avoid  full tablescan!
The following version of the query does NOT statisfy me!

Oracle8i>set autotrace on
Oracle8i>select   * from tempx x
  2    where dateEntered =
  3         (select  max(dateEntered)
  4            from tempx
  5            where famasCustid = 10 and         -- always
given
  6                x.famasCustid = famasCustid
  7                and x.stmtdate = stmtdate);

FAMASCUSTID STMTDATE    DATEENTERED

----------- ----------- -----------

         10 01-jan-1997 19-jul-2000

Execution Plan
----------------------------------------------------------

   0      SELECT STATEMENT Optimizer=CHOOSE

   1    0   FILTER

   2    1     TABLE ACCESS (FULL) OF 'TEMPX'

   3    1     SORT (AGGREGATE)

   4    3       TABLE ACCESS (BY INDEX ROWID) OF 'TEMPX'

   5    4         INDEX (RANGE SCAN) OF 'ID_N_STMTDATE_IDX'
(NON-UNIQU
          E)

Statistics
----------------------------------------------------------

          0  recursive calls

          4  db block gets

          5  consistent gets

          0  physical reads

          0  redo size

       1228  bytes sent via SQL*Net to client

        855  bytes received via SQL*Net from client

          4  SQL*Net roundtrips to/from client

          1  sorts (memory)

          0  sorts (disk)

          1  rows processed

For the famasCustID = 20, the  query and the correct result
are...

Oracle8i>select   * from tempx x
  2    where dateEntered =
  3         (select  max(dateEntered)
  4            from tempx
  5            where famasCustid = 20 and
  6                x.famasCustid = famasCustid
  7                and x.stmtdate = stmtdate);

FAMASCUSTID STMTDATE    DATEENTERED
----------- ----------- -----------
         20 01-jan-1998 01-jan-2000
         20 01-jan-1997 19-jul-2000

Oracle8i>SET AUTOTRACE OFF

Have created the following non unique indexes...

Oracle8i>SELECT INDEX_NAME, COLUMN_NAME, COLUMN_POSITION
  2  FROM USER_IND_COLUMNS
  3  WHERE TABLE_NAME = 'TEMPX';

INDEX_NAME                     COLUMN_NAME
COLUMN_POSITION
------------------------------ --------------------
---------------
D_T                            DATEENTERED
 1
ID_N_STMTDATE_IDX              STMTDATE
 2
ID_N_STMTDATE_IDX              FAMASCUSTID
 1

3 rows selected.

Oracle8i>SPOOL OFF

----------------------
Thanks a lot, Tom
-----------------------
Regards,
Bhavesh
and we said...
The most performant thing would be an index on all three columns
in the order FAMASCUSTID,stmtdate,dateentered.  Short of that --
an index solely on FAMASCUSTID would suffice (but would make us
access the table).

Here is an example:

scott@DEV8I.WORLD> create table t ( FAMASCUSTID int, STMTDATE
date, DATEENTERED date );

Table created.

scott@DEV8I.WORLD>
scott@DEV8I.WORLD> declare
  2          r       number;
  3  begin
  4          for i in 1 .. 30
  5          loop
  6                  r := random.rand;
  7
  8                  insert into t
  9                  values
 10                  ( mod( i, 5 )+1, trunc(sysdate)-r,
                       sysdate - r/10 );
 11          end loop;
 12  end;
 13  /

PL/SQL procedure successfully completed.

(see
http://osi.oracle.com/~tkyte/Misc/Random.html
for info on random numbers in plsql if you want)

scott@DEV8I.WORLD>
scott@DEV8I.WORLD> alter session set nls_date_format =
'dd-mon-yyyy hh24:mi:ss';

Session altered.

scott@DEV8I.WORLD> select * from t order by 1, 2, 3;

FAMASCUSTID STMTDATE             DATEENTERED
----------- -------------------- --------------------
          1 22-nov-1920 00:00:00 01-aug-1992 01:14:48
          1 06-feb-1937 00:00:00 16-mar-1994 01:14:48
          1 25-dec-1946 00:00:00 11-mar-1995 22:50:48
          1 29-mar-1975 00:00:00 07-jan-1998 01:14:48
          1 21-oct-1996 00:00:00 04-mar-2000 18:02:48
          1 28-jan-2000 00:00:00 02-jul-2000 03:38:48
          2 26-dec-1941 00:00:00 10-sep-1994 10:50:48
          2 24-feb-1943 00:00:00 22-oct-1994 22:50:48
          2 21-jul-1955 00:00:00 18-jan-1996 22:50:48
          2 29-jan-1972 00:00:00 13-sep-1997 13:14:48
          2 23-feb-1978 00:00:00 23-apr-1998 06:02:48
          2 19-jul-1993 00:00:00 06-nov-1999 18:02:48
          3 24-jul-1929 00:00:00 13-jun-1993 15:38:48
          3 10-jan-1938 00:00:00 18-apr-1994 20:26:48
          3 31-dec-1940 00:00:00 05-aug-1994 10:50:48
          3 22-mar-1945 00:00:00 06-jan-1995 15:38:48
          3 03-dec-1979 00:00:00 27-jun-1998 01:14:48
          3 12-jul-1999 00:00:00 12-jun-2000 03:38:48
          4 17-jun-1911 00:00:00 22-aug-1991 10:50:48
          4 11-feb-1924 00:00:00 26-nov-1992 15:38:48
          4 21-aug-1957 00:00:00 04-apr-1996 03:38:48
          4 08-dec-1982 00:00:00 15-oct-1998 03:38:48
          4 11-nov-1996 00:00:00 06-mar-2000 20:26:48
          4 26-nov-1999 00:00:00 25-jun-2000 20:26:48
          5 28-jul-1911 00:00:00 26-aug-1991 13:14:48
          5 12-oct-1915 00:00:00 27-jan-1992 06:02:48
          5 14-jun-1929 00:00:00 09-jun-1993 15:38:48
          5 03-jun-1973 00:00:00 01-nov-1997 15:38:48
          5 28-mar-1982 00:00:00 19-sep-1998 15:38:48
          5 16-may-1993 00:00:00 31-oct-1999 08:26:48

30 rows selected.

scott@DEV8I.WORLD> alter session set nls_date_format =
'dd-mon-yy';

Session altered.

scott@DEV8I.WORLD>
scott@DEV8I.WORLD> create index t_idx on
t(FAMASCUSTID,stmtdate,dateentered);

Index created.

scott@DEV8I.WORLD>
scott@DEV8I.WORLD> set autotrace on
scott@DEV8I.WORLD>
scott@DEV8I.WORLD> select FAMASCUSTID, stmtdate,
max(dateentered)
  2    from t
  3   where FAMASCUSTID = 1
  4   group by FAMASCUSTID, stmtdate
  5  /

FAMASCUSTID STMTDATE  MAX(DATEE
----------- --------- ---------
          1 22-nov-20 01-aug-92
          1 06-feb-37 16-mar-94
          1 25-dec-46 11-mar-95
          1 29-mar-75 07-jan-98
          1 21-oct-96 04-mar-00
          1 28-jan-00 02-jul-00

6 rows selected.

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   SORT (GROUP BY)
   2    1     INDEX (RANGE SCAN) OF 'T_IDX' (NON-UNIQUE)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          1  consistent gets
          0  physical reads
          0  redo size
       1510  bytes sent via SQL*Net to client
        746  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
          2  sorts (memory)
          0  sorts (disk)
          6  rows processed

scott@DEV8I.WORLD> set autotrace off
scott@DEV8I.WORLD>
July 19, 2000 Bhavesh -- Thanks for the question regarding "Tuning Query", version 8.1.5
You Asked
Hi Tom:

Good Morning!
==============================================
Sorry, Tom.., Thanks for the answer but..
I have to rephrase my question...
The table also has the "ungrouped" column Id...

================================================
This is regarding tuning the query so that I can avoid the full
table scan..
The simplified version of table is shown below..

Oracle8i>DESC TEMPX
 Name                                                  Null?
Type
 ----------------------------------------------------- --------
------------------------------------
 FAMASCUSTID
NUMBER(3)
 STMTDATE
DATE
 DATEENTERED
DATE
 ID
NUMBER

Oracle8i>select * from tempx;

FAMASCUSTID STMTDATE  DATEENTER        ID

----------- --------- --------- ---------

         10 01-JAN-97 02-JAN-97         1

         10 01-JAN-97 18-JUL-00         2

         10 01-JAN-97 19-JUL-00         3

         20 01-JAN-98 02-JAN-98         4

         30 01-JAN-99 02-JAN-99         5

         20 01-JAN-98 01-JAN-00         6

         20 01-JAN-97 19-JUL-00         7

7 rows selected.

The time part of the stmtDate are choPped off...The following
query shows the time part of both DATE columns..

Oracle8i>edit
Wrote file afiedt.buf

  1  select famasCustId, to_char(stmtdate, 'hh24:mi:ss')
stmt_time, to_char(dateEntered,'hh24:mi:ss') date_time, ID
  2* from tempx
Oracle8i>/

AMASCUSTID STMT_TIM DATE_TIM        ID
---------- -------- -------- ---------
        10 00:00:00 00:00:00         1
        10 00:00:00 14:36:09         2
        10 00:00:00 14:36:11         3
        20 00:00:00 00:00:00         4
        30 00:00:00 00:00:00         5
        20 00:00:00 00:00:00         6
        20 00:00:00 14:36:11         7

Now, all I want is find the latest run (max(dateEntered)) for
each group of stmtdate for a given famasCustId in the MOST

EFFIECINT WAY! The table size will grow very fast...It has
already 10,000 records and I want to avoid  full tablescan!
The following version of the query does NOT statisfy me!

Oracle8i>set autotrace on
Oracle8i>select   * from tempx x
  2    where dateEntered =
  3         (select  max(dateEntered)
  4            from tempx
  5            where famasCustid = 10 and         -- always
given
  6                x.famasCustid = famasCustid
  7                and x.stmtdate = stmtdate);

FAMASCUSTID STMTDATE  DATEENTER        ID

----------- --------- --------- ---------

         10 01-JAN-97 19-JUL-00         3

Execution Plan
----------------------------------------------------------

   0      SELECT STATEMENT Optimizer=CHOOSE

   1    0   FILTER

   2    1     TABLE ACCESS (FULL) OF 'TEMPX'

   3    1     SORT (AGGREGATE)

   4    3       TABLE ACCESS (BY INDEX ROWID) OF 'TEMPX'

   5    4         INDEX (RANGE SCAN) OF 'ID_N_STMTDATE_IDX'
(NON-UNIQU
          E)

Statistics
----------------------------------------------------------

          0  recursive calls

          4  db block gets

          5  consistent gets

          0  physical reads

          0  redo size

       1228  bytes sent via SQL*Net to client

        855  bytes received via SQL*Net from client

          4  SQL*Net roundtrips to/from client

          1  sorts (memory)

          0  sorts (disk)

          1  rows processed

For the famasCustID = 20, the  query and the correct result
are...

Oracle8i>select   * from tempx x
  2    where dateEntered =
  3         (select  max(dateEntered)
  4            from tempx
  5            where famasCustid = 20 and
  6                x.famasCustid = famasCustid
  7                and x.stmtdate = stmtdate);

FAMASCUSTID STMTDATE  DATEENTER        ID

----------- --------- --------- ---------

         20 01-JAN-98 01-JAN-00         6

         20 01-JAN-97 19-JUL-00         7

Oracle8i>SET AUTOTRACE OFF

Have created the following non unique indexes...

Oracle8i>SELECT INDEX_NAME, COLUMN_NAME, COLUMN_POSITION
  2  FROM USER_IND_COLUMNS
  3  WHERE TABLE_NAME = 'TEMPX';

INDEX_NAME                     COLUMN_NAME
COLUMN_POSITION
------------------------------ --------------------
---------------
D_T                            DATEENTERED
 1
ID_N_STMTDATE_IDX              STMTDATE
 2
ID_N_STMTDATE_IDX              FAMASCUSTID
 1

3 rows selected.

Oracle8i>SPOOL OFF

----------------------
Thanks a lot, Tom
-----------------------
and we said...
Ok, not much different but different enough.  If you have that
index on all 3 columns FAMASCUSTID,stmtdate,dateentered OR at
least the 2 columns FAMASCUSTID,stmtdate -- we can still do this
pretty good.  There are at least 2 ways.  One is to do the
original query we had in the other question (see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:451020136223
for that reference) and then apply a SELECT in the SELECT
list to it (sort of like a correlated subquery).  This works in
8.1 and up.  The other is to use an IN, that is, run the
original query in the subquery -- and select * from T where
(c1,c2,c3) IN (that query).

Here is the modified example:

scott@DEV8I.WORLD> create table t ( FAMASCUSTID int, STMTDATE
date, DATEENTERED date, id number );

Table created.

scott@DEV8I.WORLD>
scott@DEV8I.WORLD> declare
  2          r       number;
  3  begin
  4          for i in 1 .. 30
  5          loop
  6                  r := random.rand;
  7
  8                  insert into t
  9                  values
 10                  ( mod( i, 5 )+1, trunc(sysdate)-r,
                                  sysdate - r/10, i+100 );
 11          end loop;
 12  end;
 13  /

PL/SQL procedure successfully completed.

scott@DEV8I.WORLD>
scott@DEV8I.WORLD> alter session set nls_date_format =
'dd-mon-yyyy hh24:mi:ss';

Session altered.

scott@DEV8I.WORLD> select * from t order by 1, 2, 3;

FAMASCUSTID STMTDATE             DATEENTERED                  ID
----------- -------------------- -------------------- ----------
          1 01-may-1921 00:00:00 17-aug-1992 02:39:49        105
          1 27-jan-1932 00:00:00 13-sep-1993 09:51:49        110
          1 11-jul-1934 00:00:00 12-dec-1993 00:15:49        130
          1 01-dec-1970 00:00:00 02-aug-1997 05:03:49        115
          1 06-feb-1979 00:00:00 28-may-1998 02:39:49        120
          1 02-may-1982 00:00:00 23-sep-1998 05:03:49        125
          2 04-jun-1922 00:00:00 26-sep-1992 00:15:49        101
          2 10-jan-1939 00:00:00 25-may-1994 09:51:49        126
          2 30-dec-1950 00:00:00 05-aug-1995 14:39:49        111
          2 06-oct-1955 00:00:00 26-jan-1996 17:03:49        106
          2 30-jun-1959 00:00:00 11-jun-1996 00:15:49        116
          2 22-apr-1985 00:00:00 09-jan-1999 19:27:49        121
          3 07-mar-1925 00:00:00 04-jan-1993 17:03:49        107
          3 18-feb-1943 00:00:00 22-oct-1994 09:51:49        102
          3 02-apr-1960 00:00:00 08-jul-1996 17:03:49        112
          3 25-jul-1961 00:00:00 25-aug-1996 14:39:49        122
          3 22-apr-1988 00:00:00 29-apr-1999 09:51:49        117
          3 19-jun-1999 00:00:00 09-jun-2000 21:51:49        127
          4 11-dec-1910 00:00:00 03-aug-1991 17:03:49        113
          4 05-jul-1918 00:00:00 06-may-1992 00:15:49        108
          4 09-may-1954 00:00:00 06-dec-1995 05:03:49        128
          4 08-sep-1974 00:00:00 17-dec-1997 21:51:49        123
          4 25-may-1976 00:00:00 18-feb-1998 09:51:49        103
          4 10-apr-1998 00:00:00 27-apr-2000 09:51:49        118
          5 16-mar-1955 00:00:00 06-jan-1996 07:27:49        124
          5 05-oct-1969 00:00:00 21-jun-1997 00:15:49        104
          5 09-may-1974 00:00:00 05-dec-1997 17:03:49        114
          5 17-jul-1977 00:00:00 01-apr-1998 05:03:49        109
          5 08-jan-1991 00:00:00 06-aug-1999 12:15:49        119
          5 20-jun-1992 00:00:00 28-sep-1999 09:51:49        129

30 rows selected.

scott@DEV8I.WORLD> alter session set nls_date_format =
'dd-mon-yy';

Session altered.

scott@DEV8I.WORLD>
scott@DEV8I.WORLD> create index t_idx on
t(FAMASCUSTID,stmtdate,dateentered);

Index created.

scott@DEV8I.WORLD>
scott@DEV8I.WORLD> set autotrace on
scott@DEV8I.WORLD>
scott@DEV8I.WORLD> select t.*,
  2             (select id
  3                    from t t2
  4                   where t2.FAMASCUSTID = t.FAMASCUSTID
  5                     and t2.stmtdate = t.stmtdate ) ID
  6    from ( select FAMASCUSTID, stmtdate, max(dateentered)
  7             from t
  8            where FAMASCUSTID = 1
  9            group by FAMASCUSTID, stmtdate ) T
 10  /

FAMASCUSTID STMTDATE  MAX(DATEE         ID
----------- --------- --------- ----------
          1 01-may-21 17-aug-92        105
          1 27-jan-32 13-sep-93        110
          1 11-jul-34 12-dec-93        130
          1 01-dec-70 02-aug-97        115
          1 06-feb-79 28-may-98        120
          1 02-may-82 23-sep-98        125

6 rows selected.

thats the example of selecting a SELECT.  We get the 3 columns
by the group by and then go back and pick up the row again to
get the ID.  This counts on FAMASCUSTID,STMTDATE,DATEENTERED
being unique -- if it is not -- then only the next query works
correctly

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   VIEW
   2    1     SORT (GROUP BY)
   3    2       INDEX (RANGE SCAN) OF 'T_IDX' (NON-UNIQUE)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          9  consistent gets
          0  physical reads
          0  redo size
       1606  bytes sent via SQL*Net to client
        906  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
          2  sorts (memory)
          0  sorts (disk)
          6  rows processed

scott@DEV8I.WORLD> select *
  2    from t
  3   where (FAMASCUSTID, stmtdate, dateentered) IN
  4             ( select FAMASCUSTID, stmtdate, max(dateentered)
  5             from t
  6            where FAMASCUSTID = 1
  7            group by FAMASCUSTID, stmtdate )
  8  /

this works in all cases, whether those columns are unique or
not

FAMASCUSTID STMTDATE  DATEENTER         ID
----------- --------- --------- ----------
          1 01-may-21 17-aug-92        105
          1 27-jan-32 13-sep-93        110
          1 11-jul-34 12-dec-93        130
          1 01-dec-70 02-aug-97        115
          1 06-feb-79 28-may-98        120
          1 02-may-82 23-sep-98        125

6 rows selected.

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   NESTED LOOPS
   2    1     VIEW
   3    2       SORT (GROUP BY)
   4    3         INDEX (RANGE SCAN) OF 'T_IDX' (NON-UNIQUE)
   5    1     TABLE ACCESS (BY INDEX ROWID) OF 'T'
   6    5       INDEX (RANGE SCAN) OF 'T_IDX' (NON-UNIQUE)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
         10  consistent gets
          0  physical reads
          0  redo size
       1601  bytes sent via SQL*Net to client
        846  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
          2  sorts (memory)
          0  sorts (disk)
          6  rows processed

scott@DEV8I.WORLD> set autotrace off
scott@DEV8I.WORLD>
July 19, 2000 David -- Thanks for the question regarding "Space Estimation For Schema Objects", version N/A
You Asked
Tom,
    While investigating the writing of a database object sizing
package I discovered 2 differences in the calculation between
Oracle 7 server and Oracle8. These are listed below. The reasons
behind these differences are either typo errors or actual
changes in the calculations. Can you enlighten me as to what the
true situation is. The documents I was using can be found at:

Oracle 7 Server
http://technet.oracle.com/doc/server73x/SAD73/apA.htm#toc201
Oracle8
http://technet.oracle.com/doc/server804/a58397/apa.htm

Error 1

Oracle 7 Server

Step 1: Calculate the Total Block Header Size
The space required by the data block header is the result of the
following formula:
Space after headers (hsize)
=
DB_BLOCK_SIZE - KCBH - UB4 - KTBBH - (INITRANS - 1) * KTBIT -
KDBH

Oracle8 Release 8.0

Step 1: Calculate the Total Block Header Size
The space required by the data block header is the result of the
following formula:
Space after headers (hsize)
=
DB_BLOCK_SIZE - KCBH - UB4 - KTBBH - ((INITRANS - 1) * KTBIT) -
KDBH

Error 2

Oracle 7 Server

Space used per row (rowspace)=MIN(UB1 * 3 + UB4 + SB2, rowsize)
+ SB2

Oracle8 Release 8.0

Space used per row (rowspace)=MAX(UB1 * 3 + UB4 + SB2, rowsize)
+ SB2

Regards,

David.
and we said...
Well, mathematically speaking, error #1 is not an error.  The
formula are the same.  The addition of the parans on 8.0 didn't
change the outcome as

(initrans-1)*ktbit

is the same as

((initrans-1)*ktbit)

and since multiplication takes precendence over
addition/subtraction -- the end result is the same.

for #2, that was a documentation bug in the 7.x doc set.

the correct reference to the 8.0.4 doc set is:
http://technet.oracle.com/doc/server.804/a58397/apa.htm
(missing a dot above)
July 19, 2000 Mark -- Thanks for the question regarding "using uploaded images in dynamically generated pages", version 4.0.8.1
You Asked
I have uploaded some images using oas 4.0.8.1 and I now want to
use those
images on my web pages I am generating using PL/SQL.
How can this be done?
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:242014628882
step 7 is mostly what you are interested in.  You'd make a
procedure similar to that and then:

<img src=/dadname/down?file_val=your_file_name.gif>
July 19, 2000 Hiten -- Thanks for the question regarding "Sql Statement for Counting between 1/2 hr period", version 8.1.6
You Asked
The web hits are recorded in a table A as date column and we
need to write a query which will return count of records which
fall in particular range which may be 30 minutes, 20 or 10.

eg.
Table A
Col1      Number -- sequence number generated.
Col2      Date   -- Date/time ..

report needed
7/18/2000
Range                       Numbers
00:00 Am - 00:30 Am   ..     22
00:31 Am - 01:00 Am   ..     18
...
23:31 Pm - 24:00 Pm   ..     30

What is your suggestion regarding how do i proceed generating
such a report.

Thanks.
and we said...
Sure, a little date arithemetic and we can do this.  consider:

ops$tkyte@8i> /*
DOC>drop table t;
DOC>
DOC>create table t ( x date );
DOC>
DOC>insert into t
DOC>select trunc(sysdate)+ 1/25/60/60 * rownum
DOC> from all_users
DOC>/
DOC>*/
ops$tkyte@8i>

that just created a table with lots of time records in it for
today -- I have about 35k named accounts on my instance so that
created 35k records for today

ops$tkyte@8i> alter session set nls_date_format='dd-mon-yyyy
hh24:mi:ss';

Session altered.

ops$tkyte@8i> select min(x), max(x), count(*) from t
  2  /

MIN(X)               MAX(X)                 COUNT(*)
-------------------- -------------------- ----------
19-jul-2000 00:00:01 19-jul-2000 09:08:41      34293

ops$tkyte@8i>
ops$tkyte@8i> variable period number
ops$tkyte@8i> exec :period := 15

PL/SQL procedure successfully completed.

Period is the number of minutes we want -- I want to count by
15 minute periods so I set it to 15

ops$tkyte@8i>
ops$tkyte@8i> select fixed_up_date+
                     (1/24/60)*(hour_piece*:period), count(*)
  2    from ( select trunc(x,'hh') fixed_up_date,
  3                  trunc(to_char(x,'mi')/:period) hour_piece
  4             from T )
  5   group by fixed_up_date+(1/24/60)*(hour_piece*:period)
  6  /

FIXED_UP_DATE+(1/24/   COUNT(*)
-------------------- ----------
19-jul-2000 00:00:00        936
19-jul-2000 00:15:00        938
19-jul-2000 00:30:00        937
19-jul-2000 00:45:00        938
19-jul-2000 01:00:00        937
19-jul-2000 01:15:00        938
19-jul-2000 01:30:00        937
19-jul-2000 01:45:00        938
19-jul-2000 02:00:00        937
19-jul-2000 02:15:00        938
19-jul-2000 02:30:00        937
19-jul-2000 02:45:00        938
19-jul-2000 03:00:00        937
19-jul-2000 03:15:00        938
19-jul-2000 03:30:00        937
19-jul-2000 03:45:00        938
19-jul-2000 04:00:00        937
19-jul-2000 04:15:00        938
19-jul-2000 04:30:00        937
19-jul-2000 04:45:00        938
19-jul-2000 05:00:00        937
19-jul-2000 05:15:00        938
19-jul-2000 05:30:00        937
19-jul-2000 05:45:00        938
19-jul-2000 06:00:00        937
19-jul-2000 06:15:00        938
19-jul-2000 06:30:00        937
19-jul-2000 06:45:00        938
19-jul-2000 07:00:00        937
19-jul-2000 07:15:00        938
19-jul-2000 07:30:00        937
19-jul-2000 07:45:00        938
19-jul-2000 08:00:00        937
19-jul-2000 08:15:00        938
19-jul-2000 08:30:00        937
19-jul-2000 08:45:00        938
19-jul-2000 09:00:00        544

37 rows selected.

that gave me my counts by 15 minute windows... Now lets try 10
minute windows

ops$tkyte@8i> exec :period := 10

PL/SQL procedure successfully completed.

ops$tkyte@8i> /

FIXED_UP_DATE+(1/24/   COUNT(*)
-------------------- ----------
19-jul-2000 00:00:00        624
19-jul-2000 00:10:00        625
19-jul-2000 00:20:00        625
19-jul-2000 00:30:00        625
19-jul-2000 00:40:00        625
19-jul-2000 00:50:00        625
19-jul-2000 01:00:00        625
19-jul-2000 01:10:00        625
19-jul-2000 01:20:00        625
19-jul-2000 01:30:00        625
19-jul-2000 01:40:00        625
19-jul-2000 01:50:00        625
19-jul-2000 02:00:00        625
19-jul-2000 02:10:00        625
19-jul-2000 02:20:00        625
19-jul-2000 02:30:00        625
19-jul-2000 02:40:00        625
19-jul-2000 02:50:00        625
19-jul-2000 03:00:00        625
19-jul-2000 03:10:00        625
19-jul-2000 03:20:00        625
19-jul-2000 03:30:00        625
19-jul-2000 03:40:00        625
19-jul-2000 03:50:00        625
19-jul-2000 04:00:00        625
19-jul-2000 04:10:00        625
19-jul-2000 04:20:00        625
19-jul-2000 04:30:00        625
19-jul-2000 04:40:00        625
19-jul-2000 04:50:00        625
19-jul-2000 05:00:00        625
19-jul-2000 05:10:00        625
19-jul-2000 05:20:00        625
19-jul-2000 05:30:00        625
19-jul-2000 05:40:00        625
19-jul-2000 05:50:00        625
19-jul-2000 06:00:00        625
19-jul-2000 06:10:00        625
19-jul-2000 06:20:00        625
19-jul-2000 06:30:00        625
19-jul-2000 06:40:00        625
19-jul-2000 06:50:00        625
19-jul-2000 07:00:00        625
19-jul-2000 07:10:00        625
19-jul-2000 07:20:00        625
19-jul-2000 07:30:00        625
19-jul-2000 07:40:00        625
19-jul-2000 07:50:00        625
19-jul-2000 08:00:00        625
19-jul-2000 08:10:00        625
19-jul-2000 08:20:00        625
19-jul-2000 08:30:00        625
19-jul-2000 08:40:00        625
19-jul-2000 08:50:00        625
19-jul-2000 09:00:00        544

55 rows selected.

Thats all we have to do to achieve this.

ops$tkyte@8i> alter session set nls_date_format='dd-mon-yy';

Session altered
July 19, 2000 Eli -- Thanks for the question regarding "Chinese capabilities in Oracle8i", version 8.1.6
You Asked
I would like to ask you few question about Intermedia text
capabilities in Chinese.

1. What kind of Chinese is Intermidia support? (Traditional or
Simplified)
2. What are the performance compare English language?
3. Can I get more information on Chinese indexing and Chinese
language using oracle?

Note:
I serach for this on oracle technet with no results.
and we said...
for 1, the Chinese lexer supports both Traditional and
Simplified Chinese in interMedia Text.  Note that the
CHINESE_VGRAM_LEXER only works with the UTF-8 character set.

For #2, I personally do not know of any available performance
data of interMedia Text using Chinese or even a DBCS. Sorry.

For #3, Although there is not a lot of specific information
related to interMedia Text and Chinese, you can gather some
information from the whitepaper at:
http://technet.oracle.com/products/intermedia/pdf/imt_multi.pdf
...
July 20, 2000 Eli -- Thanks for the question regarding "Using database link or new connect", version 8.06
You Asked
Hi
In my company we develop application for selecting  and update
reference tables.
The reference tables location are  in one database name RTMS.
The application need for time to time to access table in remote
instance CORE (there is no need to join local table and remote
table)
My concern is if to perform new connect to the remote instance
and get the data (in this case my application will user 2
connect) or to use database link.

For what I understand when I use database link oracle open
server process in the remote machine (link new connect) and my
concern is performances
Can't you advise

Tnx
and we said...
Well opening a database link from server to server will take as
much time as opening a new connection from client to server.
Its mostly a matter of ease of use.  The database link can hide
the fact that the tables are on CORE -- your developers will
access synonyms or views that look like local tables, they will
not be aware that the tables are remote.

see
http://technet.oracle.com/doc/server.804/a58247/ds_ch2.htm#12904
for some more info on database links and consider the shared
database link perhaps as well (to cut down on resources).  There
are significant enhancements to the shared database link in
Oracle8i (Net8.1) see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76960/ds_conce.htm#15997
for info on that.

What you might also consider is replication.  In this fashion,
only 1 back end process will use a database link (to replicate
with) and all developers/end users will use real local tables.
You will not be dependent on 2 databases being available for
your application.  You can do either read only replication or
read-write replication.  Read only replication is trivial to
implement and if you just need access to some lookup tables --
would be the way to go.  Read Write replication can be a little
more involved but for simple tables -- its fairly
straightforward.
July 20, 2000 Neeraj -- Thanks for the question regarding "Concatenated Index ", version Oracle 8.0.4
You Asked
Tom:

A typical B tree index looks like :

                     4
          ------------------------
          |                       |
          2                       6
       -------                  ------
       |      |                 |     |
       1      3                 5     7
       R      R                 R     R

where R : stands for rowid.

How does Oracle implement a concatenated index ? Could you
give a visual diagram like above . I scanned Oracle metalink,
docs but could not find one.

Thanks,
Neeraj
and we said...
lets say you indexed ( x,y ) where x was a number and y was a
date.

It would be the same as above except each entry would have 2
elements instead of 1.  The comparison of

(x1,y1) to (x2,y2)

would be made using the same rules as ORDER by would use to sort
data is all.

It is no different then a non-concatenated index.  Given the
data above (1...7), for values of X, if we just added a Y date
value -- the diagram would remain the same.  If we added
additional entries (say x=4, y=some value) then the 2 X's = 4
would be compared, found equal and then their Y values would be
compared to figure out who goes to the LEFT and who goes to the
RIGHT.
July 20, 2000 prashant -- Thanks for the question regarding "Intranet development -- what tools does Oracle have", version 8.1.5
You Asked
Hi Tom
We are planning to develop Intranet for our company using Oracle
tools .I find Oracle WEBDB suitable for that.Can you give me
your suggestions and guidance in this regard and in choosing the
oracle tool for this.
Thanks and regards
Prashant
and we said...
Depends on what you are building on your intranet.

WebDB is suitable for simple data input screens, online reports
and portal development.

If you are building full blown applications, something like
Jdeveloper or Developer Server would be more appropriate.

If you are building complex reports with lots of formatting,
Developer server (reports component) would be more applicable.

In fact, a combination of all three is possible -- using WebDB
as the portal to pull them all together.

See
http://www.oracle.com/tools/InternetDevTools/index.html
for more info on those.
July 20, 2000 Kelli -- Thanks for the question regarding "Default system accounts and passwords on Solaris?", version Oracle 7.3.4 on Solaris 2.6
You Asked
Hi Tom, I can't seem to find this explicitly stated in Oracle
manuals,
but I'm wondering if the Solaris version of Oracle creates a
default password for the SYS and SYSTEM (as the Windows NT
versions
do.) I've been using Oracle on NT for awhile, but am just
getting
started with the Unix side of the world, so any help will be
greatly appreciated.
Hope you're doing well, btw--from the looks of your site, you're
as
busy as ever! thanks for the help,
Kelli
and we said...
Yes, the default accounts are setup on Solaris as well (and all
platforms).

SYS    = change_on_install
SYSTEM = manager

These defaults are setup in the sql.bsq file (found in
$ORACLE_HOME/dbs/sql.bsq for 7.x).  You can see this if you:

$ grep 'create user' sql.bsq
create user sys identified by change_on_install
create user system identified by manager

sql.bsq is the script that creates the data dictionary itself --
its the "bootstrap" sql file for the database.
July 20, 2000 E.J. -- Thanks for the question regarding "Returning resultsets from functions without defining a table type?", version 7.3.4.2
You Asked
Every method I've seen for returning a result set from a
function has involved creating a data type for each function
with a different result-set type.  For resultsets with large
amounts of columns (say approximately 30 in this case) this is
very very unwieldy (especially if you want to do it properly
using <tablename>.<columnname>%TYPE).  It also means if you have
several functions you end up having a lot of types to manage.

Is there a different and/or better way of doing this.  I long
for SQL Server/Sybase's ability to return the results of a
select statement from a procedure without any special handling
at all. :)

Thanks,
E.J. Wilburn
and we said...
Since 7.2 of the database, we've had this thing called a "ref
cursor".

See
http://osi.oracle.com/~tkyte/ResultSets/index.html
to read all about it.   It has examples for SQLPlus, Pro*C,
Java/JDBC, ODBC, ADO/ASP, and OCI.   Sorry it took so long for
you to find it, its what you are looking for.
Review & Followup
Rating: 4
Result Sets from Stored Procedures April 03, 2001
Reviewer: Armin Luetkenhaus from Germany
The page about "Result Sets from Stored Procedures In Oracle" was the first
*complete* ref cursor sample I found so far. (I would have expected something
like this in the Oracle manuals!) The OCI sample written by Brett Rosen was
exactly what I was looking for. Thanks, Tom and Brett!
http://osi.oracle.com/~tkyte/ResultSets/index.html

July 20, 2000 Phillip -- Thanks for the question regarding "Oracle 8.1.6 or Oracle 8.0.6: when migrating from earlier versions", version Oracle 8.1.6
You Asked
Oracle8i is the database for internet computing. When an old
Oracle database needs to be migrated, Oracle8i seems to be the
choice. Some applications have something to do with the
internet, whereas others do not. Should Oracle8i be used for
internet-related applications and Oracle8 for others? Will
Oracle8i completely replace Oracle8? If that is the case, all
Oracle8 applications have to be migrated again to Oracle8i. Are
there any white papers that cover this issue?
and we said...
No question about it 8.1.6 is the correct version to migrate
to.

Oracle8i is simply the marketing name for the next release of
Oracle -- the database.

There was Oracle7, release 7.3 (version 7.3.4)
There was Oracle8, release 8.0 (version 8.0.6)
There is Oracle8i, release 1 (8.1.5) and release 2 (8.1.6)

it would make sense to move to the latest release -- 8.1.6.  It
is just a natural progression.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
for a detailed break down of the features added by release.
Many dozens of 8i features (many many of them) are not
"internet" specific.
July 21, 2000 James -- Thanks for the question regarding "Can I simulate OPS using a single server?", version 8i
You Asked
Due to resource limitation, can I setup a OPS server on one
single server?  I'll install 8i and start a normal instance and
then migrate the instance to 2 instance and make use of the
original datafiles.

Best rgds
and we said...
You cannot setup OPS on a single machine however, you may
migrate a previously single instance Oracle to a multiple
instance Oracle.

See
http://technet.oracle.com/doc/oracle8i_816/paraserv.816/a76934/chap9.htm#1007068
for the details/considerations.
July 21, 2000 Onkar -- Thanks for the question regarding "Executing a Oracle stored procedure in MS SQLServer 7.0", version 8.0.5.0.0
You Asked
How to execute an Oracle stored procedure from MS SQLServer 7.0?
and we said...
OleDB is probably the answer.

See
http://technet.oracle.com/tech/nt/ole_db/
for more info.  It is part of 8.1.6.1 however it can be used to
access 7.x and 8.0 databases as well.
July 21, 2000 fernando -- Thanks for the question regarding "Using a Recordset in a Loop Statement ", version 5.0.6.22.0
You Asked
Hi Tom,

    I need to translate this sentence from Visual Basic to
Oracle Forms 5.0.6.22.0.

For Each fld In recset.Fields
             ...
Next fld

Where
    recset.Fields: it's a  collection that contains all stored
Field objects of a Recordset object.
    fld: it's a Field of the collection.

I've seen a similar sentence with a record from a cursor,

FOR record_name IN
 {  cursor_name [(cursor_parameter_name[,
      cursor_parameter_name]...)]
  | (select_statement)}
LOOP
   seq_of_statements
END LOOP [label_name];

 but I'm working with a recordset from a MapObjects OCX form
ESRI. Can it be done?

    Thank you very much.
and we said...
This functionality is available in the EXEC_SQL builtin package
in forms (DBMS_SQL on the server, use EXEC_SQL when in forms,
DBMS_SQL when in a stored procedure).

It allows you to iterate over rows by fetching them and to
iterate over columns using a positional index (eg: you can ask
for the i'th column of a given row).

Here is an example.  If I had a form with a block T and a text
item X (and X was sufficiently large), this would take all of
the rows in EMP and put a comma separate list of values into the
field :t.x

declare
  connection_id EXEC_SQL.CONNTYPE
                     default exec_sql.default_connection;
  cursorID      EXEC_SQL.CURSTYPE;

  nIgn        number;
  columnValue varchar2(4000);
  ncols       number;
  sep         varchar2(1);
  colName     varchar2(40);
  colLen      number;
  coltype     number;
  tmp         varchar2(20000);
BEGIN
  IF exec_sql.is_connected = FALSE THEN
    Message('No primary connection. Please connect.');
    RETURN;
  END IF;

  cursorID := EXEC_SQL.OPEN_CURSOR;
  EXEC_SQL.PARSE(cursorID, 'select * from emp', exec_sql.V7);
  nIgn := EXEC_SQL.EXECUTE(cursorID);

  for i in 1 .. 1000 loop
  begin
        exec_sql.describe_column( connection_id, cursorId, i,
                                    colName, colLen, colType );
        exec_sql.define_column(cursorID, i, columnValue,
                                  4000 );
    exception
          when exec_sql.invalid_column_number then
              ncols := i-1;
              exit;
     end;
  end loop;

  while (exec_sql.fetch_rows(cursorID) > 0)
  loop
        sep := '';
        for i in 1 .. ncols loop
             EXEC_SQL.COLUMN_VALUE(cursorID, i, columnValue);
             tmp := tmp || sep || columnValue;
         sep := ',';
        end loop;
        tmp := tmp || chr(13) || chr(10);
  END LOOP;

  EXEC_SQL.CLOSE_CURSOR(cursorID);
  EXEC_SQL.CLOSE_CONNECTION;
  :t.x := tmp;

END;
July 21, 2000 Rob -- Thanks for the question regarding "Long datatype is SQL*Plus -- how to move or copy a LONG field.", version 7.3.4.5.0
You Asked
Hi,

is there any way to select out the contents of a table that
includes a long to generate insert statements so that the
contents of the table can be inserted into another identicate
table in a different database?

I've tried this..

select 'insert into a_table (name,long_col) values ' ||
       '('''||name||''','''||long_col||''') ;'
from source_table
/

And I've also tried a PL/SQL select and dbms_output.put_line.
Neither of which work.

Cheers,

Rob
and we said...
See
http://osi.oracle.com/~tkyte/Misc/MoveLongs.html
for the answer.

full syntax of the command in 7.3 after you read the above is to
be found at:
http://technet.oracle.com/doc/server73x/SP33/ch6a.htm#toc054
...
July 21, 2000 Anwar -- Thanks for the question regarding "Database Roles", version 7.3.2
You Asked
Hi Tom,

In Oracle DB who owns database roles & why?
and we said...
No one owns them.  They are similar to user accounts.  They are
one of the few schema objects that do not have an owner.

When you create a role, it is automatically granted to you as a
default role with the ADMIN option.  If someone else revokes the
role from you -- you will not be able to drop it or do anything
with it (even though you created it, you don't "own" it)
July 21, 2000 Anwar -- Thanks for the question regarding "Date checking in DB Constraints", version 7.3.2
You Asked
Hi Tom,

I've seen nemerous examples quoting the use of 'sysdate' in
database check constraints but when I tried to do so an error
was returned? What is the problem with it?
and we said...
Its never been allowed:

ops$tkyte@DEV8I.WORLD> create table t ( x date check ( x >
sysdate ) );
create table t ( x date check ( x > sysdate ) )
                                    *
ERROR at line 1:
ORA-02436: date or system variable wrongly specified in CHECK
constraint

$ oerr ora 2436
02436, 00000, "date or system variable wrongly specified in
CHECK constraint"

*Cause:
 An attempt was made to use a date constant or system variable,
 such as USER, in a check constraint that was not completely
 specified in a CREATE TABLE or ALTER TABLE statement.  For
 example, a date was specified without the century.

*Action:
 Completely specify the date constant or system variable.

Can you point me to an example in the Oracle documentation that
shows otherwise?
July 21, 2000 Anwar -- Thanks for the question regarding "Tablespace Coalesce", version 7.3.2
You Asked
Hi Tom,

I've entered the following command to coalesce my 'users'
tablespace but it returned without any coalescing:

alter tablespace users coalesce;

What is the reason?
and we said...
Coalesce simply takes contigous free extents and makes them into
a single bigger free extent.

It is not a reorganization tool.  It is a command to take any
free extents that are right next to some other free extent and
make one bigger free extent out of them.  It is useful after a
drop command when you want to create another object right away.
SMON will normally perform this coalescing in the background but
if you need it to happen "right now", the coalesce command will
do it.

for example, the following query shows that in my database, my
system tablespace has 2 extents right next to eachother that
could be combined:

ops$tkyte@DEV8I.WORLD> select a.tablespace_name, a.file_id,
a.block_id, a.blocks, b.block_id
  2    from dba_free_space a, dba_free_space b
  3   where a.tablespace_name = 'SYSTEM'
  4     and b.tablespace_name = 'SYSTEM'
  5     and a.tablespace_name = b.tablespace_name
  6     and a.file_id = b.file_id
  7     and a.block_id+a.blocks = b.block_id
  8  /

TABLESPACE_NAME        FILE_ID   BLOCK_ID     BLOCKS   BLOCK_ID
------------------- ---------- ---------- ---------- ----------
SYSTEM                       1      66568          2      66570

So I coalesce it:

ops$tkyte@DEV8I.WORLD> alter tablespace system coalesce;
Tablespace altered.

And now I see the contigous extents have been merged

ops$tkyte@DEV8I.WORLD> select a.tablespace_name, a.file_id,
a.block_id, a.blocks, b.block_id
  2    from dba_free_space a, dba_free_space b
  3   where a.tablespace_name = 'SYSTEM'
  4     and b.tablespace_name = 'SYSTEM'
  5     and a.tablespace_name = b.tablespace_name
  6     and a.file_id = b.file_id
  7     and a.block_id+a.blocks = b.block_id
  8  /

no rows selected

ops$tkyte@DEV8I.WORLD>
July 21, 2000 Sushmita -- Thanks for the question regarding "Date format", version version 8.1.5
You Asked
Hi,

   Is there an eqivalent command of sleep() of C in oracle
,where the parameter is less than a second. can date be shown in
miliseconds in any format?

Thanks and regards,
Sushmita
and we said...
For the milliseconds question, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:341817437103
The dbms_lock.sleep command has a granularity of 1 second.  That
is the finest level of granularity provided.  Java can take it
down to milliseconds if need be in 8i.  For example:

create or replace
procedure micro_sleep( p_sleep in number )
as language java
name 'java.lang.Thread.sleep( long )';
/

Procedure created.

ops$tkyte@DEV8I.WORLD> declare
  2      l_start    number;
  3  begin
  4      for i in 1 .. 10
  5      loop
  6          l_start := dbms_utility.get_time;
  7          micro_sleep(100);
  8          dbms_output.put_line(
  9       to_char(round((dbms_utility.get_time-l_start)/100,2))
 10             || ' hsecs' );
 11      end loop;
 12  end;
 13  /
.11 hsecs
.11 hsecs
.11 hsecs
.11 hsecs
.11 hsecs
.11 hsecs
.11 hsecs
.11 hsecs
.11 hsecs
.11 hsecs

PL/SQL procedure successfully completed.
July 21, 2000 Dorothy -- Thanks for the question regarding "Custom datatypes", version Oracle 8i
You Asked
does Oracle have custom  or user defined datatypes  similar to
the Ingress custom datatypes ?
and we said...
Yes, see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c11ordb.htm#427515
for info on exactly that.  Read
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/toc.htm
for an entire overview of Oracle.


Subject | Article | Last Updated (East coast time)
comparing the date inJSP | article only | Jul 31, 2000 12:48 pm
RESIZE -- is it destructive. | article only | Jul 31, 2000 04:19 pm
Dynamic FETCH for a cursor variable | article only | Jul 31, 2000 05:57 pm
read only user | article only | Jul 31, 2000 07:34 pm
Oracle8i Personal Edition vs Oracle8i Enterprise Edition | article only | Jul 31, 2000 07:38 pm
Automating SQL script execution | article only | Jul 31, 2000 08:24 pm
how to copy/transmit a file of client to server machine in pl/sql | article only | Aug 01, 2000 06:54 am
Oracle Data Integrity -- do I need to use RAW files. | article only | Aug 01, 2000 06:56 am
How to set the user id in the browser | article only | Aug 01, 2000 06:59 am
MIgration -- where is the Access Migration Utility | article only | Aug 01, 2000 07:57 am
table nologging and redo /undo consumption | article only | Aug 01, 2000 04:22 pm
Install oracle client software on solaris 5.6 | article only | Aug 01, 2000 04:26 pm
configuration ORA-27146: post/wait initialization failed | article only | Aug 02, 2000 08:26 am
DBA/NET8 | article only | Aug 02, 2000 08:40 am
what is autobinding | article only | Aug 02, 2000 09:03 am
ORACLE Designer r.6.5 - what new we can expect | article only | Aug 02, 2000 09:33 am
How to compile a stored procedure without affecting other packages? | article only | Aug 02, 2000 10:13 am
How to do an incremental backup of a particular table? | article only | Aug 02, 2000 10:40 am
Oracle - MS-Access -- table names in mixed case. | article only | Aug 02, 2000 12:34 pm
How to tune this particular query. | article only | Aug 02, 2000 12:59 pm
What is it CRLOGDR utility ? | article only | Aug 02, 2000 06:32 pm
Which Options are better ? -- using table.column%type or "varchar2" | article only | Aug 02, 2000 07:23 pm
How to insert word "&" into database ? | article only | Aug 03, 2000 08:32 am
System Requirements of Designer 6i and DEveloper 6i | article only | Aug 03, 2000 08:51 am
Trigger on Blob-Fields | article only | Aug 03, 2000 09:16 am
mouse pointer | article only | Aug 03, 2000 09:24 am
looking for a script | article only | Aug 03, 2000 09:28 am
Confusion About Oracle_sid | article only | Aug 03, 2000 09:57 am
Database size | article only | Aug 03, 2000 11:41 am
Using Sqlplus and procesures in Korn Shell | article only | Aug 03, 2000 04:09 pm
Return Array to PL/SQL from Java | article only | Aug 03, 2000 08:22 pm
XA connections | article only | Aug 03, 2000 08:33 pm
Inserting a Date Value Into Oracle using JDBC | article only | Aug 04, 2000 09:25 am
Oracel D2K V2.1 integration with Btrieve database | article only | Aug 04, 2000 09:30 am
Import Export and the 2Gb file size limit | article only | Aug 04, 2000 10:33 am
Migrating from Intel to RISC based system | article only | Aug 04, 2000 10:35 am
Resource Requirements | article only | Aug 04, 2000 10:37 am
About Pl/Sql - getting result sets back. | article only | Aug 04, 2000 10:45 am
Communication between Oracle database and C++ client. | article only | Aug 04, 2000 01:08 pm
Size limit for disk space allocation to tablespaces | article only | Aug 04, 2000 02:37 pm
Oracle Account SYS, SYSTEM, INTERNAL and ORACLE (Unix) | article only | Aug 04, 2000 04:15 pm
row(s) 1 - 41 of 41
July 31, 2000 naulli -- Thanks for the question regarding "comparing the date inJSP ", version 3.1
You Asked
hi!!!
how to compare the date where i was type in the field level
in JSP?
the date not save into database yet.
if date1 > date2, error message prompt out
else
date1,date2 will save in the database
TQ
and we said...
couple of ways.

1) convert the input strings into Java dates and compare them.
Java dates can be compared.  eg:

   if date1.compareTo( date2 ) > 1
   {
       .....

2) convert the dates into integers of the format

   YYYYMMDDHH24MISS  (year, month, day, hour, minute, second)

   and simply use >, eg:

      if (date1 > date2)
      {
        .....

3) use a plsql block to compare them (not recommended, would be
a server roundtrip to the DB when its not really needed)....
July 31, 2000 Valentin Bernardo -- Thanks for the question regarding "RESIZE -- is it destructive.", version 7.3.3
You Asked
WHAT HAPPEND IF I WANT TO INCREASE A TABLESPACE WHIT THE
FOLLOWING COMMAND:

ALTER DATABASE <name database> DATAFILE '<.......>' RESIZE X M;

FOR EXAMPLE FROM 20M TO 50M.

THE COMMAND DESTROY THE DATA SAVED IN THE TABLESPACE
WHEN I INCREASE THE DATAFILE ? OR WHAT HAPPEND ?
I'M NOT SURE TO USE THIS WAY, I DON'T WANT TO DESTROY DATA IN
THE TABLESPACE.
and we said...
The correct syntax would be:

alter database datafile '/path/filename.dbf' resize 50m;

It will resize the file in a non-destructive fashion.  This
command can be used to either increase or (if possible) decrease
the size of a file.  It will not "destroy" existing data at all.
July 31, 2000 Tom -- Thanks for the question regarding "Dynamic FETCH for a cursor variable", version Oracle 8i
You Asked
I am trying to use a cursor variable to read 42 different tables
and create a flat file extract. I have mannaged to get this to
work by using an IF/THEN/ELSIF to determine which file I am
reading and I hard coded the FETCH statement exactly as I had
built it in a string variable. However, I can not seam to find a
way to use this string variable to execute the FETCH statement.

I have tried an EXECUTE IMMEDIATE string_variable; but I
received an invalid SQL statement. I would appreciate it if you
could give me some direction.

Thank you.
and we said...
I believe you are looking for:

  open p_cursor for string_variable;

for example:

ops$tkyte@8i> declare
  2      type rc is ref cursor;
  3
  4      l_cursor    rc;
  5      l_string    varchar2(255);
  6      l_dummy        dual.dummy%type;
  7  begin
  8      l_string := 'select * from dual';
  9
 10      open l_cursor for l_string;
 11
 12      loop
 13          fetch l_cursor into l_dummy;
 14          exit when l_cursor%notfound;
 15
 16          dbms_output.put_line( l_dummy );
 17      end loop;
 18
 19      close l_cursor;
 20  end;
 21  /
X

PL/SQL procedure successfully completed.

However, if you are creating the flat file from PLSQL using
UTL_FILE, an easier method might be a generic routine like my
dump_csv:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:235814350980
Or, if you have Pro*C (it'll be the fastest method) you can look
at:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:459020243348
as well.
July 31, 2000 sing -- Thanks for the question regarding "read only user", version 8.0.6
You Asked
Tom,

To create a read-only user is it enough to grant
user x :
object privilege : select on the object in question,
system privilege: connect to database?

Thanks,
Sung
and we said...
They do not need connect which might have more then you want.
They need only:

o create session

o select on whatever objects you want (or be granted a ROLE
  which has the correct select grants)

bear in mind, any privelege granted to PUBLIC will be theirs as
well.
July 31, 2000 diep -- Thanks for the question regarding "Oracle8i Personal Edition vs Oracle8i Enterprise Edition", version Oracle8i
You Asked
Dear Tom:

Would you kindly explain the difference (in term of database
features) between
Oracle8i Personal Edition on NT
and
Oracle8i Enterprise Edition on NT?

The only thing I know so far is that the Personal Edition was
designed for single user whereas the Enterprise Edition was
designed for multi-users (I am stuck on the how part!)

Thanks in advance for your help.
and we said...
Actually, Personal Edition and Enterprise edition are very much
the same pieces of code -- its mostly licensing issues (which
features/functions you have and are allowed to use).

You can review the functionality differences online at:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/ch4.htm#73594
...
July 31, 2000 Najmal -- Thanks for the question regarding "Automating SQL script execution", version 8.1.5
You Asked
Hi Tom,

I am using Oracle 8.1.5 on Solaris 2.6
How can I execute a SQL script in a particular time interval?.
I tried to put the job in UNIX cron tabs as root, but it didn't
work.
Is the environment variables causing the problem? Can I add cron
jobs
as Oracle user?

Please advice.

Thank You
Najmal
and we said...
You can use CRON, but you must remember that cron runs jobs in a
very very sparse environment.  You'll need to set your
Oracle_home, sid and so on.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:267815470945
for an example.

I would strongly recomment you not use ROOT to run these
jobs.  You should use some (any) other account to run them.
root is pretty powerful and shouldn't be used for such things.

Another option, if you can put all of your logic into a stored
procedure instead of a sqlplus script, is to use the job queues
in the database to automate the execution of recurring jobs.
See the dbms_job package (has the bonus that the jobs will only
run if the database is actually available).
August 01, 2000 ping -- Thanks for the question regarding "how to copy/transmit a file of client to server machine in pl/sql", version version 8i
You Asked
Dear:
 Now I'm developing a web page. it's software is :owas4.0.8.2+
oracle server8i+ digital unix. I wanna to copy/transmit a file
of client to the machine in which oracle server is installed,
then read the content of that file using "utl_file" package and
insert the content to a table of database. This procedure will
be programmed in pl/sql. But I don't know how to copy/transmit
that file of client to the server machine in a pl/sql procedure.
Someone told me that ifs can be used. But I don't know how to
do.
Thank you very much for your help.

best regards!
and we said...
iFS could be used but it would require the client to push the
file into the database (everything will).  I think you can do
this with OAS though.

We can use OAS 4.x to do a file upload from a web page into a
long raw in the database.

see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:242014628882
for setup details on that.

Once you have the file getting uploaded into the LONG RAW in the
database, you will want to convert it to a BLOB so you can use
DBMS_LOB.READ (in place of UTL_FILE) to piecewise read and
process the uploaded file.  To do that, we will:

create table my_lob_table( data blob );

And you will programatically insert into my_lob_table select
to_lob( the long raw columm ) from the content table OAS uses.
You can now select that blob out and use dbms_lob.read to parse
it (and then later delete the entry in my_lob_table and the
content services).
August 01, 2000 Vinod -- Thanks for the question regarding "Oracle Data Integrity -- do I need to use RAW files.", version Oracle 8.1.5
You Asked
Hi Tom,

Are RAW devices the only way to make sure that Oracle writes are
not cached by the OS?  If I dont use raw devices, am I in danger
of not being able to recover properly since LGWR and Oracle have
written but OS has not placed on disk?

Thanks for your help

Vinnie
and we said...
Feel free to use cooked files.  We open all files on O_SYNC mode
or the equivalent thereof on every OS.  You do not need to use
raw partitions (exceptions for Oracle Parallel Server -- which
runs on a cluster).

So, if you have a single instance Oracle on a single machine --
you need not consider raw if you don't want to.
August 01, 2000 KK -- Thanks for the question regarding "How to set the user id in the browser", version 4.0.8
You Asked
I've used the owa_custom.set_authorization(owa_sec.global) to
authenticate my users.  As I know, owa_sec.get_user_id can
return the user id to the procedure.

In my OAS application, I have a page which will require the
user to input a new login id, so can I use some functions
provided by OAS to put the new login id into the browser?

By the way, owa_sec.get_user_id return the user id from
the client side, where is the user id stored in the client side?
and we said...
You'll have to do that via cookies.  If you use BASIC
AUTHENTICATION, whereby the browser pops up a little window
(like
http://technet.oracle.com/
does), the browser will automagicially remember the
username/password for you.  If you are using your own page to
gather this information -- its up to you to remember it.  A
cookie is a popular way to do this.

see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:446620083639
for a roadmap to getting something like this going with
cookies.
August 01, 2000 Dilbagh -- Thanks for the question regarding "MIgration -- where is the Access Migration Utility", version 8.0.6
You Asked
Tom, one of my friend has installed "MSAccess migration utility"
along with oracle install on PC. I am looking for same utility
by itself for migrating MS Access database to oracle 8. Could
you tell me where to download this utility from.

Thanks
and we said...
Sure, see
http://technet.oracle.com/software/tech/migration/workbench/software_index.htm
for that.
August 01, 2000 ted -- Thanks for the question regarding "table nologging and redo /undo consumption", version 8i
You Asked
thomas,

If a table is altered with nologging option, would subsequent
delete/update consumes less redo/undo (similar to direct insert)
? I posted this question at deja and some people tells me yes.
when I did test found from v$sysstat, there is no difference in
redosize, redo writes and redo blocks written before and after
'alter table nologging;.

thnx in advance,
ted chyn
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:366018048216
for more info.  The very very short answer is NO.

Normal inserts/updates/deletes on the table are logged as
normal.  nologging only affects certain operations like direct
path loads and such on the object.
August 01, 2000 sing -- Thanks for the question regarding "Install oracle client software on solaris 5.6", version 8.0.6.0.1
You Asked
Tom ,

Could you please direct to me to the documentation for
installing oracle client software on  sun solaris 5.6 ?

THanks,
Sing
and we said...
the installation guides (and all 8.0 documentation) is at:
http://@technet.oracle.com/docs/products/oracle8/doc_index.htm
...
August 02, 2000 wallacel -- Thanks for the question regarding "configuration ORA-27146: post/wait initialization failed", version 8.1.6
You Asked
I shutdown my oracle server.
make some modification to init.ora file.
and then when i startup it, it give me error message:
ora-27146 post/wait initialization failed.

and then i check the file in udump and found following message:

ksedmp: internal or fatal error
ORA-27146: post/wait initialization failed
ORA-27300: OS system dependent operation:semget failed with
status: 28
ORA-27301: OS failure message: No space left on device
ORA-27302: failure occurred at: sskgpcreates

I think the reason why it can't startup is because i increase
the
value for db_block_buffer,db_files,shared_pool_size etc,
after i decrease a little bit, everything works fine.
my question is:
1.actually our server have 6G memory, and my SGA configuration
only use something like 900M, why it can't increase anymore?
well, it is ttue that this server also have
some other program runing, but i think it will not need much
memory.
2. how do i know how much memory are available for me in our
server after serveral other program runing?

Thanks,
and we said...
You need to increase your OS kernel settings for semaphores.
You don't mention an OS so I cannot be very specific.

In Solaris, I would be editing my /etc/system file and setting
parameters such as:

set shmsys:shminfo_shmmax=4294967295
set shmsys:shminfo_shmmin=1
set shmsys:shminfo_shmmni=100
set shmsys:shminfo_shmseg=10

set semsys:seminfo_semmni=500
set semsys:seminfo_semmsl=500
set semsys:seminfo_semmns=500
set semsys:seminfo_semopm=500
set semsys:seminfo_semvmx=32767
set semsys:seminfo_semmap=250
set semsys:seminfo_semmnu=500
set semsys:seminfo_semume=100

See the OS Install guide for your platform for specifics.  See
also
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:454420165038
for guidelines
Review & Followup
Rating: 4
Share memory and Semaphores on HP UX platform March 20, 2001
Reviewer: Yu Dong from Canada
Very good answer. But what about HP UX platform? My server has 3 GB physical
memory, for an application used by 300 concurrent users, with DB size about 30
GB, so SHMMMAX should be 3 GB, but what about SHMMIN, SHMMNI, SHMSEG and those
about Semaphores (SEMMNI,SEMMNS)? An estimate on these would be a great guidance
for my confirguation.

August 02, 2000 Sankalp -- Thanks for the question regarding "DBA/NET8", version 8.x
You Asked
My table A is
                  ID number,
                  USERNAME varchar2(16)

ID - primary key constraint, with a sequence attached to it.
USERNAME - unique constraint

My table B is
             USERNAME    varchar2(16) - primary key.

Consider the both tables to have 1000 or more records.

Question A) : Which of the two tables when queried, will produce
faster results?Also, from the system analyst point of view, will
he  go for the table A structure as it has a waste column in ID
?
Also, on a DBA point of view, can u tell me which one is better
tuned??

QUESTION B)
Also, in Net8, we have the concept of SERVICES. Can u tell
me/give me the exact defiition of what SERVICES are? Are they
separate executable files or what.

Thanks in advance
SANKALP
and we said...
Question a) both will perform about the same.  I assume you
would be using a query such as

  select * from T where username = SOMENAME

they would use the index and get the row.  the existence (or
lack thereof) of a single number column will not materially
affect this operation.

Whether ID is a "waste" or not is quite subjective.  Lets say
USERNAME is a field that could change (eg: someone gets married
-- their username changes, happens all of the time).  Username
is not a good candidate for a primary key as primary keys
should never change especially if they are foreign keys in
other objects.  In this case, the schema using a surrogate key
ID is "more correct".  You are free to change the username at
will but the ID (which is stored in other tables as a foreign
key) will not change.

So -- it depends more on the nature of the USERNAME column then
anything else.  If ever there is a chance you might update that
column -- ID will be very very useful and save you lots of
trouble.

Question B)

See
http://technet.oracle.com/doc/server.815/a68020/ch2.htm#140388
for a description of what a service is.
August 02, 2000 Eric -- Thanks for the question regarding "what is autobinding", version 8.1.6.1.0
You Asked
Tom,

in
http://osi.oracle.com/wa/ask/owa/ask_tom_pkg.display?p_dispid=299616457737

you briefly mention the autobinding feature:

"[...] In 8.1.6, there is a new "autobinding" feature.
Applications, including many packaged applications, that use
literals instead of bind variables in SQL can see improved
performance because release 8.1.6 can automatically substitute
bind variables in place of the literal values. This lets
multiple users share the parsed SQL regardless of the literal
value, dramatically reducing the SQL parse time and saving
memory in these applications."

Could you give me more information or URL on it (I failed
to find resources about it). Does it always work ?
(if not, on which kind of query can it be efficient ?)

best regards and thanks *a lot* for your tips,
it is a great source of knowldege for us.
eric
and we said...
Sure, see
http://technet.oracle.com/docs/products/oracle8i/doc_index.htm
it describes the parameter CURSOR_SHARING and its settings of
EXACT and FORCE.  It also outlines when you might want to (or
not) use this feature.
August 02, 2000 Dusan -- Thanks for the question regarding "ORACLE Designer r.6.5 - what new we can expect", version 8.1.5
You Asked
Hi Tom,

I am using ORACLE Designer tools, currently r6.0. I have heard
that the new version will have some changes and news.
Currently we can generate modules basicaly to Forms 6 and Web
server, but there are another ORACLE products like jDeveloper
and WebDB. Will the generators for these products be available
in new version(s)of ORACLE Designer?

cheers,

Dusan Valasek
and we said...
The answer to the generators question is no -- Designer 6.5 will
not have any new generators for them.  As for "whats new" in
6.5, you can review:
http://osi.oracle.com/~tkyte/65newfeatures.pdf
it gives an overview of whats new.
August 02, 2000 Jesse -- Thanks for the question regarding "How to compile a stored procedure without affecting other packages?", version Oracle8.0.5/Sun OS
You Asked
Hi Tom,
I use stored procedure in the application for the ease of
control
and maintenance. But I found out that whenever I made changes to
package A will affect the other packages which call the
procedures/
functions in package A.
Eg.
Error messages defined in package errhndlr. A procedure called
prn_errmsg
is defined and the error messages are defined as constants, eg:
Errmsg(err_invalid_usr) := 'Invalid User!'

If I would like to modify this constant to be more informative,
I
need to recompile the whole package. Since most of the packages
call prn_errmsg, I need to recompile all the packages too!
Is there anyway I can recompile package errhndlr without
recompile
other packages. If not, is there any better programming way to
reduce the dependency?

Thank you in advance.

Regards,
Hwee
and we said...
Well, in your case -- if the constant you want to modify is in
the PACKAGE SPECIFICATION -- then all dependent pieces of code
must by definition be invalidated.  If on the other hand, the
spec does not change and only the BODY needs to be recompiled --
then the depenedent packages will not

see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:286816015990
for a discussion of this feature.

If the specification of the package is recompiled, there is no
avoiding the cascading invalidations -- the other code must be
recompiled -- you've changed the interface they depend on.

So, as long as the changes are contained in the BODY of the
package and you only recompile the body -- nothing else will
become invalid.
August 02, 2000 Jesse -- Thanks for the question regarding "How to do an incremental backup of a particular table?", version Oracle8.0.5/Sun OS
You Asked
Hi Tom,
Oracle enable logical backup of a table using Export utility.
However
the option incremental backup only enabled for FULL database
mode.
Is there anyway I can do an incremental backup of a table?
Thank you.
Regards,
Jesse
and we said...
Not using EXPORT.  An incremental export exports FULL TABLES (if
1 row in a 1billion row table was altered -- export will get the
entire table).

Export is not a good backup tool.  It can only do a point in
time picture of some data.

Backups are done via the server.  If you are using RMAN
(recovery manager) it is fully capable of doing incremental
backups (true incremental backups) whereby only blocks that have
changed are backed up.

See
http://technet.oracle.com/doc/server.804/a58396/ch7.htm#423978
for more info.
August 02, 2000 Seetharaman -- Thanks for the question regarding "Oracle - MS-Access -- table names in mixed case.", version 8.0.5
You Asked
Hi Tom,

  Greetings!..

  Hope you enjoyed your vacation.  Good to see your replies
back.

  I have created a table in MS Access and while importing it
into Oracle DB I gave the table name in InitCap way ie. like --
"UserEntered".  Now i want to drop the table from Oracle DB.
Since it is in cap/small types not able to delete it.  How to
proceed it?..

  Thanks in advance

regards

Seetharaman Srinivasan
and we said...
To manipulate objects that contain special characters or mixed
case, you simply use quoted identifiers.  In your case:

SQL> drop table "UserEntered";

will do it.
August 02, 2000 Scott -- Thanks for the question regarding "How to tune this particular query.", version 8.0.4
You Asked
I am trying to get the first description from the sesion_sv view
in this query.  It is very slow! is there a better way to write
the join that is more efficient?

SELECT FC.Problem_ID, S2.Description FROM
(SELECT UNIQUE P1.Problem_ID, MIN(S1.Call_ID) FIRST_CALL
 FROM   exav.problems_sv P1,
       exav.sesion_sv S1
 WHERE  P1.CLOSE_DATE IS NULL
        AND P1.Problem_ID = S1.Problem_ID
 GROUP BY P1.Problem_ID) FC,
exav.sesion_sv S2
WHERE FC.First_Call = S2.Call_ID
and we said...
Well, for starters -- you can lose the UNIQUE in the first
subquery -- its not necessary (the group by will unique it for
you -- you are just redoing whats already by done).

What might work better is something like:

select p1.problem_id, s2.description
  from exav.sesion_sv   S1,
       exav.problems_sv P1
 WHERE P1.CLOSE_DATE IS NULL
   AND P1.Problem_ID = S1.Problem_ID
   AND S1.Call_id = ( select min(S2.call_id)
                        from exav.sesion_sv S2
                       where S2.problem_id = P1.PROBLEM_ID )
/

Here is my take on how that query will be processed:

o a full scan on P1 will occurr since you have CLOSE_DATE is
  NULL and NULLS are not indexed (unless you have a bitmap index

  in which case we would use that index perhaps to find these
  rows)

o for each row in the above -- we will join to all rows in S1
  for that problem_id.  If you have an index on
  SESION_SV.PROBLEM_ID that would be good (even better -- an
  index on (PROBLEM_ID,CALL_ID) so we can avoid lots of table
  access by rowids in the subquery!

  We'll only keep the row with the MIN(CALL_ID) for that
  PROBLEM_ID.

This is one case where you might consider not using NULLS.  If
instead of having a NULL in close_date -- you had some date that
is impossible (i use to_date( '01/01/0001', 'dd/mm/yyyy' )
myself), we could code:

select p1.problem_id, s2.description
  from exav.sesion_sv   S1,
       exav.problems_sv P1
 WHERE P1.CLOSE_DATE = to_date('01/01/0001', 'dd/mm/yyyy' )
   AND P1.Problem_ID = S1.Problem_ID
   AND S1.Call_id = ( select min(S2.call_id)
                        from exav.sesion_sv S2
                       where S2.problem_id = P1.PROBLEM_ID )
/

instead and use a conventional b*tree index on p1(close_date) to
avoid the full scan on P1.
August 02, 2000 Ruben -- Thanks for the question regarding "What is it CRLOGDR utility ?", version Version 8.1.5
You Asked
Hi, Tom

Greetings ..!!

I´ve seen this in an Oracle DBA quiz, I had never seen this type
of utility, I have not found nothing seems like this both in OTN
or in Oracle documentation and manuals.
Can you explain me how it works, or when can I find it ???

Thank you a lot in advance.
and we said...
Its a fairly obscure utility  -- it is specific to NT, and even
then specific to OPS (parallel server) on NT.

See
http://technet.oracle.com/doc/oracle8i_816/nt.816/a73025/manage.htm#1006415
for info.

<quote>
The CRLOGDR utility enables you to create and delete logical
drives and their associated symbolic names on a disk that does
not have a primary partition and has only one extended
partition.
</quote>
August 02, 2000 -- Thanks for the question regarding "Which Options are better ? -- using table.column%type or "varchar2"", version 8.1.5
You Asked
While Creating PL/SQL package(or Procedure), which is better
option when declaring Input parameters with known data types or
to anchor with a table interms of performance and memory
allocations ?

eg.  deptno   IN Varchar2
  or deptno   IN dept.departmentno%TYPE (We are very much pretty
sure datatype wont be altered )

Second Question is about OAS Setup.

Which is most suitable option with OAS regarding listeners
config whether to go for OAS listeners or to go for external
listeners (like Netscape or Microsoft ) ?

thanks in adv.
and we said...
For the first question -- its a matter of style.  I rarely use
te table.column%type myself but others use it all of the time.
I do use table%rowtype frequently though -- thats a real
timesaver.

I guess technically speaking -- the second method is "better".
It provides more information and in the event the datatype does
change -- or the column disappears -- the trickle down effect
will happen and things that need to will recompile (or not if
they cannot anymore -- meaning that column you just dropped was
really needed!)

The second question is a matter of preference as well -- we are
switching to Apache as the webserver of choice (see
http://www.oracle.com/ip/deploy/ias/index.html
for more info).  You should use whatever you feel comfortable
with.  I've personally never used either of Netscape or MSIIE so
cannot comment on them.
August 03, 2000 zhu -- Thanks for the question regarding "How to insert word "&" into database ?", version version 8.1.5
You Asked
When I want insert a string that include the word "&" into a
column, the string after the word "&" have lost , How can I do
to
keep the whole string ? Thank you .
and we said...
if you issue

SQL> set define off

The ampersand will not be a "special" character anymore.
August 03, 2000 Jean-Marc -- Thanks for the question regarding "System Requirements of Designer 6i and DEveloper 6i", version Designer 6i
You Asked
Hi Tom,

A. I am looking for information on the minimum system
requirements for using:-
1. Designer 6i
2. Developer 6i.
together with the requirement database platform of Oracle.

THanks You.

Jean-Marc
and we said...
for 1a, see
http://technet.oracle.com/doc/des6i/doc/deshlp72/des2k_insgde/dsgnr_igttl_65.htm
and specifically
http://technet.oracle.com/doc/des6i/doc/deshlp72/des2k_insgde/dsgnr_igch1_65.htm#SystemRequirements

for 2a, see
http://technet.oracle.com/docs/products/forms/doc_index.htm
and get the pdf file "Oracle Forms Developer Release 6i: Getting
Started for Windows".  Chapter 1.2 outlines the requirements.
August 03, 2000 Naether -- Thanks for the question regarding "Trigger on Blob-Fields ", version 8.0.5
You Asked
Hallo Tom,

I 'd like to use a trigger in Oracle as follows :

   1. there is a Blob-Field in the triggered table
   2. in case of Updating the Blob-Field by any user-action
      the fiered Update-trigger makes a copy of the Blob to
      an other Blob in an other table

I use this kind of trigger-action with "normal" Fields for
a long time. Now I need that feature for the blobs too -
but it seems it is very difficult.

I could not found terms as: new.Blobfieldname,
:old.Blobfieldname ...

I could not give a Blobfield in the trigger-observed FieldList
...

How can I make it ?

Greetings from Dresden, Andreas Näther
and we said...
Well, this is a sticky issue (i think we can solve it though).
The problem is two fold:

o Triggers are not supported on LOBs. However, you can use a LOB
in the body of a trigger as follows:

- in regular triggers old values may be read but not written and
new values may not be read nor written.
- in 'instead of triggers', the:old and:new values can be read
but not written.

o dbms_lob.write (and other dbms_lob calls) do not fire a
trigger -- people can and will change the value of a blob and
you will not be able to detect it with a trigger.  In order to
update a LOB, I might never issue an UPDATE.

Now, if you want to copy the blob to another table -- we can use
snapshots to copy the data.  This can be accomplished via basic
replication.  See the Oracle8 server replication guide.
August 03, 2000 Shrikanth -- Thanks for the question regarding "mouse pointer", version 5.0
You Asked
how to change the mouse pointer in forms 5.0 at runtime, is
there any way

thanx
shrikanth
and we said...
you will call:

SET_APPLICATION_PROPERTY
  (property  NUMBER,
   value     VARCHAR2)

with a property of CURSOR_STYLE and a value of:

BUSY         Displays a GUI-specific busy symbol.
CROSSHAIR    Displays a GUI-specific crosshair symbol.
DEFAULT      Displays a GUI-specific arrow symbol.
HELP         Displays a GUI-specific help symbol.
INSERTION    Displays a GUI-specific insertion symbol.
August 03, 2000 saida -- Thanks for the question regarding "looking for a script", version 8
You Asked
hi Tom,

I need a script where it can page/phone me whenever is something
wrong with my database. And also i need same sample of scripts
too. I'm using NT.  thank you
and we said...
Thats what OEM (enterprise manager) does
http://www.oracle.com/take_control/index.html?oem.html
for more info.
August 03, 2000 Ravinder -- Thanks for the question regarding "Confusion About Oracle_sid", version 8.1.6
You Asked
Hi Tom,

I have most of my experience on Unix. And this the first time, I
got a chance to work on Windows NT. I am preparing for my OCP
certification (Oracle 8 DBA) and I am using the CBT CD provided
by Oracle/NETG.

At one stage this CD says that

instance name specified in the ORACLE_SID parameter should be a
maximum of 4 characters in Windows NT and eight characters in
Unix.

I agree with the Unix view of 8 characters, But I have confusion
for Windows NT 4 characters instance name in ORACLE_SID
parameter.

I am running a database on Win NT and the sid name is of 7
characters and I havn't faced any problem. i.e totally against
what the CBT CD says. May be this is allowed in Oracle 8i and it
was not allowed in Oracle 8.0.4.

Still a confusion, Can you please clarify this.

Thanks in Advance

Ravi
and we said...
On NT the SID should consist of four or fewer alphanumeric
characters. This is to avoid problems with filename length
restrictions on some platforms, e.g. the 8.3 restriction on DOS,
which is still present on NT if using DOS-style names (which
Oracle requires). So the initialisation file for a database
called ORCL will be called initORCL.ora, representing the
longest possible filename.

Actually, straight out of the 8.1.6 Solaris install guide:

ORACLE_SID
Specifies the Oracle system identifier, or sid, which is the
name of the Oracle Server instance. Because the sid is
incorporated into many filenames, Oracle Corporation recommends
restricting it to no more than four characters to avoid
filename problems on heterogeneous systems.

Although in the Solaris Admin guide it does also say:

ORACLE_SID
Function: Specifies the Oracle System Identifier.
Syntax:   The string of numbers and characters that must begin
with a letter. A maximum of eight characters is recommended. For
more information, see the Oracle8i Installation Guide for Sun
SPARC Solaris.
Example:  SAL1
August 03, 2000 Abhijit -- Thanks for the question regarding "Database size", version 8.1.5
You Asked
Could you please explain me how to decide total size of the
Oracle database?
and we said...
How to "decide" or how to "find".

How to "decide" is a function of what you are going to put in
there. See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:302216525000
for some pointers.

How to "find" -- thats a query:

--------------------------------------------------------
-- free.sql
--
-- This SQL Plus script lists freespace by tablespace
--------------------------------------------------------

column dummy noprint
column  pct_used format 999.9       heading "%|Used"
column  name    format a16      heading "Tablespace Name"
column  Kbytes   format 999,999,999    heading "KBytes"
column  used    format 999,999,999   heading "Used"
column  free    format 999,999,999  heading "Free"
column  largest    format 999,999,999  heading "Largest"
column  max_size format 999,999,999 heading "MaxPoss|Kbytes"
column  pct_max_used format 999.9       heading "%|Max|Used"
break   on report
compute sum of kbytes on report
compute sum of free on report
compute sum of used on report

select nvl(b.tablespace_name,
             nvl(a.tablespace_name,'UNKOWN')) name,
       kbytes_alloc kbytes,
       kbytes_alloc-nvl(kbytes_free,0) used,
       nvl(kbytes_free,0) free,
       ((kbytes_alloc-nvl(kbytes_free,0))/
                          kbytes_alloc)*100 pct_used,
       nvl(largest,0) largest,
       nvl(kbytes_max,kbytes_alloc) Max_Size,
       decode( kbytes_max, 0, 0, (kbytes_alloc/kbytes_max)*100)
                    pct_max_used
from ( select sum(bytes)/1024 Kbytes_free,
              max(bytes)/1024 largest,
              tablespace_name
       from  sys.dba_free_space
       group by tablespace_name ) a,
     ( select sum(bytes)/1024 Kbytes_alloc,
              sum(maxbytes)/1024 Kbytes_max,
              tablespace_name
       from sys.dba_data_files
       group by tablespace_name )b
where a.tablespace_name (+) = b.tablespace_name
order by &1
/

Run that script as

SQL> @free 1

and it'll show you the space allocated, used, largest free
extent, maxsize it could grow to and so on.
August 03, 2000 Santhosh -- Thanks for the question regarding "Using Sqlplus and procesures in Korn Shell", version 8.1.5
You Asked
How can i use korn shell to invoke
0. A Cron job which does step connects to Sqlplus to login as
dba user and execute a procedure which transfers data from
several schemas to single ascii file. and
Thanks
.
and we said...
Something like:

#!/bin/ksh
#
#

export ORACLE_SID=ora8i
export ORACLE_HOME=/export/home/oracle8i
export PATH=$ORACLE_HOME/bin:/usr/local/bin:/usr.....

sqlplus -s / <<EOF
        set pages 0 echo off verify off feed off term off
        spool /tmp/foo.lst
        select * from user1.T;
        select * from user2.t;
        select * from user3.t;
        spool off
        exit
EOF
August 03, 2000 Thad -- Thanks for the question regarding "Return Array to PL/SQL from Java", version Oracle8i Enterprise Edition Release 8.1.6.0.0 - Production; PL/SQL Release 8.1.6.0.0 - Production; CORE 8.1.6.0.0 Production; TNS for IBM/AIX RISC System/6000: Version 8.1.6.0.0 - Production; NLSRTL Version 3.4.0.0.0 - Production
You Asked
I've noted lots of discussion about populating a Java array from
a Java program making a call to Oracle, but nothing about
populating a PL/SQL array type based on a PL/SQL program calling
a Java stored procedure.

As an oversimplified example, consider the following Java class:

public class TestArrays {
    public static String[] getArray() {
        String[] test = new String[3];
        test[0] = "one";
        test[1] = "two";
        test[2] = "three";
        return test;
    }
}

What I want to do is call the Java method TestArrays.getArrays()
from PL/SQL and return the Java array to a PL/SQL table or
varray. I've been successful returning scalar types to PL/SQL
from Java but am stuck on arrays. Is it possible? Thanks in
advance for your time and consideration.
and we said...
You need to use object types (nested table collections or
varrays) to accomplish this.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:331217279811
for an example (this example is JAVA recieving an ARRAY from
PLSQL -- going the other way is very similar) and pointers to
the documentation on this.
August 03, 2000 Michael -- Thanks for the question regarding "XA connections", version 8.0.5
You Asked
Can a single thread open XA connections to multiple Oracle
instances at the same time and then use the "EXEC SQL ... AT"
syntax to disambiguate between them?
and we said...
Yes, see
http://technet.oracle.com/doc/server.804/a58241/ch_xa.htm#2454
for the details on this.
August 04, 2000 Vladimir -- Thanks for the question regarding "Inserting a Date Value Into Oracle using JDBC", version Oracle 8i
You Asked
PROBLEM DESCRIPTION

I have an Oracle table and one of it's columns has a Date
datatype. In my program I have a Date object. I want to place
the value of the Date object into the Oracle table.

THE APPROACH I HAD IN MIND

I thought I'd use the "DateFormat.getDateTimeInstance(...)" to
convert the Date object into a String object.  I then thought I
would use the oracle "TO_DATE" along with this String in the SQL
UPDATE statement.

TWO ISSUES
FIRST - I don't know how to get
"DateFormat.getDateTimeInstance(...)"  to produce a time in 24
hour format. (i.e. 2:00 pm => 14:00). This is important as I
must distinguish between 2am & 2 pm.

SECOND - Is there an easier way to do this? I get the feeling
there must be a simpler way to store a Date into an Oracle DB
using JDBC.

Any help would be appreciated.
and we said...
There are lots of ways to do it  -- I myself prefer the
TO_DATE/TO_CHAR method.  I get all dates from the database in a
STRING and I send them as a STRING.  The date format I use on
the way IN and OUT is:

     'yyyy/mm/dd hh24:mi:ss'

The functions I generally use are:

  static public java.util.Date strToDate(String s)
  {
    java.util.Date   d   = null;

    if (s != null && s.length() == 19 )
    {
      d = new java.util.Date(
                   Integer.parseInt(s.substring(0,4)) - 1900,
                   Integer.parseInt(s.substring(5,7)) - 1,
                   Integer.parseInt(s.substring(8,10)),
                   Integer.parseInt(s.substring(11,13)),
                   Integer.parseInt(s.substring(14,16)),
                   Integer.parseInt(s.substring(17,19)));
    }
    return d;
  }

  static public String dateStr( java.util.Date x )
  {
    if ( x != null )
      return (x.getYear()+1900) + "/" +
             (x.getMonth()+1) + "/" +
             x.getDate() + " " +
             x.getHours() + ":" +
             x.getMinutes() + ":" +
             x.getSeconds();
    else
      return null;
  }

You can also simply:

ResultSet rset = stmt.executeQuery("select DATECOL from TABLE");

while rset.next()
{
  //get the date data
  java.sql.Date date = rset.getDate(1);
  ....
Review & Followup
Rating: 5
Good ideas on handling datatypes April 05, 2001
Reviewer: Harrison Picot from Haymarket, VA USA
If you are working with JSP (and I am) mapping datatypes seems like a huge pain
and this helps figure it all out.

August 04, 2000 Rahul -- Thanks for the question regarding "Oracel D2K V2.1 integration with Btrieve database", version 2.1
You Asked
Dear Tom,
  We have a product developed on Oracle8 and Front End D2k V2.1.
We want to integrate our application with an existing
application running on Btrieve database. (ie with the table
structures loaded on
Btrieve database)
Please let us know how to go about it?
Regards
Rahul
and we said...
does btrieve support ODBC?

see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:218213305850
for more info.
August 04, 2000 David -- Thanks for the question regarding "Import Export and the 2Gb file size limit", version 8.0.5.2.1
You Asked
Tom,
    we are planning to migrate and tune a data warehouse
instance to a new environment where we will modify and benchmark
with different values of disk stripe width and DB_BLOCK_SIZE. As
we will have to re-load the data after each database build (4
are planned) I thought that using EXPORT/IMPORT would be the
most efficient in terms of CPU usage and network traffic.
However I can’t find anything in the literature about how export
deals with the Unix file size restriction of 2Gb. Exporting in
Table mode is not an option to get round this as the largest
table currently stands at 14Gb and contains 140 million records?
 Do you know the behaviour of export in these circumstances?
Also, I am assuming that importing into a database with a
different DB_BLOCK_SIZE and disk stripe width is supported but
again nothing in the documentation to support or contradict this
assumption. Any advice on this?

    If EXPORT/IMPORT is not feasible which of the following
options would you go with?
A) Export to tape – Problem speed
B) Pull data over database link – Problem repeated CPU and
network usage
C) Select to pipe file which is being SQL*Loaded from – Problem
repeated CPU and network usage

Any input gratefully received.

Regards,

David.
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:32412348052
for how to export a really large export (i use compress and
split).  In Oracle8i, you can specify a filesize= parameter as
well with export (doesn't help you in 8.0 but its something
thats coming) and export will break the output files up.

Now, What I would probably do in this case though is actually a
table by table export if the tables are so large.  That would
let me import in parallel on the recieving machine.  I might do
an export with rows = n and do a "structural" import (just
creates the schemas).  Then, I would drop the indexes and import
the tables (many at one time -- (each coming from a separate dmp
file that was created with indexes=n and so on) -- coming back
later to use parallel index creates on the tables.  Otherwise
the exp/imp might take a very very long time.
August 04, 2000 Satyajit -- Thanks for the question regarding "Migrating from Intel to RISC based system", version 7.3.0.2
You Asked
We are developing a system(Oracle 7.3.0.2 on SCO open Server 5)
an on Intel based server(IBM Netfinity 3500).Will it be possible

to port this application on a RISC based Server/platform when in

the Production environment?
and we said...
Yes, absolutely. The only portion I cannot tell you if it will
"port" or not is any applications you develop on the server
outside of the database (eg: any scripts, C programs, whatever
you create on the SCO box).

All of the database stuff will go onto any other machine with
Oracle unchanged.
August 04, 2000 Amanda -- Thanks for the question regarding "Resource Requirements", version 8.0.5
You Asked
Are there any matrixes to show resource requirements for Oracle
8 on Unix?
and we said...
The install guide has the system requirements.  For solaris for
example, you can read it at:
http://technet.oracle.com/docs/products/oracle8i/doc_index.htm
....
August 04, 2000 suresh -- Thanks for the question regarding "About Pl/Sql - getting result sets back.", version 8.1.5
You Asked
Hi Tom,
  Can we return more than one record at a time from oracle to
front
end (JSP) using Pl/Sql? I know that at a time we can return
1 record. If possible how can we return group of records from
pl/sql
Give me an example please!
Thanking You.
Suresh
and we said...
see
http://osi.oracle.com/~tkyte/ResultSets/index.html
for how to do that.
August 04, 2000 Piali -- Thanks for the question regarding "Communication between Oracle database and C++ client.", version Oracle 8i Release 8.1.6.0.0
You Asked
Hi Tom,
I am developing an application where C++ is client and Oracle is
the backend. I know I can use ADO and OraOleDB to pass result
sets from server to client. But in this application instead of
result sets I want to pass the output of same query as XML
(which is generated using XSU – xmlgen). I don’t want to pass it
as a .XML file. I want that client application should be able to
read that XML output from the memory. So is there any way to
pass XML output from server’s memory to client’s memory?

Regards
Piali.
and we said...
Install the PLSQL portion of the toolkit, then you can simply
execute:

select xmlgen.getXML('select * from all_Tables where
owner=''SCOTT''') from dual;

and retrieve the CLOB back into your C++ routine.
August 04, 2000 Shawn -- Thanks for the question regarding "Size limit for disk space allocation to tablespaces", version 8.1.6
You Asked
As with any 32-bit environment, the largest addressable size for
a file or logical volume is 2GB.  When using 8.1.6 for Solaris
7, does the 64-bit environment allow for larger files and/or
logical volumes when assigning disk space to tablespaces?
and we said...
Large file support was added to Oracle8.0 and up (on 32bit
platforms).  We do not require a 64bit OS to do this -- just
large file support with the OS (I believe that was 2.6 solaris
but it might have been 2.5.x).

With 8.1.6 on 2.7 -- you can exceed 2 gig.  Make sure your
BACKUP tool can handle that as well (whatever your are using...)

See page 1-15 of the Install Guide for Solaris on
http://technet.oracle.com/docs/products/oracle8i/doc_index.htm
for more info.
August 04, 2000 Leon -- Thanks for the question regarding "Oracle Account SYS, SYSTEM, INTERNAL and ORACLE (Unix)", version 7.3
You Asked
Tom,

What is the difference among these Oracle database
accounts in term of database administration or their
roles and functionality? Some examples in Oracle DBA
training material and other Oracle books show using
SYS or SYSTEM or INTERNAL for the same management task.
This confuses me. Can you give me more explanation on
when to use different account (SYS, SYSTEM, INTERNAL)
(ORACLE account at server side like Unix) for various
DBA tasks.

Thanks,

Leon,
and we said...
SYS and INTERNAL are synonymous.  SYS should only be used
administatively.  SYS (and internal) is special.  You cannot
create a trigger on a SYS table, you cannot have a read only
transaction as SYS and so on.

SYSTEM is simply an account that holds some data dictionary
tables/views (not many) and is a DBA.  SYSTEM is a "regular"
user -- nothing special about it.

Use SYS/internal as little as possible, I never use system for
anything (Oracle software might use it now and again to install
some tables/run some scripts but thats it).  Create your own DBA
accounts.


Subject | Article | Last Updated (East coast time)
Split block Concepts -- fractured block | article only | Aug 05, 2000 11:12 am
Max datafile size for 8.1.6.1.1 db on NT4? | article only | Aug 05, 2000 11:44 am
Storedprocedures from Oracle Reports | article only | Aug 05, 2000 03:09 pm
Uninstalling Oracle 8i | article only | Aug 06, 2000 09:11 am
When exactly the space in pctfree will be used | article only | Aug 06, 2000 01:54 pm
When the sort shrink back to sort_area_retained_size | article only | Aug 06, 2000 02:00 pm
How to use Oracle Application Server to display the CLOB in Oracle v8.1.5 | article only | Aug 06, 2000 03:47 pm
How to approach this task? -- to build an online testing system | article only | Aug 07, 2000 06:47 am
How to formulate SQL query | article only | Aug 07, 2000 07:14 am
Application Saver | article only | Aug 07, 2000 07:19 am
db_file_simultaneous_write Parameter | article only | Aug 07, 2000 07:32 am
two questions | article only | Aug 07, 2000 07:34 am
How to commit a perticular dml statement ? | article only | Aug 07, 2000 07:46 am
Full import from a lower version to a higher version overwrites sys/system objects? | article only | Aug 07, 2000 07:51 am
Index cannot extent while tablespace have enough space | article only | Aug 07, 2000 08:00 am
Memory usage | article only | Aug 07, 2000 08:06 am
Windows 2000 Advanced Server And the Oracle Family 7-8-8i | article only | Aug 07, 2000 12:47 pm
Database Users | article only | Aug 07, 2000 02:00 pm
Transactions per second | article only | Aug 07, 2000 06:17 pm
Users per hour | article only | Aug 07, 2000 07:19 pm
Recovery New features and power | article only | Aug 08, 2000 07:04 am
oracle procedures,functions,packages and triggers | article only | Aug 08, 2000 07:24 am
Spool File | article only | Aug 08, 2000 08:42 am
Handling Cross Tab Structures | article only | Aug 08, 2000 08:45 am
nested select statement | article only | Aug 08, 2000 09:22 am
Update or no update based on decode value | article only | Aug 08, 2000 10:58 am
Will the database hang when one of the archive destination become full?. | article only | Aug 08, 2000 01:24 pm
Analyzing Tables | article only | Aug 08, 2000 01:53 pm
How Oracle identifies the oracle unix user tnsnames.ora location for db link? | article only | Aug 08, 2000 02:54 pm
Can I send messages on mobile phone from Oracle database? | article only | Aug 08, 2000 03:41 pm
Password encode | article only | Aug 08, 2000 07:47 pm
Dyanamic files generation -- creating sqlldr control files on the fly | article only | Aug 08, 2000 08:30 pm
Stored procedures -- resolution of object names and scope | article only | Aug 09, 2000 08:38 am
Recovery Manager Catalog - different versions of Database | article only | Aug 09, 2000 08:45 am
Part #2 of Function Based Indexes | article only | Aug 09, 2000 09:32 am
Genrating Control Files | article only | Aug 09, 2000 09:33 am
Qs on V$ views and a Q on OAS | article only | Aug 09, 2000 09:58 am
Enable Novalidate does not work for PK? | article only | Aug 09, 2000 11:38 am
Inserting a COLUMN into the MIDDLE of a table... | article only | Aug 09, 2000 11:44 am
public and private RBS | article only | Aug 09, 2000 04:07 pm
SPOOL FILE IN PLSQL | article only | Aug 09, 2000 04:09 pm
Developer 6.0 with calculation in field | article only | Aug 09, 2000 04:21 pm
Table Joins and ResultSets | article only | Aug 09, 2000 04:30 pm
Unique constraints by non-unique indexes on local partition indexes | article only | Aug 09, 2000 06:43 pm
SQL command | article only | Aug 10, 2000 09:32 am
Data transfer from AS/400 to Oracle | article only | Aug 10, 2000 09:43 am
How to execute .sql files without actually going to SQLPLUS | article only | Aug 10, 2000 09:47 am
PL/SQL-Stored-Function in OCI | article only | Aug 10, 2000 09:49 am
How to export data from one platform(windows nt) to another (solaris) | article only | Aug 10, 2000 10:10 am
INtermedia Text Fuzzy Search | article only | Aug 10, 2000 10:15 am
DB_BLOCK_GETS AND CONSISTANT GET | article only | Aug 10, 2000 10:35 am
CTAS | article only | Aug 10, 2000 10:43 am
Oracle - XML | article only | Aug 10, 2000 11:10 am
Using UTL_FILE | article only | Aug 10, 2000 04:43 pm
Loading from flat file into db table | article only | Aug 10, 2000 08:55 pm
NLS support | article only | Aug 11, 2000 08:43 am
SqlPlus Query and output result sets | article only | Aug 11, 2000 08:46 am
developer 2000/6i -- setting iconic property | article only | Aug 11, 2000 08:50 am
Oracle Forms -- where is the documentation | article only | Aug 11, 2000 01:43 pm
Checking that a database is up | article only | Aug 11, 2000 01:50 pm
New feature difference 8 and 8i | article only | Aug 11, 2000 02:03 pm
How to copy everything from one schema to another schema, all objects, priviledges etc. | article only | Aug 11, 2000 04:00 pm
Impact of ORACLE_SID | article only | Aug 11, 2000 04:01 pm
row(s) 1 - 63 of 63
August 05, 2000 suriyanarayan -- Thanks for the question regarding "Split block Concepts -- fractured block", version Oracle 8.1.5
You Asked
What is the meaning of Split block concepts?

Regards

S. Maharajan
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:271815712711
for an explaination of a fractured block (split block) and when
we might encounter them and how we avoid them (by logging extra
redo during a hot backup)
August 05, 2000 Eric -- Thanks for the question regarding "Max datafile size for 8.1.6.1.1 db on NT4?", version 8.1.6.1.1
You Asked
What is the max datafile size for 8.1.6 db on NT4?  The
db_block_size for this particular db = 2k but I'd like to know
all sizes and reference to where I can find this info as well.

Are there other factors to consider? - e.g., what's the
recommended largest size for optimal performance?
manageability?
- especially I/O concerns?

This NT4 server is, of course, NTFS.

Thanks,

Eric Myers
and we said...
With 8.1.6 as you have, the limits are:

    Windows NT        Maximum 4Gb files on FAT
                Theoretical 16Tb on NTFS

(note that regardless of the file size, the maximum extent size
is always 2gig)

Some advantages of files larger than 2Gb:

Less files to manage for smaller databases.
Less file handle resources required

Some disadvantages of files larger than 2Gb:

The unit of recovery is larger. A 2Gb file may take between 15
minutes and 1 hour to backup / restore depending on the backup
media and  disk speeds.  An 8Gb file may take 4 times as long.

Parallelism of backup / recovery operations may be impacted.

There may be platform specific limitations - Eg: Asynchronous IO
operations may be serialised above the 2Gb mark.

As handling of files above 2Gb may need patches, special
configuration     etc.. there is an increased risk involved as
opposed to smaller files. Eg: On certain AIX releases
Asynchronous IO serialises above 2Gb.

Your backup tool might not operate with >2gig files.
August 05, 2000 Reji -- Thanks for the question regarding "Storedprocedures from Oracle Reports", version Oracle Report6i
You Asked
Tom:
   How do I execute a stored procedure from Oracle Reports?
   What I would like to do is to execute a stored procedure
   instead of using the Query builder to build the sql query
   to retrieve the data?

   Thx
   Reji
and we said...
There are 2 approaches to this that I am aware of.

You must keep in mind that reports works with a "static" sql
query in the designer component -- we can change the "height" of
a result set it will work with (the rows can change at run time)
but the columns must stay the same (like forms).

Method 1: run the report NOT using a common username/password
but have each user log in as themself.  Each report will simply
reference a view.  The report, in an after parameter block
trigger or somewhere like that, can call a procedure you write
that based on the user input, creates or replaces their view.
The report runs using that view.  This view must always return
the same number and types of columns -- with the same column
names but can query different tables or use different
predicates.

Method 2: Use SQL to run PLSQL.  You can "select * from (plsql
function)" instead of "select * from Table".  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:398618956558
for an example of that.
August 06, 2000 Coleen Angela -- Thanks for the question regarding "Uninstalling Oracle 8i", version 8.1.5 R2
You Asked
Greetings. Sir, I have one question. I uninstalled my oracle 8i
for Windows NT 4 using the Universal Installer. I was able to
uninstall it without any warnings then I rebooted the machine.
After Rebooting I then realized that the oracle home (e:\orant)
and all the files are still there and my hard disk size has not
decreased. Since Universal Installer could see any products
installed at this point, I decided to delete the folders inside
the e:\orant but I didn't touch the folders which NT says that
it has some shared dll's. After doing this, I rebooted again the
machine. Then afterwards, I checked the control panel services
to see if the oracle services are still there. All of the
services Oracle has installed are already gone except for the
OracleDefault_HOMETNSListener and OracleServiceOrcl. Do you any
procedure to remove this? I need your help. Some time this month
I'm going to buy a new harddrive dedicated to Oracle and I'm
having some fear that this might have a conflict If I'll
installed a fresh oracle again. Thanks

Sincerely Yours.
Coleen Angela Luz
and we said...
This is support note <Note:45834.1> on this topic:

REMOVING ORACLE SOFTWARE FROM AN NT 4.0 SYSTEM
==============================================

Because Oracle products comprise many different components which
may have different file dependencies than any existing Oracle
software, it is easiest to install new Oracle products onto a
system devoid of Oracle software. This article describes how to
remove all traces of Oracle software from a Windows NT system.

Caution: The following procedures require the editing of Windows
         NT registry variables, a potentially dangerous
         operation. There is no Undo option in the Registry
         Editor.

The safest procedure to remove all traces of Oracle software
from
a Windows NT system is to:

* stop all Oracle services
* use the Oracle Installer to remove installed Oracle software
* delete the ORACLE_HOME directory
* delete any Oracle INI files (e.g., ORADIM73.INI, OEMTBAR.INI)
  from the Windows NT boot directory (specified by the WINDIR
  environment variable, e.g., C:\WINNT40)
* remove the HKEY_LOCAL_MACHINE | SOFTWARE | ORACLE branch from
  the Registry
* remove all Oracle services from HKEY_LOCAL_MACHINE | SYSTEM |
  CurrentControlSet | Services
* remove the Oracle for Windows NT shortcut folder
* remove the ORACLE entries from the NT environment
* reboot the system

The following example uses a Windows NT 4.0 system, but the same
principles apply to a Windows NT 3.51 system.

1. STOP ALL ORACLE SERVICES

Run the Services Control Panel to stop the installed Oracle
services.

You can accomplish this by:

* selecting a service
* clicking Stop

 or type at command-prompt:

  c:\> net stop servicename

  c:\> net stop OracleServiceOrcl

 Close the Services Control Panel.

 Verify if you have database instances that are created; there
 exist services in the Services Control Panel with a name like
 OracleService<SID> or OracleStart<SID>.

 If so remove the instances with the appropriate ORADIMxx:

  ORADIM73 for Oracle7  7.3
  ORADIM80 for Oracle8  8.0
  ORADIM   for Oracle8i 8.1

 c:\>Oradimxx -delete -sid <SID>

2. DEINSTALL ORACLE PRODUCTS

Launch the Oracle Installer from Start Menu/Programs/Oracle for
Windows NT/Oracle Installer

At the Product Selection screen, select all of the installed
products except for the Oracle Installer (which cannot deinstall
itself). Click on the Remove button to being the deinstallation
process.

Say yes to all confirmation dialogues.

Click the Exit button to quit the Oracle Installer, confirming
the final dialogue.

3. DELETE THE ORACLE_HOME DIRECTORY

Delete the Oracle home directory (e.g., C:\ORANT).

4. DELETE ANY "ORACLE.INI" FILES

Delete any Oracle INI (configuration) files that may exist in
the Windows NT boot directory. The Windows NT boot directory may
be found by entering "SET WINDIR" from a command prompt.

Typical Oracle INI files for 32-bit installations include
ORADIM73.INI, ORADIM80.INI.

5. REMOVE REGISTRY KEYS

The preferred method of removing Oracle Services is by using
the command line or GUI version of the ORADIMnn utiltity, where
nn is a version number such as 73. However, the Registry Editor
can also be used, as follows.

Launch "REGEDIT.EXE" using the Start Menu Run command.

Navigate to "HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE" by
doubling-clicking on each key in turn and select the Oracle-key.

  Press the Delete key and confirm the subsequent dialogue by
  clicking the Yes button.

Navigate to
"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services" by
double-clicking on each key in turn. Scroll down to the listing
for Oracle services.

  Select the appropriate services and delete them.

  The other option to delete services is to use one of two
  utilities provided by Microsoft as part of the NT Resource
  Kit.  The two utilities are 'instsrv.exe' and 'srvinstw.exe'.
  The former is a command line executable to install or remove
  services, and the latter does the same thing but has a GUI
  interface.

  Confirm the subsequent dialogues.

Navigate to
"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uni
nstall".

Just remove the key for any entries you no longer want.

Exit the Registry Editor.

6. REMOVE ORACLE FROM START MENU

Delete the Oracle for Windows NT menu or the eventual other
Oracle entries option from "%windir%\Profiles\All Users\Start
Menu\Programs"
(e.g., C:\WINNT\Profiles\All Users\Start Menu\Programs).

7. REMOVE ORACLE ENTRIES FROM THE NT ENVIRONMENT

Right-click on My Computer and select Properties.  Click on the
Environment tab. Under the System Variables section, highlight
and delete any Oracle environment variables. Select the Path
variable and remove any entries pointing to Oracle directories.
If you are logged-in as the user that installed Oracle, you
should also see variables listed in the User Variables section.
Highlight and delete these as well.

Click the OK button to save the change and exit the program.

Finally, reboot the system to allow all these session's changes
to take effect. Ensure that "%ORACLE_HOME%\bin" no longer
appears in the Path.

------------------------------------------------------------
                           Oracle Worldwide Customer Support
Review & Followup
Rating: 5
April 02, 2001
Reviewer: Chunchu Srinivasa Rao from Mumbai - India

August 06, 2000 Ravi -- Thanks for the question regarding "When exactly the space in pctfree will be used", version 8.0.4.4
You Asked
Tom,

Scenerio : Pctused is 40% and pctfree is 10%.
           One table is created
           One row is inserted and  this operation did not
remove the block from the freelist.
           Committed.

   If the same is updated now, will it use the space from the
pctfree though enough space is available in the block and it is
still in the freelist. When exacty the space in the pctfree is
used.

Your reply in this is higly appreciated.

Regards
Ravi
and we said...
Trick question -- updates don't obey the pctfree that way --
pctfree is used during a INSERT to determine whether a NEW row
can go onto a block (if adding that new row would cause the
percentage of the block to spill into the area that is supposed
to be left free for updates -- the insert will not use that
block, it'll find another).

PCTFREE is used to leave space for updates.  You use PCTFREE to
explicity set aside space for future updates -- to avoid row
migration and block chaining that would happen if you filled the
block entirely during the insert operation.

An update can take a block on or off the freelist but an update
will always try to use all of the space on a block (or as much
as it needs).

<quote server concepts manual>
The PCTFREE Parameter

The PCTFREE parameter sets the minimum percentage of a data
block to be reserved as free space for possible updates to rows
that already exist in that block. For example, assume that you
specify the following parameter within a CREATE TABLE statement:
PCTFREE 20

This states that 20% of each data block in this table’s data
segment will be kept free and available for possible updates to
the existing rows already within each block. New rows can be
added to the row data area, and corresponding information can
be added to the variable portions of the overhead area, until
the row data and overhead total 80% of the total block size.
Figure 4–3 illustrates PCTFREE.
</quote>
August 06, 2000 Ravi -- Thanks for the question regarding "When the sort shrink back to sort_area_retained_size", version 8.0.4.4
You Asked
Tom,

I have set both the sort_area_size and sort_area_retanied_size.
If an user gives a select statement which requires sort size
more than sort_area_retained size, please clarify the following.

1) During the sort operation, after growing to sort_area_size,
if the process involved in sort goes for some other work.
oracle explains that the sort_area_size may be reduced to
sort_area_retained_size.

What are the operations by that process, which reduces the
sort_area_size to sort_area_retained_size.

2) If the query is completed, what is the area of memory
allocated to the session

Is it 0, becuase no sort after the operation
Is it sort_area_retained_size
Is it sort_area_size if no sort_area_retained_size is set

3) when exactly the memory used for sort area, is deallocated
from a particular process/session and can be used by any other
session.

Is it immediately after the statement/transation/session
completion

Sorry for putting a long question.

Regards
Ravi
and we said...
I don't fully understand question 1 where you ask:

"What are the operations by that process, which reduces the
sort_area_size to sort_area_retained_size."

basically -- once the sort is done and we no longer need the
memory -- we shrink the amount of allocated memory back down to
sort_area_retained_size.

2 -- it would be sort_area_retained size.  If you let it default
then:

...<quote>....
Note: The default value as reflected in the V$PARAMETER dynamic
performance view is 0. However, if you do not explicitly set
this parameter, Oracle actually uses the value of the
SORT_AREA_SIZE parameter.
</quote>

this parameter is used to control the amount of memory we give
back after we've allocated it.  since allocate/deallocating
memory is expensive -- we let you control it.  Lots of ram --
sort_area_size = retained.  Little ram -- retained = some
fraction of sort_area_size.  Its up to you.

3) Yes in most cases -- depends on how the OS manages memory of
course.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:437619854172
for more info.
August 06, 2000 Kelvin -- Thanks for the question regarding "How to use Oracle Application Server to display the CLOB in Oracle v8.1.5", version 4.0.7
You Asked
Hi, Tom

   We have load some text file into the CLOB. How to use the
Application Server to display the content of CLOB in the
Browser.

Thanks!
and we said...
Using the PLSQL cartridge -- you just need a small routine like
this:

procedure get_text( p_id in number )
is
    l_lob   clob;
    l_amt   number default 4096;
    l_off   number default 1;
    l_data  varchar2(4096);
begin
    select theClob into l_lob
      from demo
     where id = p_id;

    begin
        loop
            dbms_lob.read( l_lob, l_amt, l_off, l_data );
            htp.prn( l_data  );
            l_off := l_off+l_amt;
            l_amt := 4096;
        end loop;
    exception
        when no_data_found then
            NULL;
    end;
end;

Now a URL like:

  http ://hostname/DAD/get_text?p_id=55

would get document 55 from your table and display its contents
August 07, 2000 Hima -- Thanks for the question regarding "How to approach this task? -- to build an online testing system", version 8.1.6
You Asked
Tom,
I am very new to this role.My company is planning to create a
application related to intranet.They want to design tables for
conducting an online certification exam for their employees
which they are doing manually tilldate.I really have no clue
what is going in the background ie for example there are some
sites which conduct online exams.I am having few doubts related
to them.
1)when the webpage pop's up with a question and multiple choice
answers is it a static web page or it is fetching data(questions
and answers) from the database?If it is fetching from the
database what are the tables and fields required to maintain it?
2)
An employee can take that test 3times.Everytime he must be given
a different set of question paper and if he fails that entire
questions and answers given by him must be archived for future
reference.
They asked me to create tables to store the questions,grade,date
of pass or fail,date at which he attended the test etc..
Can u give me a overall view of how to approach this task.
Thanks
Hima
and we said...
You know -- I worked on such a project myself.  We have an in
house system we call PKT (product knowledge testing).  It
supports the authoring and delivery of online tests on the web.

We have a database full of tests -- each test has many questions
(many more then we give to someone in an instance of the test --
if you are going to have a test with 30 questions, our database
would typically have 75-150 questions to pick from).  Each
question has 6-20 possible answers.  When some says "I want to
take test 'X', we generate a list of questions choosen at random
and then randomly pick the answers (some of the answers must be
included -- for multiple choice questions that are of the form
"which ONE of the following is true").  Thus, each time you take
the test -- you get a new test that you've never seen before.
Even if you get the same question 2 times -- it'll have a
different set of answers in a different order.

We have limits on the number of times you can take the test and
not pass -- after that, you must meet with your manager (this is
all table driven) and they can reset your attempt count after
talking with you.

Of course, all of the reports are there - who as taken it,
passed/failed, by organization and so on.

Thats what we did.

You can actually get this as part of a consulting
implementation, see:
http://www.oracle.com/fastforward/enterpriseportal/index.html
for information on that.
August 07, 2000 Pierre -- Thanks for the question regarding "How to formulate SQL query", version 3.3.2.0.0
You Asked
UPDATED 2000-08-07
Hi Tom,

don't worry about PID's (I was just trying to give you a bit of
background).

Basically, I'd like to show 3 trend curves in the one graph in
Oracle Reports. The 3 trends of interest can be found  in the
table numlogval described below. The entries can can differ in
frequency and sample rate.

I am not quite sure what dataset I need to be able to present
this type of information. From what I can understand, a graph
can only handle a single query.

I can see 2 different datasets that might work:

TIME         MV_LOG          OUT_LOG         SP_LOG
12:00:00     11              NULL            NULL
12:00:01     NULL            NULL            33
12:00:03     NULL            22              NULL
12:00:07     NULL            NULL            34
12:00:09     NULL            23              NULL
12:00:10     13              NULL            NULL
12:00:13     NULL            NULL            34
12:00:15     NULL            23              NULL
12:00:20     14              NULL            NULL
12:00:30     15              NULL            NULL
12:00:55     NULL            NULL            36
12:01:01     NULL            NULL            36
12:01:15     NULL            25              NULL
12:01:21     NULL            26              NULL

How would the system plot this? How would the graph interpret
NULL values?

Another dataset that might work OK would be:
TIME         MV_LOG          OUT_LOG         SP_LOG
12:00:00     11              22              33
12:00:01     11              22              33
12:00:03     11              22              33
12:00:07     11              22              34
12:00:09     11              23              34
12:00:10     13              23              34
12:00:13     13              23              34
12:00:15     13              23              34
12:00:20     14              23              34
12:00:30     15              23              34
12:00:55     15              23              36
12:01:01     15              23              36
12:01:15     15              25              36
12:01:21     15              26              36

So, basically just holding the value until a new one is
available.

But like I said, I don't really know what dataset I need for the
graph.

Another way of putting my problem would be:
I have got 3 timeseries of data that I would like plot in a
graph. All 3 series are over 2 hours but they have different
sample rate and other irregularities.

So, I hope that my comment about needing a query returning 4
columns (1 with the time values and 3 with the values) is a
little bit clearer.

Thanks!!

/Pierre Oberg

ORIGINAL

Dear Sir/Madame,

I used your services a few weeks back and I was really happy
with the service provided. This time I have a slightly different
problem that I have been trying to get working for a long time.
I hope that you can help me. We are storing historical values in
a Oracle database, these values are sampled from our Distributed
Control System, so we are storing actual measured values,
setpoints for PID loop, outputs for PID loops etc.

We would like to run a report where we plot the setpoint,
measured value and output for the same PID loop, in the same
graph in Oracle Reports (version 2.5.5.21.0) ontop of an Oracle
7.3.2.3.0 database.

From what I can understand, a graph can only accept 1 query as
its input and I therefore need to come up with a query that will
give all necessary information. Basically we need the query to
return what is to be plotted as the x-axis (in our case a time
series) and also 3 columns of data to be plotted on the y-axis.

OK, our database structure:
SQL> desc numlogval
 Name                            Null?    Type
 ------------------------------- -------- ----
 NAME                                     VARCHAR2(82)
 TIME                            NOT NULL DATE
 MS                              NOT NULL NUMBER(10)
 ENTRYVALUE                      NOT NULL FLOAT(24)
 ENTRYSTATUS                     NOT NULL NUMBER(10)
 OBJECTSTATUS                    NOT NULL NUMBER(10)
 RET_TYPE                                 VARCHAR2(14)
 INTERP_ALG                               VARCHAR2(6)
 SELECTION                                VARCHAR2(10)
 CALC_ALG                                 VARCHAR2(14)
 INTERVAL                                 NUMBER(10)

Let's focus on name, time and entryvalue.
So, we might have entries in here like:

NAME               TIME                    ENTRYVALUE
SP_LOG             3-AUG-2000 12:00:01     33
SP_LOG             3-AUG-2000 12:00:07     34
SP_LOG             3-AUG-2000 12:00:13     34
SP_LOG             3-AUG-2000 12:00:55     36
SP_LOG             3-AUG-2000 12:01:01     36
...

MV_LOG             3-AUG-2000 12:00:00     11
MV_LOG             3-AUG-2000 12:00:10     13
MV_LOG             3-AUG-2000 12:00:20     14
MV_LOG             3-AUG-2000 12:00:30     15
...

OUT_LOG            3-AUG-2000 12:00:03     22
OUT_LOG            3-AUG-2000 12:00:09     23
OUT_LOG            3-AUG-2000 12:00:15     23
OUT_LOG            3-AUG-2000 12:01:15     25
OUT_LOG            3-AUG-2000 12:01:21     26
...

Please note that the time is a date field and that the sample
times can differ in frequency and sample rate.

How can I write one SQL query that will return 4 columns (1 time
serie and 3 data columns) that can be plotted in a graph in
Oracle reports?

Please help!!

Best regards
Pierre Oberg
and we said...
2 queries that might help you get started then are:

ops$tkyte@8i> select time,
  2         to_date(to_char(time,'j')||
               to_char(trunc(
                 to_char(time,'SSSSS')/5)*5,'00009'),
                   'j SSSSS' ) ntime,
  3         decode(name,'MV_LOG',entryvalue,null) mv_log,
  4         decode(name,'SP_LOG',entryvalue,null) sp_log,
  5         decode(name,'OUT_LOG',entryvalue,null) OUT_LOG
  6    from t
  7   order by time
  8  /

TIME                 NTIME                    MV_LOG     SP_LOG
  OUT_LOG
-------------------- -------------------- ---------- ----------
----------
03-aug-2000 12:00:00 03-aug-2000 12:00:00         11
03-aug-2000 12:00:01 03-aug-2000 12:00:00                    33
03-aug-2000 12:00:03 03-aug-2000 12:00:00
       22
03-aug-2000 12:00:07 03-aug-2000 12:00:05                    34
03-aug-2000 12:00:09 03-aug-2000 12:00:05
       23
03-aug-2000 12:00:10 03-aug-2000 12:00:10         13
03-aug-2000 12:00:13 03-aug-2000 12:00:10                    34
03-aug-2000 12:00:15 03-aug-2000 12:00:15
       23
03-aug-2000 12:00:20 03-aug-2000 12:00:20         14
03-aug-2000 12:00:30 03-aug-2000 12:00:30         15
03-aug-2000 12:00:55 03-aug-2000 12:00:55                    36
03-aug-2000 12:01:01 03-aug-2000 12:01:00                    36
03-aug-2000 12:01:15 03-aug-2000 12:01:15
       25
03-aug-2000 12:01:21 03-aug-2000 12:01:20
       26

14 rows selected.

That measures things on a "random" basis though.  Since
everything is measured at a different rate -- its not "nice"
looking.  We can normalize to 5 second (or whatever period)
samples.  For example:

ops$tkyte@8i>
ops$tkyte@8i> select time, avg(mv_log), avg(sp_log),
avg(out_log)
  2    from (
  3  select to_date(to_char(time,'j')||to_char(trunc(to_char
                 (time,'SSSSS')/5)*5,'00009'),'j SSSSS' ) time,
  4         decode(name,'MV_LOG',entryvalue,null) mv_log,
  5         decode(name,'SP_LOG',entryvalue,null) sp_log,
  6         decode(name,'OUT_LOG',entryvalue,null) OUT_LOG
  7    from t
  8             )
  9   group by time
 10  /

TIME                 AVG(MV_LOG) AVG(SP_LOG) AVG(OUT_LOG)
-------------------- ----------- ----------- ------------
03-aug-2000 12:00:00          11          33           22
03-aug-2000 12:00:05                      34           23
03-aug-2000 12:00:10          13          34
03-aug-2000 12:00:15                                   23
03-aug-2000 12:00:20          14
03-aug-2000 12:00:30          15
03-aug-2000 12:00:55                      36
03-aug-2000 12:01:00                      36
03-aug-2000 12:01:15                                   25
03-aug-2000 12:01:20                                   26

10 rows selected.

Still has the NULL gaps there -- we can get rid of them if
need be.  one way (looks like you are using 7.3) that will work
is:

ops$tkyte@8i> select time, get_ev( time, 'SP_LOG' ) sp_log,
  2               get_ev( time, 'MV_LOG' ) mv_log,
  3               get_ev( time, 'OUT_LOG' ) out_log
  4    from ( select start_time+(r-1)*5/24/60/60 time
  5             from ( select min(time) start_time
  6                      from t ),
  7                  ( select rownum r
  8                      from all_objects
  9                     where rownum <= 25 )
 10         )
 11  /

TIME                     SP_LOG     MV_LOG    OUT_LOG
-------------------- ---------- ---------- ----------
03-aug-2000 12:00:00                    11
03-aug-2000 12:00:05         33         11         22
03-aug-2000 12:00:10         34         13         23
03-aug-2000 12:00:15         34         13         23
03-aug-2000 12:00:20         34         14         23
03-aug-2000 12:00:25         34         14         23
03-aug-2000 12:00:30         34         15         23
03-aug-2000 12:00:35         34         15         23
03-aug-2000 12:00:40         34         15         23
03-aug-2000 12:00:45         34         15         23
03-aug-2000 12:00:50         34         15         23
03-aug-2000 12:00:55         36         15         23
03-aug-2000 12:01:00         36         15         23
03-aug-2000 12:01:05         36         15         23
03-aug-2000 12:01:10         36         15         23
03-aug-2000 12:01:15         36         15         25
03-aug-2000 12:01:20         36         15         25
03-aug-2000 12:01:25         36         15         26
03-aug-2000 12:01:30         36         15         26
03-aug-2000 12:01:35         36         15         26
03-aug-2000 12:01:40         36         15         26
03-aug-2000 12:01:45         36         15         26
03-aug-2000 12:01:50         36         15         26
03-aug-2000 12:01:55         36         15         26
03-aug-2000 12:02:00         36         15         26

25 rows selected.
Review & Followup
Rating: 2
what if i had the columns from diff tables May 23, 2002
Reviewer: Naveed Bhagwani from India
suppose
      sal1  sal2
      ---- ------
       444
            3344
            7967
       544
             if i want like this from two tables

August 07, 2000 -- Thanks for the question regarding "Application Saver", version 6.7
You Asked
Dear Tom,
   in our secured applications we need a ficility that allows
the developer to lock the application after a period of time has
expired .. we have different alterbnatives ( like  adding timers
on each form and sencing mouse movements and keyboard stroks ,
using connection idle time) , but none of the previous
alternatives seems to be proffisional solution to the case.

   if you have any thing can help like dll files or ready make
packaes or any thing else just please let me know.

Regards
and we said...
Depends on what you mean by "lock the application".

The easiest method, if it suffices, would be to use RESOURCE
PROFILES in the database and enable a max connection idle time.
After that time has expired, the connection to the database will
be broken and the application will have to re-log into the
database.  The application on the client could have an error
handler such that when it detects the database connection is
broken, it either prompts for a username/password or simply
exits.  This would be by far the easiest -- most bullet proof
way in my opinion.

See the admin guide for information on enabling profiles.
August 07, 2000 Ashish -- Thanks for the question regarding "db_file_simultaneous_write Parameter", version 8.0.5
You Asked
Hi Tom,

This time my question is more OS specfic.

Currently I have ORACLE (8.0.5) on UNIX 2.6 . I have
four disk configured with RAID 0+1 . These means I have
actually two stripe disks.My datafiles is spread across
the disk.

What will be the best value for init parameter
'db_file_simultaneous_write ' and why ?

Thanx in advance
Ashish
and we said...
I'll just quote a support note that covers this parameter well:

Article-ID:         <Note:30713.1>
Alias:              PARAMETER:DB_FILE_SIMULTANEOUS_WRITES

Parameter: DB_FILE_SIMULTANEOUS_WRITES
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 Obsoleted:        Oracle8i
 Parameter type:    integer
 Parameter class:   static
 Default value:     4
 Range of values:   minimum: 1
            maximum:
                       * when striping used: 4 times the number
                         of disks in the file that is striped
                         the most.
                       * when striping not used: 4

 Related:

Description:
~~~~~~~~~~~~
The number of simultaneous writes ("batches") for each database
file when written by DBWR.

DB_FILE_SIMULTANEOUS_WRITES specifies the maximum number of
simultaneous writes that can be made to a given database file.
Oracle also uses the value of this parameter in computing
various internal parameters that affect read and write
operations to database files.

If you specify an excessively large value for this parameter,
significant delays in performing read and write operations to a
given database file might occur. This is because I/O requests
get queued in the disk. If you set a value which is too small,
the number of I/Os that can be issued to a given database file
will be limited.

In environments where the database files reside on RAM devices
or which use disk striping at the operating system level, it is
beneficial to increase the value of this parameter. If striped
files are used, Oracle recommends that you set the value of this
parameter to 4 times the maximum number of disks in the file
that is striped the most.

This parameter is also used to determine the number of
reads-per-file in the redo read-ahead when reading redo during
recovery.
August 07, 2000 hagay -- Thanks for the question regarding "two questions", version 8.1.5
You Asked
1)  i want to save the results of select statements for some
sort of chashing , it means that i dont want to go to the DB
again with the same statement if i already use it , and that's
becuase i want to save time.

2)  i want to uses a data type that will contain a char type and
will be used as  char type and will contain about 4 giga

thanks - i hope you understand me.  hagay
and we said...
1) depends on your client then.  Java and ODBC support
scrollable result sets for example -- you can page up and down
through them.

2) LOB types do this.  a CLOB in particular.  See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/index.htm
for LOB documentation
August 07, 2000 -- Thanks for the question regarding "How to commit a perticular dml statement ?", version 5.0
You Asked
Hello Sir,

I have a doubt, may be basic.  Whenever we issue COMMIT  it will
save the changes made since last commit.  But can I commit a
perticular transaction ? This concept is available with rollback
using savepoint.

..
..
..
 if qty>0 then
     update part_master
     set temp_qty := nvl(:temp_qty,0)+ :inv_det.qty
     where part_no = :inv_det.part_no;

  --- > I would like to commit only the above update statement.
..
..
..
NOTE: This is useful in sales order system.  As soon as a sales
man selects some quantity of a perticular part, only the
remaining quantity should be available to others simaltaniously.

thank you very much for ur  help...

regs
mubeen
and we said...
Well, I'd like to know what happens when the application crashes
AFTER that update but before the rest of the transaction
completes.

In any case, the feature you are looking for is called an
autonomous transaction -- available in Oracle8i release 1 and
up.  See
http://osi.oracle.com/~tkyte/autonomous/index.html
for more info.

Now, in Forms, you can use the EXEC_SQL package to open another
non-default connection (use 2 connections to the same database).
 I sort of skipped version 5 of forms (went right from 4.5 to
6.0) so I'm not sure if v5 has this package or not (4.5 did not,
6.0 does).  You could also put this logic into a separate form
of course and use CALL_FORM or OPEN_FORM with a new session to
achieve the same results -- so regardless of the version of
forms or the version of the database I know you can do this:

o autonomous transactions, Oracle8.1 and up
o EXEC_SQL at least v6 of forms and up
o using another form with its own session -- all versions

Again though -- it sounds like a shaky approach.  Sounds like
you'll have lots of reserved qty's over time that are not really
being used as the application will crash, people will reboot and
so on...
August 07, 2000 spencer -- Thanks for the question regarding "Full import from a lower version to a higher version overwrites sys/system objects?", version 8.1.5
You Asked
To upgarde from a lower version of database to a higher version,
eg (7.x to 8.x or 8.0.5 to 8.1.6) a full export and import is
advised (we dont like inline upgrade), wouldn't the older
sys/system objects be overwrite the newer objects causing
problem. eg if the new version has a system table that has a
extra new column, wouldn't it be replaced?

I read the best method to do it was with the options rows=y
initially, followed by a second full import with full=n. Is this
true?

Thanks.
and we said...
SYS objects are not exported so that is not an issue.

SYSTEM owns some tables like the replication tables and AQ
tables but these will be upgraded by running the upgrade scripts
after the imp completes.

See
http://technet.oracle.com/doc/server.815/a67774/migeximp.htm#7014
for the steps.
August 07, 2000 James -- Thanks for the question regarding "Index cannot extent while tablespace have enough space", version 7.3.4 for NT
You Asked
I got an error when running a Form.
ORA-01654: unable to extend index
SYSTEM.ARAID_INVOICE_SEQ_ID by 512 in tablespace ar_idx

When I check the database, I found the following

                     Size     Used          Free
Tablespace           in MG. in MG.        in MG.
-------------------- ------ ------ ------ ------ ------
AR_IDX                  250    204 (82%)      46 (18%)

INDEX_NAME                     TABLESPACE INITIAL_EX NEXT_EXT
Max  Use  M-U MAX_SIZE     USED_SIZE
------------------------------ ---------- ---------- ----------
---- ---- ---- ------------ ------------
ARAID_INVOICE_SEQ_ID           AR_IDX     15360K     1024K
249    3  246      263.00M       17.01M

Segments that cannot extend
===========================
                             Seg
OWNER                        Name              Tablespace
NEXTEXT   LARGEST
--------------- ------------------------------ ---------------
--------- ---------
SYSTEM          ARID_SALES_RECAP               AR_IDX
1054720    819200
SYSTEM          ARID_REVENUE_CENTRE
1054720    819200
SYSTEM          ARID_CODE_YEAR
1054720    819200
SYSTEM          ARID_ACCOUNT_NO
1054720    819200
SYSTEM          ARAID_CODE_YEAR
1054720    819200
SYSTEM          ARAID_INVOICE_SEQ_ID
1054720    819200
SYSTEM          ARAID_SALES_RECAP
1054720    819200
SYSTEM          PK_CMSTMP_BATCH
1048576    819200
SYSTEM          IDX_ARID_MC
1054720    819200

It seems that there is plenty of space for the indexes.  What is
the reason for the error?
Best Regards
and we said...
Run the free.sql script below, eg:

SQL> @free 1

(that'll sort by tablespace name).  It'll show you how much
space is ALLOCATED to a tablespace, how much of that is
allocated to objects, how much is free and most important for
you the largest free contigous extent in that tablespace.

You might have 46meg free but the largest contigous extent might
only be 100k.

It is possible that you have lots of free extents that are next
to eachother - you can try running "alter tablespace T coalesce"
to see if that increases the "largest" column from the following
query....

--------------------------------------------------------
-- free.sql
--
-- This SQL Plus script lists freespace by tablespace
--------------------------------------------------------

column dummy noprint
column  pct_used format 999.9       heading "%|Used"
column  name    format a16      heading "Tablespace Name"
column  Kbytes   format 999,999,999    heading "KBytes"
column  used    format 999,999,999   heading "Used"
column  free    format 999,999,999  heading "Free"
column  largest    format 999,999,999  heading "Largest"
column  max_size format 999,999,999 heading "MaxPoss|Kbytes"
column  pct_max_used format 999.9       heading "%|Max|Used"
break   on report
compute sum of kbytes on report
compute sum of free on report
compute sum of used on report

select nvl(b.tablespace_name,
             nvl(a.tablespace_name,'UNKOWN')) name,
       kbytes_alloc kbytes,
       kbytes_alloc-nvl(kbytes_free,0) used,
       nvl(kbytes_free,0) free,
       ((kbytes_alloc-nvl(kbytes_free,0))/
                          kbytes_alloc)*100 pct_used,
       nvl(largest,0) largest
from ( select sum(bytes)/1024 Kbytes_free,
              max(bytes)/1024 largest,
              tablespace_name
       from  sys.dba_free_space
       group by tablespace_name ) a,
     ( select sum(bytes)/1024 Kbytes_alloc,
              tablespace_name
       from sys.dba_data_files
       group by tablespace_name )b
where a.tablespace_name (+) = b.tablespace_name
order by &1
/
August 07, 2000 Tony -- Thanks for the question regarding "Memory usage", version 8.x
You Asked
Hi Tom,

If a database is used for datawarehousing purposes only (without
updating data), how must I configure Oracle for optimal use of
memory. Can I for instance force Oracle to use memory instead of
temporary tablespaces?
and we said...
Force is such a strong word.

You can increase the sort_area_size and sort_area_retained_size
as well as

o bitmap_merge_area_size
o create_bitmap_area_size
o hash_area_size

to decrease the number of times we will need sort space on disk.
 Remember though -- there is definitely "too much of a good
thing" potential here.

For example, lets say you were going to create some indexes in
parallel.  There is no way the entire thing will fit in RAM.
You decide to set sort_area_size really big anyway and create
the index.  Each PQ slave will read lots of data (lots of IO),
sort lots of data in RAM (tons of CPU) and then write lots of
data (lots of IO).  Since they are doing this in such big chunks
-- they will be doing this in lockstep with eachother (in
general, all will be reading at about the same time, sorting at
the same time, writing at the same time).  There is not that
much opportunity for them to get out of sequence with eachother
when doing such large chunks (they all read together, sort
together, write together).  However, if they worked in smaller
units -- you would find that very quickly some are reading while
others are sorting and writing and so on.  The overall mix of
work going on it better spread out -- less contention for
resources.  In this case, a smaller -- not necessarily larger --
sort_area_size is called for.  (this is why tuning can be so
hard, its not always "common sense")
August 07, 2000 Xavier -- Thanks for the question regarding "Windows 2000 Advanced Server And the Oracle Family 7-8-8i", version 7-8-8i
You Asked
Hello Tom ,

I begin to work with the new windows 2000 advanced server. (NT)

Is posible install one version 7.3.4 in W2000 Advanced Server ?
   have limitations ?
Is posible install one version 8.0.5 in W2000 Advanced Server ?
   have limitations ?
Is posible install one version 8.1.5 in W2000 Advanced Server ?
   have limitations ?
Is posible install one version 8.1.6 in W2000 Advanced Server ?
   have limitations ?

At this moment i install the 8.0.5 enterprise edition and the
software developer2000 forms4.5 and work fine.

I agree yours comments
and we said...
Oracle8i, release 2 (version 8.1.6) is the only supported
version of the database on that platforms.  Others may work (but
then again they may not).

If you are talking production instances, do not put anything
other then 8.1.6 and up on Win2k otherwise they are simply not
supported.

I would not recommend putting 8.1.5 or before on Win2k as that
is an environment you will never be able to field a production
application on.
August 07, 2000 Sebastian -- Thanks for the question regarding "Database Users", version 7.3.4.0.0
You Asked
Can I set the minimum characters required for the password of
database users?
and we said...
Not with Oracle7.3 -- that is a feature that was added with 8.0
of the server.

You can read about this feature "Password Management Policy" at
http://technet.oracle.com/doc/oracle8i_816/server.816/a76956/secure.htm#2185
....
August 07, 2000 Gabe -- Thanks for the question regarding "Transactions per second", version 8.0.5.1.0
You Asked
Hi Tom,

Is there a quick way to calculate the number of tranactions per
second that my database has processed since it was started?

Thanks,

Gabe Zauss
and we said...
No, not really -- and besides, I'm sure it has sat idle at some
point, that would drag down the averages.

You can see how many commits have happened and divide -- but
that is most certainly not "TPS" in any meaningful way.

select value from v$sysstat where name = 'user commits';
August 07, 2000 Mark -- Thanks for the question regarding "Users per hour", version 8.0
You Asked
How to generate a report that shows the number of users per
hour using the database.
and we said...
You would have to enable auditing -- in order to audit connects
and disconnects.  Then, the system auditing tables would be able
to tell you -- in a given hour, how many sessions were active.

Other then that, there is nothing in the database to give you
hourly reports on sessions.  We can tell you the MAX number of
sessions since the database was started, the current number of
sessions, but we cannot tell you how many sessions there were 1
hour ago (without auditing -- then we can derive that
information).

If you just want a "snapshot" (eg: at noon there were 50 people,
at 1pm there were 100, at 2pm there were 75 and so on) -- we can
easily write a stored procedure to insert into some table you
own:

 insert into t select sysdate, count(*) from v$session where
username is not null;

and use dbms_job to schedule that job to run every hour (see
supplied packages guide for info on that package)...
August 08, 2000 balasubramanian -- Thanks for the question regarding "Recovery New features and power", version 8.0.6 / 8.1.5
You Asked
Dear Tom,

 1.In new version of oracle (8i), the recovery manager is given
with additional features and power. For example, through
Recvoery Manager, we can start/mount/open/shutdown the database.
Basically what is the idea of giving such an advanced rights to
RMAN ?

 2.In New version RMAN, we can run RMAN without catalog
efficiently compared to version 8.0.x. What is the additional
capabilities given to RMAN (when using without catalog) ?
and we said...
1) its not given RMAN (which is a piece of software) any
"rights".  It has given RMAN the syntactic ability to issue yet
more commands.  The account under which RMAN runs needs the
sysdba/sysoper privs in order to startup and shutdown (but an
appropriate priveleged user could do this from SQLPlus if they
wanted).

The reasoning would be one of completeness.  In order to do a
cold backup -- the database must be shutdown for example.  In
8.0- that required using svrmgrl or sqlplus to issue a shutdown
and then RMAN to backup and then sqlplus/svrmgrl again to
startup.  Now, RMAN can do it all for you.

2) see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76990/recocat.htm#446924
for a list of commands that are only available when you use a
catalog (versus having us store the information in the control
files)
August 08, 2000 sravan -- Thanks for the question regarding "oracle procedures,functions,packages and triggers", version 7.3
You Asked
hello tom
  we have a problem regarding pl/sql library units.

1.when we have procedures and functions what is the need of
using packages?

2.what are the advantages of using packages over procedures
and functions?

3.what is a mutating table?

4.how does oracle resolve dependencies among procedues
packages.
and we said...
for #1, #2 and #4 see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:309816708253
and the other article it points to.

For #4, see
http://osi.oracle.com/~tkyte/Mutate/index.html
...
August 08, 2000 Tew -- Thanks for the question regarding "Spool File", version version 8.1.5
You Asked
Hi,

Is it possible to dynamically specifying the filename of a spool
file and forcing it to be a .sql file instead of a .lst file?

i.e. I have tried several times trying to achieve something like
that... spool c:\temp\test_&1.sql ... where &1 is part of the
filename that I want this spool file to be. Although I can
achieve the following... spool c:\temp\test_&1 ... it will by
default be a .lst file.

Please kindly acknowledge. Thank you very much.

Best Regards,
Siew Yen
and we said...
You would

spool c:\temp\test_&1..sql

The . after &1 demarks the end of the macro expansion -- to get
another ., you need ..
August 08, 2000 Vivek -- Thanks for the question regarding "Handling Cross Tab Structures", version 8.1
You Asked
Hi Tom,
I am Vivek from India and we are facing one problem to handle
cross tab reporting using powerbuilder.
Infact the problem is while we have more than 1 Lac records
coming on front end.
Power Builder does not respond(Or it takes too much time[In
hours].
Can you suggest some methods to develop such cross tabs in
oracle using sort of backend scripting.
Regards
Vivek
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:124812348063
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:396618940119
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:363818030381
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:229614022562
for my ideas on this problem
August 08, 2000 Servet -- Thanks for the question regarding
      "nested select statement", version 3.3

      You Asked
hi
"select hesapkod,(select sum(borc1) from mhi Y) as Borc from MHK
X where x.Hesapkod=Y.Hesapkod"
 This Query doenst work with oracle personel server and
oracle7.3
 But it works with oracle8.
 is there any way to make it work with oracle personel server
and oracle 7.3?
 Thanks..
 Servet

      and we said...
Your query above is not 100% correct in any release.  You have a
predicate on Y.hesapkod -- but that column is not exposed by any
part of the query.

ops$tkyte@DEV8I.WORLD> create table mhi ( borc1 number, Hesapkod
char(1) );

Table created.

ops$tkyte@DEV8I.WORLD> create table mhk ( Hesapkod char(1) );

Table created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> select hesapkod,(select sum(borc1) from
mhi Y) as Borc from MHK
  2  X where x.Hesapkod=Y.Hesapkod;
X where x.Hesapkod=Y.Hesapkod
                     *
ERROR at line 2:
ORA-00904: invalid column name

That syntax -- being able to use a subquery where ever an
identifier could be used -- was added in Oracle8i, release 8.1.

The query that would work in all releases from 7.1 on up is:

select hesapkod, sum_borc1
  from mhk X, ( select sum(borc1) from mhi ) Y
 where .....

You can join to the subquery instead of selecting from it.
August 08, 2000 Sanjib -- Thanks for the question regarding
      "Update or no update based on decode value", version Oracle 8.1.6

      You Asked
Hi Tom,
    Is it possible to have a single update statement to do
complex updates based on the decode value of a status indicator?
I have tried to make up a simple example to illustrate what I
mean by this... I am using two tables, a cursor and a single
update statement here. Updates are to be performed only if the
status indicates a change. By my experience, this can only be
achieved by writing two separate update statements. Can you
please help?

create table customer_table as (customer_name varchar2(10),
profession varchar2(20),address varchar2(20));

create table New_data as (name    varchar2(10) primary_key,
             status  varchar2(10),
             Changed_info  varchar2(20));

create procedure p1 as
begin
for cursor1 in (select * from New_data) loop
  update customer_table
  set profession= decode(cursor1.status, 'PChanged',
cursor1.Changed_info, profession),
      address   = decode(cursor1.status, 'AChanged',
cursor1.Changed_info,  address)
where customer_name=cursor1.name
end loop;
end;
                        Thanks and regards,
                          Sanjib Das

      and we said...
Yes you can -- in fact the cursor and loop are not needed either
at all (it'll be much faster as a straight update).

Consider:

ops$tkyte@DEV8I.WORLD> create table customer_table
  2  (customer_name varchar2(10),
  3   profession    varchar2(20),
  4   address varchar2(20)
  5  );

Table created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> create table New_data
  2  (name       varchar2(10) primary key,
  3   status  varchar2(10),
  4   Changed_info  varchar2(20)
  5  );

Table created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> begin
  2      for i in 1 .. 5 loop
  3          insert into customer_table
  4          values ( 'c'||i, 'p'||i, 'a'||i );
  5      end  loop;
  6  end;
  7  /

PL/SQL procedure successfully completed.

ops$tkyte@DEV8I.WORLD> insert into new_data
  2  values ( 'c1', 'PChanged', 'new p1' );

1 row created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> insert into new_data
  2  values ( 'c2', 'AChanged', 'new a1' );

1 row created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> select * from customer_table;

CUSTOMER_N PROFESSION           ADDRESS
---------- -------------------- --------------------
c1         p1                   a1
c2         p2                   a2
c3         p3                   a3
c4         p4                   a4
c5         p5                   a5

ops$tkyte@DEV8I.WORLD> update
  2    ( select profession c_profession,
  3             address c_address,
  4             status n_status,
  5             changed_info n_changed_info
  6       from customer_table c, new_data n
  7      where c.customer_name = n.name )
  8    set c_profession = decode( n_status, 'PChanged',
                               n_changed_info, c_profession ),
  9        c_address    = decode( n_status, 'AChanged',
                               n_changed_info, c_profession )
 10  /

2 rows updated.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> select * from customer_table;

CUSTOMER_N PROFESSION           ADDRESS
---------- -------------------- --------------------
c1         new p1               p1
c2         p2                   new a1
c3         p3                   a3
c4         p4                   a4
c5         p5                   a5
August 08, 2000 Ravi -- Thanks for the question regarding "Will
      the database hang when one of the archive destination become full?.",
      version 8.1.5

      You Asked
Tom,

We specified two arch log dest using
log_arch_dest and log_arch_duplex_dest parameters.
Conceptually,
will the database hang when one of the destination becomes full\
or
it will continue to operate with the other destination. How
oracle handles
the situation.

Please clarify

Regards
Ravi

      and we said...
Using the parameters you have use -- both must succeed OR the
database will halt until space becomes available.

If instead you use LOG_ARCHIVE_DEST_n (which is prefered over
duplex_dest) you can setup upto 5 archive destinations and
specify whether they are mandatory or optional.  Additionally,
you can use the LOG_ARCHIVE_MIN_SUCCEED_DEST to specify how many
of these optional archive dest's must succeed to reuse a log
file.
August 08, 2000 Paul -- Thanks for the question regarding
      "Analyzing Tables", version 8.0.4

      You Asked
Tom,

One of the developers on my team swears blind that there is no
point in analyzing a table which has no indexes. Another says
that you should analyze every table which might be used in a
join? Who is right, and why?

Thanks,
Paul Watson

      and we said...
Analyze every table wins.

We'll get more information such as

o number of rows
o cardinality of various columns.

this will tell us whether we should full scan the table, hash
it, sort merge to it and so on.  There are many many plans we
can come up with -- knowing the size and cardinality will
materially affect the plan (eg: knowing its small vs big will
make a difference).

Consider:

ops$tkyte@DEV8I.WORLD> /*
DOC>drop table t1;
DOC>drop table t2;
DOC>
DOC>create table t1 as select * from all_objects;
DOC>create index owner_idx on t1(owner);
DOC>analyze table t1 compute statistics;
DOC>
DOC>create table t2 as select * from all_objects where rownum=1;
DOC>*/

ops$tkyte@DEV8I.WORLD> select count(*) from t1;

  COUNT(*)
----------
     23852

ops$tkyte@DEV8I.WORLD> select count(*) from t2;

  COUNT(*)
----------
         1

ops$tkyte@DEV8I.WORLD> set autotrace on explain
ops$tkyte@DEV8I.WORLD> analyze table t2 delete statistics;

Table analyzed.

ops$tkyte@DEV8I.WORLD> select count(t1.object_name),
count(t2.object_name)
  2    from t1, t2
  3   where t1.owner = t2.owner;

COUNT(T1.OBJECT_NAME) COUNT(T2.OBJECT_NAME)
--------------------- ---------------------
                 6655                  6655

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=61 Card=1

   1    0   SORT (AGGREGATE)
   2    1     MERGE JOIN (Cost=61 Card=19559 Bytes=665006)
   3    2       INDEX (FULL SCAN) OF 'OWNER_IDX' (NON-UNIQUE)
   4    2       SORT (JOIN) (Cost=2 Card=82 Bytes=1394)
   5    4         TABLE ACCESS (FULL) OF 'T2' (Cost=1 Card=82

ops$tkyte@DEV8I.WORLD> analyze  table t2 compute statistics;
Table analyzed.

ops$tkyte@DEV8I.WORLD> select count(t1.object_name),
count(t2.object_name)
  2    from t1, t2
  3   where t1.owner = t2.owner;

COUNT(T1.OBJECT_NAME) COUNT(T2.OBJECT_NAME)
--------------------- ---------------------
                 6655                  6655

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Byt
   1    0   SORT (AGGREGATE)
   2    1     NESTED LOOPS (Cost=2 Card=298 Bytes=10132)
   3    2       TABLE ACCESS (FULL) OF 'T2' (Cost=1 Card=1 Byt
   4    2       INDEX (RANGE SCAN) OF 'OWNER_IDX' (NON-UNIQUE)

Notice the radically different plans generated before and
after stats on the unindexed table

ops$tkyte@DEV8I.WORLD> set autotrace off

Review &
      Followup

      Rating: 5
Analyze so
      clearly!  June 08, 2001
Reviewer:  Joseph
      Satchavarodom  from VA USA
Tom..very good job on the example.  It is clear!

August 08, 2000 Ravi -- Thanks for the question regarding "How
      Oracle identifies the oracle unix user tnsnames.ora location for db
      link?", version 8.1.5

      You Asked
Tom,

We are replicating some tables using the database link. I
understand
that the service name of the master database should exists in
the
tnsnames.ora, which is owned by the oracle unix user in the
snapshot machine.

The location of the tnsnames.ora is controlled by TNS_ADMIN env
variable, and which can be changed n number of time even during
running of database. How oracle resolves the service name in the

tnsnames.ora in such situation for replication like for ex when
I
issue select * from table1@dblink1

Regards
Ravi

      and we said...
The environment of the database is fixed when you start the
database.  the tns_admin is fixed at that point in time.

Depending on your platform - you may be able to see this
environment.  On solaris for example:

$ /usr/ucb/ps -wwe 27317
   PID TT       S  TIME COMMAND
 27317 ?        S  0:00 ora_pmon_ora816dev USER=ora816
HOME=/export/home/ora816 SHELL=/usr/bin/csh
PATH=/opt/gnu/bin:/usr/local/bin:/usr/ucb:/usr/bin:/export/home/o
ra816/bin:/usr/local/bin:/export/home/ora816/bin:/export/home/ora
816/src/sqlstuff:/usr/bin/X11:/usr/etc:.:/usr/ccs/bin:/usr/sbin:/
usr/oracle/oraweb/local/bin:/usr/openwin/bin TERM=vt100
LOGNAME=ora816 MAIL=/usr/spool/mail/ora816 TZ=US/Eastern HZ=100
PWD=/export/home/ora816 ORACLE_HOME=/export/home/ora816
ORACLE_SID=ora816dev SQLPATH=/export/home/tkyte/src/sqlstuff
UDUMP=/export/home/tkyte/src/sqlstuff
ORACLE_PROC_MAKEFILE=/export/home/ora816/precomp/demo/proc/demo_p
roc.mk PW=tkyte/tkyte
MANPATH=/usr/openwin/share/man:/usr/man:/opt/gnu/man:/opt/GCC2723
/man ORA_NET2_DESC=6,9

dumps the environment of my pmon process (i'm not using
tns_admin but you get the point).  You could just look at the
snp processes

August 08, 2000 Ashish -- Thanks for the question regarding "Can
      I send messages on mobile phone from Oracle database?", version 8.1.5

      You Asked
Hi TOM,

We are running an application on Oracle 8.1.5 on solaris and oas
4.081. We are using basic oracle users for authentication. We
want to develop a new functionality in our system by which we
will be able to send messages on the user's mobile phones.
Currently, whenever a new activity happens for any user we send
a mail to the user asking him to log on to the site and find out
the details. In the similar way can we send text messages on the
user's mobile phone along with the emails?

Thanks,

ashish

      and we said...
depends on the phone service.

I know someone with a pager that we can send a text message to
via EMAIL or a URL.  Every night we have a job that queries
tomorrows schedule  -- formats  a text message and uses UTL_HTTP
to run a URL on the pagers website that sends him a page.

If your phone service provider has a similar setup -- then yes,
either sending an email or running a URL can be used..  You'd
have to find out if thats available.

short of that -- if they have an api, a C or Java external
procedure can do virtually anything you want.
August 08, 2000 Krishna -- Thanks for the question regarding
      "Password encode", version 8i

      You Asked
How do you encode and store passwords. We have an application
which
has an input screen wherin it prompts for user name and password

for a web page . Now these values are to be stored in a table
but  the
developer wants to store encoded passwards for security reasons.

How do I do that
Thanks
Krishna Roy

      and we said...
See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:95412348059
for the solution....
August 08,
      2000 Santhosh -- Thanks for the
      question regarding "Dyanamic files generation -- creating sqlldr control
      files on the fly", version oracle8i

      You Asked
Suppose i have an ascii spool file which contains data from a
table.

1. how do i can check the number of records in it.
2. create dyanmically a control file that has the table name ,
number of rows and the timestamp.
3. create a dyanmic sqlloader control file( to import the ascii
file into another table having same columns)

all the above need to be done in korn shell
can u suggest some checks i can perform on this ascii file to
make sure that the data after export of this ascii file is still
the same .
thanks harrry

      and we said...
1) the unix utility "wc -l" will tell you that. a script such
as:

#!/bin/ksh

export X=`wc -l <$1`
echo $X

will set an environment variable = the number of lines in a
file.  Something like:

----------------------------------------------------
#!/bin/ksh

export X=`wc -l <$1`

cat <<EOF > temp.ctl
LOAD DATA
INFILE *
INTO TABLE $2
APPEND
FIELDS TERMINATED BY ','
(tname, cnt)
BEGINDATA
$3,$X
EOF

sqlldr / temp.ctl
----------------------------------------------------

with a table called "table_name" in this example created like:

ops$tkyte@DEV8I.WORLD> create table table_name( tname
varchar2(25), cnt int, timestamp date default sysdate );

and a command line of:

$ test.ksh data.dat table_name xxx

will create a control file like:

LOAD DATA
INFILE *
INTO TABLE table_name
APPEND
FIELDS TERMINATED BY ','
(tname, cnt)
BEGINDATA
xxx,      16

which totally does number 1 & 2 above...

for #3, I'll send you to:

http://osi.oracle.com/~tkyte/flat/index.html
there is a script there, sqlldr_exp, that shows how to create a
sqlldr control file using SQLPlus for a table (it also dumps all
of the data). It's a SH script -- you can either modify or
convert it, upto you.....

Table created.

August 09, 2000 rajesh -- Thanks for the question regarding
      "Stored procedures -- resolution of object names and scope", version
      Oracle 7

      You Asked
Hi Tom,

We have a typical requirement in accessing the synonym with
stored procedure. we have stored procedure to get the details
from public synonym "t_tab1" in X user. But in the same schema
we have a table with same name "t_tab1". So, when getting the
details using the stored procedure we have different values
with select statement issued from the other users like Y.
This is because from other user its getting the details from
public synonym and where as with stored procedure its getting
from table. But I want to use the stored procedure
(as front ends are developed based on this) and I want
the result from public synonym. how can I achieve this.

I cannot change the names of tables or synonyms as we
have problems with standards to be followed.
Is there any possibility of directing the stored procedure
to use only public synonym.

      and we said...
Zero chance here.  This is the only way it can work.  Object
names are resolved

o within the schema if possible
o outside of the schema if not possible.

It is simply a matter of scope here.  When logged in a user X --
t_tab1 is X.T_TAB1 -- not the public synonym.  When user X
creates a procedure -- object names are resolved using his
access permissions and scoping rules.  Therefore any procedure
that accesses T_TAB1 will access X.T_TAB1 -- not the object
pointed to by the public synonym.

Your only solution is to code the procedure to access stored
procedure to access OTHER_SCHEMA.T_TAB1 -- it must qualify the
object reference.

If you have a standard that allows for duplicate, ambigous
object names like this -- you need to change it.  Sounds like a
dangerous standard, not a helpful one.
August 09, 2000 balasubramanian -- Thanks for the question
      regarding "Recovery Manager Catalog - different versions of Database",
      version 8.0.6/8.1.5

      You Asked
Dear Tom,
 Sorry for asking again about RMAN.

 I have 2 questions:

1.Can we create a catalog for a 8i version database in another
oracle 8.0.x or 7.3.x database ? i-e I have a 8.1.5 database and
7.3.2 database. I want to backup 8.1.5 database using RMAN. Can
I use Oracle 7.3 database to create recovery catalog for oracle
8i? (Is there any restrictions about oracle versions ?)

2.Suppose my datafile is of size 2 GB. Can I break this 2GB file
in the backup pieces as (1GB+1GB)and store using RMAN in the
backup form? (Since oracle8i supports exporting into multiple
files, is it possible to break-up big file into small pieces
using RMAN ?

      and we said...
RMAN's recovery catalog should be in the release of the database
that RMAN ships with.  Since RMAN did not exist with 7.3 -- you
would not be creating an RMAN catalog in 7.3.  If you are using
the 8.0 RMAN, it would be in an 8.0 database.  If you are using
the 8i RMAN, it would be in an 8.1 instance.  This is the
supported configuration.  Part of recovery manager is a DBMS_*
package and this package is stored only in the appropriate
versioned database.

for #2, not that I am aware of.  It does image copies.  You can
use incremental backups which will result in smaller backup sets
and files but eventually you need do a full.
August 09, 2000 Tony -- Thanks for the question regarding "Part
      #2 of Function Based Indexes", version 8.1.6

      You Asked
Hi Tom,

I traced your script with the following result:

0 SELECT STATEMENT Optimizer=HINT: FIRST_ROWS (Cost=1 Card=1
Bytes=129)
  1 0 TABLE ACCESS (BY INDEX ROWID) OF 'T' (Cost=1 Card=1
Bytes=129)
  2 1 INDEX (RANGE SCAN) OF 'T_IDX' (NON-UNIQUE) (Cost=1 Card=1)

My query on the other hand resulted in:

0 SELECT STATEMENT Optimizer=CHOOSE
  1 0 TABLE ACCESS (FULL) OF 'NAW'

When performing the same query with /*+FIRST_ROWS*/ it resulted
indeed in:

0 SELECT STATEMENT Optimizer=HINT: FIRST_ROWS (Cost=2 Card=7222
Bytes=1928274)
  1 0 TABLE ACCESS (BY INDEX ROWID) OF 'NAW' (Cost=2 Card=7222
Bytes=1928274)
  2 1 INDEX (RANGE SCAN) OF 'IX_NAWNAAM' (NON-UNIQUE) (Cost=1
Card=7222)

The following question rises:

Why should I leave the OPTIMIZER MODE to CHOOSE?
It chooses between COST-BASED en RULE but according to the
help-file

**QUOTE
However, you should eventually migrate your existing
applications to use the cost-based approach, because the
rule-based approach will not be available in future versions of
Oracle.
**ENDQUOTE

you should use COST-BASED optimizing.
Are there any disadvantages of turning my optimizer mode to
COST-BASED in the ORA.INI?

Tony Cardalda.

ps.
Thank you for your help!

      and we said...
You should analyze your tables and then CBO will be used
automatically.

Leave the init.ora parameter at CHOOSE -- so when no stats exist
we use RBO (and rbo doesn't know of function based indexes) and
when stats do exist, we use the CBO.
August 09, 2000 Manoj -- Thanks for the question regarding
      "Genrating Control Files", version 7.3.4

      You Asked
Hi Tom,

How to generate CTL files given a table ? I am supposed to
load(populate) 100 odd tables. I have CSV data. Is there any
tool or go about.

Thanx,
Manoj

      and we said...
see

http://osi.oracle.com/~tkyte/flat/index.html
it is an unloader but shows one way to use sqlplus to generate a
ctl file.
August 09, 2000 Bhavesh -- Thanks for the question regarding "Qs
      on V$ views and a Q on OAS", version 8i

      You Asked
Hello Tom,
This time I have several Qs:
1. I read somewhere that there are total 132 V$ views
   in Oracle 7. Is this the same number in Oracle8i?
   Or is it more?
2. When I re-start my instance, do ALL the V$ views
   truncated? If NOT all, can u categorize which
   ones are truncated and which are not? Why?
3. I have re-started my instance with "timed_statistics = true".
   And then, after several hours of DB usage, I
   ran "UTLBSTAT.SQL".
   Now, I forgot to run "UTLESTAT.SQL", and I shut down the
   instance. After I re-started the instance
   ("timed_statistics = true"
   is still there), just for curiosity, I ran "UTLESTAT.SQL", and
   viewed "report.txt". In this report, in
   "Select Library cache statistics" section, GETs/PINs/RELOADs
   are negative numbers. And, many of the statistics
   are negative in other sections also.
   Are these all garbage numbers - 'coz I did not
   run "UTLESTAT.SQL" before shutdown ? OR, are they
   represents any other characteristic ?
4. We are using OAS 4.0 on NT (the database is on
   UNIX-Sun/Solaris). I put a file1.xls file on the NT
   server. I want to give the user a link - clicking on
   which he should get "open/save" dialogue and then he can
   open/save the file1.xls file. How I can achieve this
   functionality on OAS ?

Thanks in advance,
Bhavesh Patel

      and we said...
1) there are about 180 or so in 8i

2) all are "truncated" -- not really truncated but reset.  v$ views are "fake"
tables and are based on in memory structures.  counters, timers and so on are
all reset.

3) utlbstat/estat cannot be run across restarts -- they must be run in the same
instance without an intervening reboot.  bstat just snapshots many of the V$
tables.  Estat takes that snapshot and substracts them from the current values.
By restarting and reseting the counters -- many things would be negative.

4) depends on the browser.  with MSIE -- you'll have to physically rename
file1.xls.  MSIE doesn't obey mime types and when it sees .xls will run excel.
You SHOULD be able to set the mime type for .xls to application/octet-stream and
the browser SHOULD put up the save as dialog -- MSIE will not.  With netscape --
you just do what I described, set the mime type for .xls files to
application/octet-stream and you'd be done.  with MSIE, you'll need to rename
file1.xls to file1.dat or something and convince your users to rename it (or
train them to right click on it to save, left click to view)
August 09, 2000 Yong -- Thanks for the question regarding "Enable
      Novalidate does not work for PK?", version 8.1.5

      You Asked
I know NOVALIDATE works for foreign keys. But it doesn't seem to
work for primary keys:

SQL> create table q (a number, constraint pk_q primary key (a));

Table created.

SQL> alter table q disable constraint pk_q;

Table altered.

SQL> insert into q values (1);

1 row created.

SQL> insert into q values (1);

1 row created.

SQL> alter table q modify constraint pk_q enable novalidate;
alter table q modify constraint pk_q enable novalidate
*
ERROR at line 1:
ORA-02437: cannot validate (INDIGO2.PK_Q) - primary key violated

SQL> alter table q enable novalidate primary key;
alter table q enable novalidate primary key
*
ERROR at line 1:
ORA-02437: cannot validate (INDIGO2.PK_Q) - primary key violated

      and we said...
You can do this with a deferrable constraint.  These are
enforced with non-unique indexes.  They are not the default (so
by default -- unique index).

It would look like:

ops$tkyte@8i> create table t
  2  ( x int,
  3    constraint t_pk primary key (x)
  4    deferrable initially immediate );

Table created.

ops$tkyte@8i>
ops$tkyte@8i> alter table t disable constraint t_pk;

Table altered.

ops$tkyte@8i>
ops$tkyte@8i> insert into t values ( 1 );

1 row created.

ops$tkyte@8i> insert into t values ( 1);

1 row created.

ops$tkyte@8i>
ops$tkyte@8i> alter table t modify constraint t_pk enable
novalidate
  2  /

Table altered.

ops$tkyte@8i>
ops$tkyte@8i> insert into t values ( 1);
insert into t values ( 1)
            *
ERROR at line 1:
ORA-00001: unique constraint (OPS$TKYTE.T_PK) violated

ops$tkyte@8i>
Review & Followup

      Rating: 4
...or
      pre-create the index on pk as non-unique  October 30, 2001

Reviewer:  Nj?l A. Ekern  from Norway
Very appliciable that Oracle creates non-unique indexes for deferrable unique
constraints.

Another way to do this is to pre-create a non-unique index on the primary key.
The creation of the primary key will not create an index automatically if a
similar index (unique or non-unique) already exists on the pk-columns:

SQL> create table q (a number);

Table created.

-- Now, create a non-unique index:

SQL> create index pk_q on q(a);

Index created.

SQL> alter table q add(constraint pk_q primary key (a));

Table altered.

SQL> alter table q disable constraint pk_q;

Table altered.

SQL> insert into q values (1);

1 row created.

SQL> insert into q values (1);

1 row created.

SQL> alter table q modify constraint pk_q enable novalidate;

Table altered.

SQL> insert into q values (1);
insert into q values (1)
*
ERROR at line 1:
ORA-00001: unique constraint (xxx.PK_Q) violated

SQL> insert into q values (2);

1 row created.

SQL> commit;

Commit complete.

SQL> select * from q;
         1
         1
         2

3 rows selected.

      Rating:
      5
  January 06, 2004
Reviewer:  Puneet
      Mathur  from India
Excellent search was excatly what i wanted

August 09, 2000 Erin -- Thanks for the question regarding
      "Inserting a COLUMN into the MIDDLE of a table...", version 8.1.6

      You Asked
Tom,
 Thank you so much for your quick response of my prior two
questions. I am almost done with a script that will
automatically
export ALL PROD modules in webdb in to a single file.
 Anyway, my question today revolves around a request to insert
a field into the middle of a table.  The table currently has
over
3 million rows.  What's the best way to do this?
  1.  I know I could rename the old table, create the new one
and
       do a select into... but I was concerned about logging.

  2.  I was then thinking of using sqlloader, but excuse me for
      being so simple minded today, but I cannot find a way to
obtain
      a file of the data that I can use as input for the
sqlloader job.

If you can offer a suggestion, I would appreciate it.  I am
going
to look around in the meantime...  Thanks again, Erin

      and we said...
Well, there is no real way to add a column to the middle of a
table and there really should not be any reason to do so.  A
well behaved application should never rely on the physical order
of columns as they would be returned from a "select *" as it is
not defined and could change.  If you need columns in a
certain order -- you should explicity select them in that order.

The fastest, easiest, least resource intensive way will be:

o alter table T add new_column
o rename T to T_TABLE
o create view T as select columns-in-correct-order from T_TABLE
o revoke all on T_TABLE
o grant on T

No one will know the difference between the view and the
table...

I would do the above (actually -- I would not want to be
dependent on column order!)

My comment on #1 above would be "create table ... nologging" or
insert /*+ APPEND */ into ... will avoid redo generation....

My comment on #2 would be see

http://osi.oracle.com/~tkyte/flat/index.html
it does that.
August 09, 2000
      christophe -- Thanks for the question
      regarding "public and private RBS", version 8.1.6

      You Asked
By default, db assistant creates public RBS which don't require
declaration in init.ora :

# If using private rollback segments, place lines of the
following
# form in each of your instance-specific init.ora files:
#rollback_segments = ( RBS0, RBS1 )

But, in past, oracle suggested that public RBS should be used
only for multi-instance databases.
Is there anything new with RBS ?

      and we said...
Public vs Private rollback segments only have meaning in a
Parallel Server (clustered) environment.  In a single instance -
public rollback segments are somewhat easier to use since they
do not require listing in the init.ora.

If not using OPS -- they are the same (with the exception of
having to list them)
August 09,
      2000 Hina -- Thanks for the question
      regarding "SPOOL FILE IN PLSQL", version Oracle 7

      You Asked
Hi,

I am writing plsql and based on certain condition(if it returns
x number of records), I would like to write in file(spool
file.txt).  Unlike sqlplus can How can I spool file in PLSQL.

Thank you

      and we said...
See UTL_FILE.  that is an API with which PLSQL can write to a
file on the server.

PLSQL cannot issue a "spool" command (as that is purely a
sqlplus'ism -- its a feature of sqlplus, not of SQL or PLSQL).
PLSQL output can be spooled however.
August 09, 2000 Daniel -- Thanks for the question regarding
      "Developer 6.0 with calculation in field", version ORACLE8i

      You Asked
Hi Tom,

I have a block (register_detail) with multi line.
In this block I have a columm (SUB_CND_TOTAL).
I want a summary of this columm (SUB_CND_TOTAL) in a single
field (TOTAL_CND).
Can I use the option formula? or other way?

Thanks a lot !

Daniel

      and we said...
o create a display item (DI)
o set the datatype of this DI to number
o set the calculation mode to Summary
o set the summary function to SUM
o set the summarized block + item to block-name + sub_cnd_total
o set the block attribute of the block you put the summary DI on
to "precompute summaries".

thats it...
August 09, 2000 arvind -- Thanks for the question regarding
      "Table Joins and ResultSets", version 8i

      You Asked
Movie Table
Movie_Id     Varchar (primary key)
Movie_Name   Varchar

Artist Table
Artist_Id    Varchar  (primary key)
Artist_Name  Varchar

Artist_Movie
Movie_Id    Varchar   (foreign key)
Artist_Id   Varchar   (foreign key)

the above is the database structure. i have an intermediate
table where artist and movie are there(Artist_Movie).

now how do i select common movies of 4 artist from this
structure?

can you help me with this, i"ll be oblized.

      and we said...
select movie_id
  from artist_movie
 where artist_id in (:artist_1, :artist_2, :artist_3, :artist_4)
 group by movie_id
having count(*) = 4;

and if you need the movie info it would be:

select * from movie_table where movie_id in ( THAT_QUERY_ABOVE
);

That gets a list of movies that ALL 4 artists worked in.  You
would adjust the "having count(*) = 4" to "having count(*) = 2"
for example to find all movies that at least 2 of the 4 worked
on and so on...

August 09, 2000 Martin -- Thanks for the question regarding
      "Unique constraints by non-unique indexes on local partition indexes",
      version 8.1.6.1

      You Asked
Hi all,

we want to enforce a primary key constraint in 8.1.6.1 in a
partitioned table where the partition key is not part of the
index columns. The doc reads

"Note that:

Constraints use existing indexes; they do not create indexes
unless necessary.

Unique and primary keys can use non-unique as well as unique
indexes. They can even use just the first few columns of
non-unique indexes.

At most one unique or primary key can use each non-unique index.

The column orders in the index and the constraint do not need to
match.

If you need to check whether an index is used by a constraint,
for example when you want to drop the index, the object number
of the index used by a unique or primary key constraint is
stored in CDEF$.ENABLED for that constraint. It is not shown in
any catalog view. "

This works very well for non-partitioned tables:

SQL>
SQL> drop table test cascade constraints;

Table dropped.

SQL>
SQL> create table test (
  2           n integer
  3           , d date
  4  )
  5  /*
  6  partition by range (d)
  7  (
  8           partition test_p1 values less than (to_date
('01.01.2000', 'DD.MM.YYYY'))
  9           , partition test_p2 values less than (to_date
('01.01.2001', 'DD.MM.YYYY'))
 10           , partition test_p3 values less than (maxvalue)
 11  )
 12  */
 13  /

Table created.

SQL>
SQL> create index test_i
  2  on test (n)
  3  /*
  4  global
  5  partition by range (d)
  6  (
  7           partition test_p1 values less than (to_date
('01.01.2000', 'DD.MM.YYYY'))
  8           , partition test_p2 values less than (to_date
('01.01.2001', 'DD.MM.YYYY'))
  9           , partition test_p3 values less than (maxvalue)
 10  )
 11  */
 12  /

Index created.

SQL>
SQL> alter table test add (constraint test_pk unique (n));

Table altered.

SQL>
SQL> select index_name, partitioned, uniqueness from
user_indexes where table_name = 'TEST'
  2  /
TEST_I                         NO  NONUNIQUE

SQL>
SQL> spool off

However, this does not work with partitioned tables:

SQL>
SQL> drop table test cascade constraints;

Table dropped.

SQL>
SQL> create table test (
  2           n integer
  3           , d date
  4  )
  5  partition by range (d)
  6  (
  7           partition test_p1 values less than (to_date
('01.01.2000', 'DD.MM.YYYY'))
  8           , partition test_p2 values less than (to_date
('01.01.2001', 'DD.MM.YYYY'))
  9           , partition test_p3 values less than (maxvalue)
 10  )
 11  /

Table created.

SQL>
SQL> create index test_i
  2  on test (n)
  3  local
  4  /

Index created.

SQL>
SQL> alter table test add (constraint test_pk unique (n));
alter table test add (constraint test_pk unique (n))
*
ERROR at line 1:
ORA-01408: such column list already indexed

SQL>
SQL> select index_name, partitioned, uniqueness from
user_indexes where table_name = 'TEST'
  2  /
TEST_I                         YES NONUNIQUE

SQL>
SQL> spool off

What can I do? Please help.

Martin

      and we said...
The problem is N is not part of the partition key -- we cannot
use the partitioned index to enforce uniqueness.  A given value
of N (say the value n=1) can be in EVERY index partition.  We
would need to partition by N and then would could use that
index.

The statement is:

...they do not create indexes unless necessary...

In this case -- it is necessary as there are lots of little
indexes that would have to be scanned -- not just one index
structure that could be used.

It would also void most all of the advantages of partitions if
we allowed this such as better availability and scalability --
each and every partition would always have to be totally
available to do any inserts/updates.

Additionally -- we would have to serialize inserts/updates
to this table at the transaction level since if we added N=1 to
partition 1 -- we would have to somehow PREVENT anyone else from
adding N=1 to partition 2 or 3 -- the only way to do that would
be to prevent them from modifying partitions 2 and 3 since there
isn't anything to really "lock" over there....

This shows that this CAN work on partitioned tables (if N is
part of the partition key)

ops$tkyte@8i> drop table test cascade constraints;

Table dropped.

ops$tkyte@8i>
ops$tkyte@8i> create table test (
  2           n integer
  3           , d date
  4  )
  5  partition by range (n)
  6  (
  7           partition test_p1 values less than (50)
  8           , partition test_p2 values less than (100)
  9           , partition test_p3 values less than (maxvalue)
 10  )
 11  /

Table created.

ops$tkyte@8i>
ops$tkyte@8i> create index test_i
  2  on test (n)
  3  local
  4  /

Index created.

ops$tkyte@8i>
ops$tkyte@8i> alter table test add (constraint test_pk unique
(n));

Table altered.

This follows from the statement that:

<quote>
A local index can be created UNIQUE if the partitioning columns
form a subset of the index columns. This restriction guarantees
that rows with identical index keys always map into the same
partition, where uniqueness violations can be detected.
</quote>

A local index that contains non-partition key columns cannot
by used to enforce uniqueness.

August 10, 2000 john -- Thanks for the question regarding "SQL
      command", version 8.1.5

      You Asked
I have just started learning sql and i'm having some problems
with some of the questions. I have four groups of 15 questions
and was hoping you may be able to help me with one question from
each group so i can get an idea of the commands i would have to
use.

comm=commission
sal =salay
loc =location
mgr =

Table EMP contains EMPNO,ename,job,deptno,mgr hiredate,sal,comm
     Key in CAPS
Table DEPT contains DEPTNO,dname,loc

1.Using the EMP table find the three most command jobs listed

displayed results
   job          Count(*)
  Clerk            4
 Manager           3
Salesman           3

2 Using the EMP table find the top three eaners in the company.
Display their names and salary. If more than three employees
share the honor, then show them all.

displayed results
ENAME    SAL
SCOTT    3000
KING     5000
FORD     3000

3 Using the DEPT and EMP table, and a correlate subquery, find
all the departments with NO employees. Display the department
and name.

displayed results
DEPTNO      DNAME
   40       OPERATION

4 Using the EMP table, find the year in which most people joined

the company. Display the year and number of employees joined.
Use
the headings Year and NUMBER_OF_EMPS

displayed results
YEAR       NUMBER_OF_EMPS
1981             10

Thank you for your help
john Boober

      and we said...
This smells like homework.

#1, question is ambigous.  What if I have a table with 100 rows
and jobs job1, job2, job3, ... , jobN.  Now I have 100 jobs that
occurr "most commonly" -- not three.

do you want a random 3 from the top?

do you want the UPTO three job catagories that occur the most
(eg: given the above table the result set would be EMPTY)?

its not clear -- its a poorly worded question....

you could do this in at least 2 ways (definitely more exist).

scott@8i> select job, count(*)
  2    from emp
  3   group by job
  4   order by 2
  5  /

JOB         COUNT(*)
--------- ----------
PRESIDENT          1
ANALYST            2
MANAGER            3
CLERK              4
SALESMAN           4

scott@8i>
scott@8i> select *
  2    from ( select job, count(*)
  3             from emp
  4            group by job
  5            order by 2 desc )
  6  where rownum <= 3
  7  /

JOB         COUNT(*)
--------- ----------
CLERK              4
SALESMAN           4
MANAGER            3

scott@8i> select a.*
  2    from ( select job, count(*) as cnt
  3             from emp
  4            group by job ) a
  5   where 3 > ( select count( count(*) )
  6                 from emp
  7                group by job
  8               having count(*) > a.cnt)
  9   order by 2 desc
 10  /

JOB              CNT
--------- ----------
CLERK              4
SALESMAN           4
MANAGER            3

#2 Another poorly worded question.  I'll have to assume you
want:

the set of people making the top three SALARIES.

scott@8i> select ename, sal
  2    from emp
  3   order by sal desc
  4  /

ENAME             SAL
---------- ----------
KING             5000
SCOTT            3000
FORD             3000
JONES            2975
BLAKE            2850
CLARK            2450
ALLEN            1600
TURNER           1500
MILLER           1300
WARD             1250
MARTIN           1250
ADAMS            1100
JAMES             950
SMITH             800

14 rows selected.

scott@8i>
scott@8i> select ename, sal
  2    from emp
  3   where sal in ( select sal
  4                    from ( select distinct sal
  5                             from emp
  6                            order by 1 desc )
  7                   where rownum <= 3 )
  8  /

ENAME             SAL
---------- ----------
JONES            2975
SCOTT            3000
FORD             3000
KING             5000

#3

scott@8i> l
  1  select deptno, dname
  2         from dept
  3        where not exists ( select null from emp
  4*                         where emp.deptno = dept.deptno)
scott@8i> /

    DEPTNO DNAME
---------- --------------
        40 OPERATIONS

#4  Another ambigous question -- don't forget there may be more
then 1 most "popular" year.

select to_char(hiredate,'yyyy'), count(*)
  from emp
 group by to_char(hiredate,'yyyy')
having count(*) >= all (select count(*)
                           from emp
                          group by to_char(hiredate,'yyyy') )
/

August 10, 2000 Louie -- Thanks for the question regarding "Data
      transfer from AS/400 to Oracle", version 8.0.5.0.0

      You Asked
Hi,
I need to transfer data from AS/400 datafiles to Oracle tables. I know I could
convert the AS/400 data to text first and then use SQL*Loader to load into
Oracle tables (this is what I am doing to convert Excel data file to Oracle).
But is there a way which I can make the process easiler? Ultimately, my users
are going to do the transferring of data and I don't expect them to know how to
use SQL*Loader. They are expecting to click only a button and VOOM, data are
transferred from AS/400 to Oracle. Please advice, thanks in advance.

      and we said...
Sounds like you are looking for the transparent gateway to AS/400.  This will
let you query and modify an AS/400 database as if it were a local Oracle
database from Oracle.  Thus, moving data from Oracle to AS/400 or vice versa is
as easy as a INSERT.

I'll send you a data sheet in another email...
August 10, 2000 Jolly -- Thanks for the question regarding "How
      to execute .sql files without actually going to SQLPLUS", version
      Developer 6

      You Asked
Tom,

I am developing Installation program using Developer 6. I would
like to run lot of .sql scripts which creates all my objects in
the database. I don't want the program to go to sqlplus each and
every time to execute .sql file.

Can you suggest me a better way.

Thank you
Jolly

      and we said...
you would have to write your own sqlplus then.  SQLPLUS is an
environment that supports a scripting language -- a series of
sql statements with specific delimiters and such.  If you don't
want to use sqlplus -- you'll have to write your own script
interpreter.

You could use text_io to read a .sql file and forms_ddl() or
exec_sql to execute any arbitrary sql yourself if you want to.
You would have to write your own simple parser to do this.
August 10, 2000 Michael -- Thanks for the question regarding
      "PL/SQL-Stored-Function in OCI", version 8.0.5

      You Asked
Dear Tom,

how can I receive the function-value of a stored PL/SQL function
in a C programm using the OCI-interface?

The manuals only state examples of returning values by using
out-
parameters of stored-procedures. Receiving the return-value of
a function is not mentioned.

Thanks for the advice,
  Michael

      and we said...
An return value of a function is just like and OUT parameter of
a procedure.

if I had a package:

  create package t
  as
    procedure p( x out number );
    function f returns number;
  end;

I would be executing a block like:

  begin p(:x); end;

or

  begin :x := f; end;

I would bind to :x in exactly the same way in each.  There is no
difference...
August 10, 2000
      arvind -- Thanks for the question regarding
      "How to export data from one platform(windows nt) to another (solaris)",
      version 8i

      You Asked
hi,

i have some data structures and data on windows nt platform. i
want to transfer all data structure and data to oracle 8i
running on solaris platform. how can i do it. i am trying it by
jdbc where i wish to use thin client driver for solaris and odbc
driver for windows nt. kindly tell me what is the right
approach.

thank you.

arvind

      and we said...
I would use the EXP tool in Windows NT.  Then binary ftp the
.dmp file to Solaris.  I would then run the IMP tool on Solaris.

That'll move all of the data for you.

Note: its not mandatory to move the file even, you could run IMP
into solaris on the NT machine over sqlnet.
August 10, 2000 Carsten -- Thanks for the question regarding
      "INtermedia Text Fuzzy Search", version 8.1.6

      You Asked
Hi Tom,

what measure of the score should we use for the best seach result.
We use 30, but got a lot of answers.

;) Carsten

      and we said...
The score is totally relative to the result set each and every time.  There is
no "best" score to use to get the "best" search (generally speaking).

What I do is:

select *
  from ( select score(1),  ...
           from t
          where contains( ...., 1 )
          order by 1 desc )
 where rownum <= :MAX_ROWS_TO_GET
/

Its what I do on the "ask tom" search interface....

August 10, 2000 GAURANG -- Thanks for the question regarding
      "DB_BLOCK_GETS AND CONSISTANT GET", version 8.1.5

      You Asked
CAN YOU EXPLIN ME ABOUT DB_BLOCK_GETS AND CONSISTANT GET
(USE TO CALCULATE HIT RATIO)

      and we said...
YOU DON'T HAVE TO SHOUT ;)

"db block gets" counts logical reads in current mode.  Also includes direct read
blocks (sort-on-disk) blocks.

"consistent gets" counts the logical read in consistent mode.

db block gets would be blocks gotten in 'update' mode for example -- or queries
against some parts of the data dictionary.  consistent gets are our normal
consistent reads (you'll have lots more of these then db block gets normally).

the sum of these two numbers are the total number of logical reads done.  You
get the physical reads and you can now compute a cache hit....
August 10, 2000 Vinnie -- Thanks for the question regarding
      "CTAS", version 8.1.5

      You Asked
Tom,

I am trying to use CTAS to create a duplicate table:

CREATE TABEL t AS SELECT * from e
where 1=2;

Is there a way to also include all the storage defs?
(initrans, maxtrans......)

Vinnie

      and we said...
No, you would have to write SQL to write SQL to do that.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:47812348053,%7BMOVE%7D%20and%20%7BTABLES%7D
for an example of what I mean.  It creates table table MOVE
statements, not create table as select, but the concept is the
same.

August 10, 2000 Seetharaman -- Thanks for the question regarding
      "Oracle - XML", version 8i Rel 2

      You Asked
Hi Tom

  Good Morning.

  I have installed Oracle 8i Rel 2 on a Win NT server.  I've IIS
4.0 and I'm able to run asp pages.

  Now my question is I want to create and run XML pages thro'
famous Oracle and not thro' any infamous software packages.  I
went thro' the write up provided in www.oracle.com/xml site but
it seems to be very vague with respect to what softwares or
packages should db has to have.

  Pls. let me know what are all the kit I should have in my
system to start the Oracle-XML application.

Thanks in advance

Seetharaman Srinivasan

      and we said...
Its all at

http://technet.oracle.com/tech/xml/
...
August 10, 2000 Michael -- Thanks for the question regarding
      "Using UTL_FILE", version 8.0.6.0.0

      You Asked
We're creating stored procedures to export data from the
database to a flat file, however in using the UTL_FILE package
we are encountering some problems.  While we have been able to
write strings to the output file, we have not been successful
writing host variables.  Can you point me to any good
documentation on using the package, and is it necessary to
perform any additional setup aside from adding the package to
the oracle init file?

Thanks,

Mike

      and we said...
see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:88212348059
It has a full example of creating a flat file using a stored
procedure with PLSQL.

If that doesn't work for you -- let me know.....

The supplied packages guide goes into UTL_FILE.
Review &
      Followup

      Rating:
      3
  March 26, 2001
Reviewer:  faris
       from paris, france

August 10, 2000 Pouneh -- Thanks for the question regarding
      "Loading from flat file into db table", version 8.1.5

      You Asked
I was wondering if you could give me the exact syntax
for loading data from a flat file into a database table.
I know I am supposed to use the LOAD command but I don't know
the exact syntax. I have some control over the content of the
flat file (i.e., what delimeters it will have). The fields in
the file will match the columns in the table in which they
are to be loaded.
Thanks
Pouneh Etemad

      and we said...
The command is "sqlldr".  You must create a control file (see
examples in $ORACLE_HOME/rdbms/demo/*.ctl).  For example:

LOAD DATA
INFILE *
INTO TABLE DEPT
replace
FIELDS TERMINATED BY X'9'
(DEPTNO, DNAME, LOC)
BEGINDATA
12      SARATOGA
10  ACCOUNTING  CLEVELAND
11  ART SALEM
13  FINANCE BOSTON
21  SALES   PHILA.
22  SALES   ROCHESTER
42  INT'L   SAN FRAN

loads tab delimited data.  I have it setup to load from INFILE *
so it assumes the data is inline. If the data existed in
test.dat, the .ctl file would look like:

LOAD DATA
INFILE test.dat
INTO TABLE DEPT
replace
FIELDS TERMINATED BY X'9'
(DEPTNO, DNAME, LOC)

and my command line would be:

sqlldr user/password test.ctl

August 11, 2000 Sujatha -- Thanks for the question regarding "NLS
      support", version 8.1.6

      You Asked
we have a requirement where in we need to publish web pages in
different languages. We are thinking to have one table to store
data for all languages. Is it possible to have data in more than
one language in one table. For example in a single table can we
have data in english as well as chinese

      and we said...
Yes, as long as your character set supports it.  For "big
charactersets" like chinese, you will want to look at UTF8.

see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:327817160881,%7BUTF8%7D
for some more info.

August 11, 2000 habeebuddin -- Thanks for the question regarding
      "SqlPlus Query and output result sets", version oracle 8.x

      You Asked
Sir,

  Q1).  Please show me a query criteria to find the duplicate
record(s) in a table.

  Q2).  I created one procedure on database level wich has two
output parameters as a result.  I want to execute this procedure
on SqlPlus and want to see the values of these two variables as
output on the SqlPlus screen.  Please help me regarding this.

      and we said...
1) You would code:

   select count(*), a, b, c, ...
     from t
    group by a, b, c, ....
   having COUNT(*) > 1;

that will show you "dups" and tell you how many times they
actually appear.

2) You would use bind variables.  Lets say the procedure gives a
number and a date as outputs.  You could:

ops$tkyte@8.0> create or replace procedure p( x out number, y
out date )
  2  as
  3  begin
  4          x := 55;
  5          y := sysdate;
  6  end;
  7  /

Procedure created.

ops$tkyte@8.0>
ops$tkyte@8.0> variable a number
ops$tkyte@8.0> variable b varchar2(50)
ops$tkyte@8.0> set autoprint on
ops$tkyte@8.0>
ops$tkyte@8.0> exec p( :a, :b )

PL/SQL procedure successfully completed.

B
----------
11-AUG-00

         A
----------
        55

August 11, 2000 SUDIP -- Thanks for the question regarding
      "developer 2000/6i -- setting iconic property", version 6i

      You Asked
how to set the property of a push button as ICONIC = 'TRUE'
dynamically writing PL/SQL in the trigger when_new_form_instance?

      and we said...
You cannot.  The ICONIC property can only be set in the form
builder.

What you might be able to do is have 2 buttons.  One is iconic
and one is not.  You should hide/show the appropriate button.
They would share common trigger code (eg: the code for the
when-button-pressed would actually be a procedure so each
buttons when-button-pressed trigger is a one line trigger that
calls a procedure)
August 11, 2000
      Sing -- Thanks for the question regarding
      "Oracle Forms -- where is the documentation", version 8.0.6

      You Asked
Tom,

I haven't used Oracle forms/solaris  in a long time and I would
like to know link the right documentation .

Thanks,
Sing

      and we said...
There is only one set of doc, regardless of with
solaris/windows.  See

http://technet.oracle.com/docs/products/forms/doc_index.htm
for the online versions.
August 11,
      2000 Chris -- Thanks for the question
      regarding "Checking that a database is up", version 7.3.4, 8.1.6

      You Asked
Hi Tom,
Is there a really elegant way of detecting that a instance is up
that can be scripted and used against Oracle 7.3.4 and 8.1.6 instances which is
NT and Unix portable (we use Mks toolkit on Nt which simulates a Unix shell).

Thanks
Chris

      and we said...
Elegance is in the eye of the beholder...  One method that works (in unix
anyway, don't know about Mks) is:

#!/bin/csh

sqlplus / <<EOF | grep -q '^Connected to:'
exit
EOF
echo '$status for oracle_sid = ' $ORACLE_SID ' = ' $status

setenv ORACLE_SID foo

sqlplus / <<EOF | grep -q '^Connected to:'
exit
EOF

echo '$status for oracle_sid = ' $ORACLE_SID ' = ' $status

When I run that I see:

$ test.csh
$status for oracle_sid =  ora8i  =  0
$status for oracle_sid =  foo  =  1

showing me ora8i is UP, and foo is DOWN...

August 11, 2000 Ram -- Thanks for the question regarding "New
      feature difference 8 and 8i", version 8i

      You Asked
Hi Tom,
    Can you please point me to any documentation or provide me with the list
which highlights ALL the new features that have been added to Oracle 8i version
from 8 version.

Thanks,

Ram

      and we said...
sure, thats the "getting to know" document...

http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
...
August 11, 2000 Sanjeev -- Thanks for the question regarding "How
      to copy everything from one schema to another schema, all objects,
      priviledges etc.", version 8.1.5

      You Asked
Hi Tom,

Is there any way by which we can copy everything (All objects,
priviledges etc.) from one schema to another schema.

Thanks
Sanjeev

      and we said...
One method, the method I would use, is

$ exp .... owner=X

$ imp .... fromuser=x touser=y

Review &
      Followup

      Rating: 2
OK, but . .
      .  July 18, 2001
Reviewer:  Rob  from
      Edmonton, Alberta
Is there any other way?  Ideally, a method that can be encapsulated in a pl/sql
package.

August 11, 2000 Vinod -- Thanks for the question regarding
      "Impact of ORACLE_SID", version 8.1.5

      You Asked
Tom,

I was curious of the impact of ORACLE_SID.  I know it is set before creating a
database but does it have an impact later? Especially if have multiple databases
on same server.

Thanks

Vinnie

      and we said...
Yes it does.  The ORACLE_SID is used as a key to generate a shared memory
segment id.  The ORACLE_SID is burned into the datafiles.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:318216852435
for more info.


Subject | Article | Last Updated (East coast time)
Maintaing a database log of record changes | article only | Aug 12, 2000 01:04 pm
Log when creating Database | article only | Aug 12, 2000 01:06 pm
patchsets | article only | Aug 12, 2000 01:12 pm
Ora-1555 While Querying During Import | article only | Aug 12, 2000 01:18 pm
setting size of online redo log members | article only | Aug 12, 2000 01:23 pm
pl/sql programming | article only | Aug 12, 2000 01:26 pm
ORACLE 8 FEATURES | article only | Aug 12, 2000 01:27 pm
help with a query..... removing specific duplicates | article only | Aug 13, 2000 09:32 am
Consolidating Datafiles.... | article only | Aug 13, 2000 07:19 pm
Random numbers | article only | Aug 14, 2000 06:18 am
Automatic Startup of Oracle in NT | article only | Aug 14, 2000 06:44 am
ORA-01555 snapshot too old | article only | Aug 14, 2000 09:32 am
Trigger invoking a stored procedure | article only | Aug 14, 2000 12:25 pm
Exporting large databases | article only | Aug 14, 2000 04:22 pm
Key-preserved table concept in join view | article only | Aug 14, 2000 04:29 pm
Is it okay to change passwords on default users | article only | Aug 14, 2000 04:31 pm
Cursor | article only | Aug 14, 2000 04:42 pm
PL/SQL -- how to not wait forever for a locked row. | article only | Aug 14, 2000 07:15 pm
Can Oracle Automatically Shrink a Rollback Segment ? | article only | Aug 15, 2000 06:50 am
FGAC: coming in from OAS4081 | article only | Aug 15, 2000 07:26 am
sql query - Q about julian dates. | article only | Aug 15, 2000 07:54 am
Open Cursors | article only | Aug 15, 2000 07:58 am
procedure error | article only | Aug 15, 2000 06:38 pm
Oracle OLEDB driver for Oracle 8.1.5 (Badly needed) | article only | Aug 15, 2000 06:51 pm
Sequence vs unique number for primary key | article only | Aug 15, 2000 07:08 pm
Different Index | article only | Aug 15, 2000 07:12 pm
SQL Loader --- URGENT -- using recnum in sqlldr | article only | Aug 15, 2000 07:35 pm
Trimming special Characters | article only | Aug 16, 2000 08:23 am
Can partition key updateable ? | article only | Aug 16, 2000 08:44 am
why pga is in shared pool in MTS | article only | Aug 16, 2000 06:12 pm
how character, number and other data stored in oracle | article only | Aug 16, 2000 06:19 pm
Rollback segment and temporary tablespace usage | article only | Aug 16, 2000 08:06 pm
Comparison between OAS and iAS | article only | Aug 17, 2000 08:25 am
Defragmenting system objects | article only | Aug 17, 2000 08:29 am
to select subseconds from dual | article only | Aug 17, 2000 08:32 am
How to export the data from oracle tables to text files with delimitors? | article only | Aug 17, 2000 08:33 am
using DISTINT with ROWNUM | article only | Aug 17, 2000 08:56 am
Which schema do logon triggers fire as ? | article only | Aug 17, 2000 09:01 am
regarding reorganization of table and indices | article only | Aug 17, 2000 09:19 am
InterMedia Text Index | article only | Aug 17, 2000 09:22 am
oracle8 and servlet | article only | Aug 17, 2000 09:29 am
Cost / resource authorization | article only | Aug 17, 2000 09:49 am
How does Oracle know whether to check buffer cache or do I/O? | article only | Aug 17, 2000 01:01 pm
THe Query | article only | Aug 17, 2000 01:44 pm
return result sets from procedures | article only | Aug 17, 2000 02:01 pm
WebDB and SSL | article only | Aug 17, 2000 02:11 pm
regarding sql * net parameters | article only | Aug 17, 2000 02:32 pm
Is there a way to retrieve table DDL from the database ? | article only | Aug 17, 2000 02:49 pm
Sql & PL/SQL | article only | Aug 17, 2000 02:50 pm
What is New with Oracle release 3 | article only | Aug 17, 2000 02:55 pm
Can SQL*Loader load files greater than 2 gig in size? | article only | Aug 17, 2000 02:56 pm
comparing two schemas | article only | Aug 17, 2000 02:58 pm
Stored procedure to limit number of fetched rows with an ORDER BY statement | article only | Aug 17, 2000 03:31 pm
how to get the out parameter in select statement? | article only | Aug 17, 2000 03:41 pm
PL/SQL | article only | Aug 17, 2000 03:44 pm
eliminating rows | article only | Aug 17, 2000 07:26 pm
Select * vs. select A.columnX | article only | Aug 17, 2000 07:41 pm
Oracle XA Library Problem -- database links. | article only | Aug 17, 2000 08:25 pm
MTS Configuration | article only | Aug 17, 2000 08:30 pm
Using DECODE | article only | Aug 18, 2000 07:24 am
8.1.6 | article only | Aug 18, 2000 07:33 am
extents -- what is coalesce | article only | Aug 18, 2000 07:37 am
Undocumented init.ora parameters,converting log file | article only | Aug 18, 2000 07:56 am
pl\sql | article only | Aug 18, 2000 08:04 am
Data Encryption | article only | Aug 18, 2000 08:10 am
Naming Export dmp files in NT | article only | Aug 18, 2000 09:17 am
Rollback segments offline when service reboot | article only | Aug 18, 2000 10:24 am
oracle8 with servlet | article only | Aug 18, 2000 12:59 pm
Running from a UNIX script | article only | Aug 18, 2000 01:41 pm
java.sql.SQLException: No suitable driver | article only | Aug 18, 2000 02:06 pm
Meaning of Values for Privileges in ALL_TAB_GRANTS | article only | Aug 18, 2000 04:30 pm
row(s) 1 - 71 of 71
August 12, 2000 Kaushal -- Thanks for the question regarding "Maintaing a database log of record changes", version Developer 6
You Asked
We want to maintain a log of all database activities
(insertion,deletion and updation of records) by different users
on various tables in a shared schema. For example say whenever
any user performs any database operation, a record is added in
another table stating the username, the nature of operation and
datetime stamp. We know this can be achieved very easily through
table level triggers but can this be done at the schema level.
and we said...
If what you want to record is the username, operation and
timestamp -- you should just enable auditing.  We will do that
automatically for you then.  It is much easier and more
performant then using a trigger.

If you still want to use triggers -- then you will have to place
a trigger per table.  DML triggers are place on discrete objects
only.
August 12, 2000 -- Thanks for the question regarding "Log when creating Database", version Oracle 8.1.5
You Asked
Tom,

Wanted to ask you if Oracle had a log when creating a database to indicate
errors (e.g. Control Files not specified properly in init.ora).  What is the
name of the file and location for both NT and Solaris?

Thanks

Vinnie
and we said...
A record of these activities is kept in the ALERT*.LOG for that database.  This
is typically found in $ORACLE_HOME\admin\$ORACLE_SID\bdump but may be in a
different location depending on your setting for background_dump_destination in
your init.ora.
August 12, 2000 Gopesh -- Thanks for the question regarding "patchsets", version oracle 8.0.3,7.3.4,7.3.2
You Asked
where can I find the latest patches for different versions of Oracle.
I know the website for U.K. but not for North America.

Regards
gopesh
and we said...
You would use
http://metalink.oracle.com/
for that.
Review & Followup
Rating: 4
April 19, 2002
Reviewer: A reader

August 12, 2000 Saibabu -- Thanks for the question regarding "Ora-1555 While Querying During Import ", version 8.1.5
You Asked
Hi,Iam running Import with commit=y.I want to check how far the
import is done for one big table.While selecting count(*) from
that table ora-1555(snapshot too old) error is coming.
    As per my knowledge Rollback Segment only uses rowid's of
newly inserted rows and as soon as RBS wraps into next extent
only when that extent records are already commited,hence there
is no chance for 1555 error.Please Explain in detail.
 Thanks
and we said...
You are getting the 1555 because the IMP process is generating
lots of rollback and you must have very small rollback segments
configured.  Hence IMP is wrapping around and reusing rollback
very quickly.  We need to construct, for your select count(*), a
read consistent view of all of the blocks in the table.  Since
imp is filling them up -- and then overwriting the RBS entries
-- you can and will get an ORA-1555.  (there is most definitely
the chance for a 1555).

If you really want to do this count(*) during the import, make
your rollback segments bigger to begin with so they do not wrap
as frequently.

Better yet, just use FEEDBAK=n on the IMP command and IMP will
tell you how many rows (every N rows) it has done.
August 12, 2000 wallacel -- Thanks for the question regarding "setting size of online redo log members", version 8.1.6
You Asked
Tom:

How to set the size of online redo log members?
bigger is better or smaller is better(or it doesn't matter)?

I don't think there are performace issue regarding the size
of online redo log members because i think
the amount of redo information server generated is indepedent
on the size of redo log member, am i right?

(both in archivelog mode and noarchivelog mode)

if this is true ,in archivelog mode, what i need to do is setup
enough redo log group so archive won't wait for lgwr to finish
its job. am i right?
and we said...
Redo sizing does impact performance.

Every time we log switch, we initiate a checkpoint.  If your
logs are very very small -- we'll checkpoint frequently.  This
will decrease performance.

On the other hand, if your redo logs are very very large -- we
won't checkpoint frequently (unless you have some other
checkpoint init.ora parameters set up) and hence if we crash, it
could take a long time to recover (lots of redo to reapply).

So, you need to trade those two things off -- there is no "one
size is right for everyone".  I've used sizes from 25meg to
1gig.  It just depends.  For everyday use -- I tend to use 25meg
redo log files.  You want them to switch every 20-30 minutes at
most in a "medium" use database (more frequently in a less used
database, less frequently in a mostly read only database).
August 12, 2000 rajendra -- Thanks for the question regarding "pl/sql programming", version oracle 8
You Asked
hi! tom
i want to compare data  from two different tables with identical
columnsa and column names and insert into a third table the
unique records from the first two tables after comparision.

can i insert subseconds in timestamp column....

help will me appriciated...
thank you,Tom
and we said...
you can do this in SQL:

ops$tkyte@DEV8I.WORLD> create table t1 ( x int );

Table created.

ops$tkyte@DEV8I.WORLD> create table t2 ( x int );

Table created.

ops$tkyte@DEV8I.WORLD> create table t3 ( x int );

Table created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> insert into t1 values ( 1 );

1 row created.

ops$tkyte@DEV8I.WORLD> insert into t1 values ( 2 );

1 row created.

ops$tkyte@DEV8I.WORLD> insert into t2 values ( 2 );

1 row created.

ops$tkyte@DEV8I.WORLD> insert into t2 values ( 3 );

1 row created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> insert into t3
  2  ( select * from t1 minus select * from t2 )
  3  union all
  4  ( select * from t2 minus select * from t1 )
  5  /

2 rows created.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> select * from t3;

         X
----------
         1
         3

ops$tkyte@DEV8I.WORLD>
August 12, 2000 madhusudhana rao -- Thanks for the question regarding "ORACLE 8 FEATURES", version ORACLE 8
You Asked
hi,
    I would like to know the Oracle 8 features. Can i get any
oracle document for Oracle 8 features.

Regds.
MadhuSudhana Rao.
and we said...
thats the getting to know Oracle8i document:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
it covers whats new in 8.1.6, 8.1.5, and 8.0
August 13, 2000 -- Thanks for the question regarding "help with a query..... removing specific duplicates", version 8.0
You Asked
Hello sir,

we r receiving invoice thru email. I am importing that data into
a temporary table. That invoice can contain 500 - 1500 records.

pr_import_data
------------
part_no  varchar2(17);
unit_price number(8,3);
..
..
..

In the above temporary table, the entries r supposed to be
unique on PART_NO.  But there can be duplicate records in the
above table. Means one part_no can have more than one entry with
SAME or DISTINCT unit_price.

part_no   unit_price
------   --------
ABCD-M10  10.500
ABCD-M10  20.000
ABCD-M10  10.500
..
..
XY2-P990  .500
XY2-P990  .500
..
..

First I will display an alert for user choice saying
   "Price conflict.. Choose yes->high price, NO->Low price
updation".
As the user selects either option,I should delete duplicate
records in the table.

If he selects Yes then

 Record with Part_no ABCD-M10 & price 20.000 should ONLY be
retained in the table, rest records of that part_no should be
deleted.

if the user selection is no then

Record with Part_no ABCD-M10 & price 10.500 should ONLY be
retained in the table, rest records of that part_no should be
deleted.

** And if unit_price is same in the duplicated records of a
perticular part then irrespective of user choice duplicated
records should be deleted...like for part XY2-P990, Only one
entry should be present.
 and then the process goes on..

Thanks a lot for ur help

regs
mubeen
and we said...
You'll want an INDEX on part_no for this to work OK but here
they are:

ops$tkyte@DEV8I.WORLD> select * from t1;

PARTNO          UNIT_PRICE
--------------- ----------
abcd-m10              10.5
abcd-m10                20
abcd-m10              10.5
xyz-p990                .5
xyz-p990                .5

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> delete from t1
  2   where (rowid,unit_price) <>
  3         ( select min(rowid),unit_price
  4             from t1 b
  5            where b.partno = t1.partno
  6              and unit_price =
  7                    ( select min(unit_price)
  8                        from t1 c
  9                       where c.partno = t1.partno )
 10                       group by unit_price
 11                    )
 12  /

3 rows deleted.

ops$tkyte@DEV8I.WORLD> select * from t1;

PARTNO          UNIT_PRICE
--------------- ----------
abcd-m10              10.5
xyz-p990                .5

ops$tkyte@DEV8I.WORLD> rollback;

Rollback complete.

ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD>
ops$tkyte@DEV8I.WORLD> delete from t1
  2   where (rowid,unit_price) <>
  3         ( select min(rowid),unit_price
  4             from t1 b
  5            where b.partno = t1.partno
  6              and unit_price =
  7                    ( select max(unit_price)
  8                        from t1 c
  9                       where c.partno = t1.partno )
 10                       group by unit_price
 11                    )
 12  /

3 rows deleted.

ops$tkyte@DEV8I.WORLD> select * from t1;

PARTNO          UNIT_PRICE
--------------- ----------
abcd-m10                20
xyz-p990                .5
August 13, 2000 Raghu -- Thanks for the question regarding "Consolidating Datafiles....", version 7.3.4
You Asked
Tom,

I need to know if there is a way to cosolidate datafiles in a
particular tablespace(Index and USER tablespace). Currently
there are over 120 datafiles which are very small in size. I
want to roll them up into one or maybe two large datafiles. Is
there a wasy to do this without having to do a full export and
import?
Thanks for you advice.

Raghu Ramanna.
and we said...
Sorry but no.  You'll have to export the data in this
tablespace, drop it (the tablespace) and rebuild it with 1
datafile.

Consider using "alter database datafile '/file/name.dbf' resize
Xmeg" in the future (as opposed to adding lots of little files).

In Oracle8i, release 8.1, we can do this without exp/imp using
"alter table T MOVE".... and alter index I rebuild ....
August 14, 2000 rajashekar -- Thanks for the question regarding "Random numbers", version 1.8.0.6
You Asked
Hi Thomas

I want to generate a random no. instead of the sequential
generator can i do that. The no. generated should be the unique
and it is used as an id in the table.

Awaiting to ur earliest reply

Regards
Raj
and we said...
"random" and "unique" -- no such thing exists (it would no
longer be random)...

What I've done in the past is to use both a random number as
well as a sequence to remove all practical chances of collision.
 So, I would return:

 random_number || mod(to_char(sequence_number,'fm00009'),100000)

In that fashion, the chance of a collision is 1 in 100,000.
Alternatively, what I've also seen done is:

 random_number||lpad(to_char(sysdate,'dddsssss'),8,0)
August 14, 2000 Victor -- Thanks for the question regarding "Automatic Startup of Oracle in NT", version 8.0.5.0.0
You Asked
Can you help me how to create a script that checks whether the
database is not mounted/opened in NT at any time and then run
this script to mount/open it if it is false?  Thanks in advance
and more power to you!
and we said...
Sure, lets say you have a .SQL script:

--------------- test.sql ---------------------------------
set serveroutput on
set feedback off
spool temp.cmd
exec dbms_output.put_line( 'echo Database is UP' )
spool off
exit
--------------- eof --------------------------------------

and a .CMD file:

----------------- checkup.cmd ----------------------------
echo net start OracleServiceTKYTE816 > temp.cmd
sqlplus tkyte/tkyte @test.sql < nul
temp.cmd
---------------------- eof --------------------------------

That'll do it (replace the name of the OracleServiceTKYTE816
with YOUR service to start the database.  If sqlplus can get
logged in -- then test.sql we rewrite the temp.cmd script with a
simple "echo Database is up".  Else temp.cmd will have the
command to start the database.
August 14, 2000 GAURANG -- Thanks for the question regarding " ORA-01555 snapshot too old", version 8.1.5
You Asked
Could you explain me why this error occur
ORA-01555 snapshot too old
i heard that if you commit frequently in batch transcation than this occur.
and we said...
Please goto
http://osi.oracle.com/wa/ask/owa/ask_tom_pkg.search
and search on 1555.  It'll get about 7 hits and they are all relevant to your
question (especially the first hit)
August 14, 2000 Doug -- Thanks for the question regarding "Trigger invoking a stored procedure", version 8.1.6
You Asked
Tom,
We want to invoke a specific stored procedure based upon a row
being inserted into a table. The specific stored procedure to
invoke is based on a value of a column being inserted into the
trigger table. The stored procedure(s) that we would invoke have
COMMITs and ROLLBACKs. When we insert the row and fire the
trigger to run the stored procedure we get:

insert into temptrig values (2740,3)
            *
ERROR at line 1:
ORA-04092: cannot ROLLBACK in a trigger
ORA-06512: at "DEV2.P_867_PROD_TRANSFER_INSRT", line 3683
ORA-06512: at "DEV2.TI_TEMPTRIG", line 9
ORA-04088: error during execution of trigger 'DEV2.TI_TEMPTRIG'

We surmised you can't have a COMMIT or ROLLBACK within the
'range' of a fired trigger... Is that correct and, if so, can
you think of a work-around?
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:486421585357
for your solution (remember though -- commiting in a trigger is
a terribly bad practice that should be avoided at all cost--
what if you insert 2 rows with a single statment and one row
goes in -- fires the trigger -- commits the work done by that
procedure and then the second row fails -- rolling back the
first insert.  What you'll have is that the procedure ran,
committed but the statement that fired the trigger did not.
It's really messy.)
August 14, 2000 Ramana -- Thanks for the question regarding "Exporting large databases", version 8.1.5
You Asked
Hi,
  My system is working on oracle version 8.1.6 and sloaris 2.6.
When I tried to export the database, it is exporting until the
export file is 2GB. As soon as it reaches 2GB it is terminating
and giving error EXP-002 and system error message 27.  Can give
me whether it is bug or limitation on export file and what is
the solution for this problem.
Thanks
Ramana
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:122612348063
for the solution (not a bug, 2 gig file limit with the export
tool when you export to a device that supports seeking.  The
solution is to export to a different type of device)...

In addition to the script referenced above which uses
compression and split, you can also use FILE and FILESIZE with
exp on 8.1.5 and up.  FILESIZE will set a max output file size
at which point exp will stop writing that file and go onto
another file (sort of like split would do).

See
http://technet.oracle.com/doc/server.815/a67792/ch01.htm#17078
for the details.
August 14, 2000 GAURANG -- Thanks for the question regarding "Key-preserved table concept in join view", version 8.1.5
You Asked
Could you explain me about  Key-preserved table  concept
in join views.i know that a table is ket preserved if every key of the table can
also be a key of result of the join.
but i not understand meaning of this.

Thanks
and we said...
Key preserved means the row from the base table will appear AT MOST ONCE in the
output view on that table.

For example, lets say I have tables T1 and T2 and a view:

create view T
as
select * from t1, t2 where t1.x = t2.y
/

Now, I do not know if for any given row in T1 if it will appear in the output
result set 0, 1 or MANY times (eg: if a given t1.x is joined to every row in t2
by y and there are 2 rows in t2 with the same value for y -- then that row in t1
will be output 2 times).

For example, say you have:

T1.X                      T2.Y
------                    --------
1                         1
                          1

That single row T1 in the view will be output 2 times.  If we were to issue:

 update T set x = x+1;

The outcome would be to set X=3, since it appears in there 2 times.  That is
not key preserved and we will not allow that to happen (the results can be
ambigous depending on an access plan -- the same statements could result in
DIFFERENT data in the database depending on how we access the data).

So, if you can assert that a given row in a table will appear at most once in
the view -- that table is "key preserved" in the view.  It sounds backwards
because in our example above -- its T2 that needs a unique constraint on Y if we
want T1 to be key preserved (you put the key on T2, not on T1 to key preserve
T1!)

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:273215737113
for more examples....
August 14, 2000 Bruce -- Thanks for the question regarding "Is it okay to change passwords on default users", version 8.1.5.0.5
You Asked
When a database is created and the various scripts run, some
users are created.  Can the password be changed on these userids
(like DBSNMP and OUTLN) without harming the database?  If an
alter user is done to change the passwords, where else should
they be changed?  We don't explicity use these userids for
anything ourselves and would like to close up a potential
security risk by changing any passwords assigned to non-default
values.

Thank-you for you assistance,
Bruce
and we said...
It is not only OK, it is highly recommended to alter these users
passwords.

Just change then -- you can change them back at a later date if
we need to update them with a patch or whatnot.
August 14, 2000 Manoj -- Thanks for the question regarding "Cursor", version 8.0.3.0.0
You Asked
I want to get some Records out of my database. I want to store
them in a temporary table.
But the Declaration of the Cursor will vary each time. I mean
the column names may vary, their sor order will vary,

My question is
Is there any way I can make the declaration of a Cursor,
Dynamic.
I want to do it in PL/SQL.

I need to use a cursor
the cursor declaration may be
CURSOR c1 is SELECT * FROM emp WHERE empno=a_variable_name1 and
empdate=a_variable_name2;

or the same cursor may be like this
CURSOR c1 is SELECT * FROM emp WHERE dept=a_variable_name3;

There are 50 different cominatuions of these.

What i ideally want is

PROCEDURE test(select_clause VARCHAR2)
AS
    CURSOR c1 is SELECT * FROM emp WHERE || select_clause;
BEGIN
    OPEN c1;
    FETCH c1 INTO ...
    ...
    ...
    ...
    CLOSE c1;
END;

DECLARE
    select_clause varchar2(200);
BEGIN
    select_clause:=' dept=SALES';
    test(select_clause);
    select_clause:=' empno=50 AND MANAGER=KUTTAN';
    test(select_clause);
END;

I know this does not wok this way. Is there some other methods
to achive what I want?

Thank you
Manoj
and we said...
In Oracle8i, release 8.1, we can

  open some_cursor for 'some string' using bind_vars;

In 8.0, we cannot.  In 8.0 and before, we can however use
DBMS_SQL.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:235814350980
for a generic example using dbms_sql in 8.0...
August 14, 2000 senthilkumar -- Thanks for the question regarding "PL/SQL -- how to not wait forever for a locked row.", version 7.3.4
You Asked
If I want to catch or timeout on a deadlock (hang on exclusive
lock) for an update in a pl/sql batch script, how can I do this?
and we said...
Well -- its not a deadlock, deadlocks are situations that unless
the server killed one of the statements -- you would both stay
locked forever.

Deadlocks are detected and taken care of automagicially.

This is just a "regular" lock.  If you do not want to wait
forever, what you do is:

declare
   l_rec    T%rowtype;
begin

   ...

   select *
     into l_rec
    where <some_condition>
      FOR UPDATE NOWAIT;

   update T set .....
    where <some_condition>;

For example, I ran this block in two sessions, this is the
output from the second session:

scott@8i> declare
  2          l_rec   emp%rowtype;
  3          busy    exception;
  4          pragma  exception_init(busy,-54);
  5  begin
  6
  7          select * into l_rec
  8            from emp
  9           where rownum = 1
 10             FOR UPDATE NOWAIT;
 11
 12          update emp
 13             set sal = sal*1.1
 14           where rownum = 1;
 15  exception
 16          when busy then
 17              dbms_output.put_line( 'Try again later....' );
 18  end;
 19  /
Try again later....

PL/SQL procedure successfully completed.

showing it is able to detect the locked row and not block.
August 15, 2000 Ruben -- Thanks for the question regarding "Can Oracle Automatically Shrink a Rollback Segment ?", version 8.1.5
You Asked
Hi Tom , Greetings.

I have a doubt about that appears in Oracle8 Adm. Guide,
I Quote :
"OPTIMAL should be large so that Oracle
does not have to shrink and allocate extents frequently."

I quote from Oracle8 SQL Reference :
"Oracle deallocates as many extents
as possible without reducing the total size of the rollback
segment below the OPTIMAL
value."

I know that the following statement shrinks manually rollback
segment RBS_01 to 100K:
ALTER ROLLBACK SEGMENT rbs_01 SHRINK TO 100K;

If so, then, can Oracle automatically shrinks a rollback segment
by using the OPTIMAL option ?

Can you explain the diference between 'to shrink' and 'without
reducing', is this the same or what ?

Thanks in advance.
and we said...
Oracle will automatically shrink a rollback segment back to its
optimal setting.  You can manually request us to shrink them as
well.

From the concepts guide:

<quote>
Extents in Rollback Segments
Oracle periodically checks to see if the rollback segments of
the database have grown larger than their optimal size. If a
rollback segment is larger than is optimal (that is, it has too
many extents), Oracle automatically deallocates one or more
extents from the rollback segment. See "How Extents Are
Deallocated from a Rollback Segment" on page 4-25 for more
information.

...
(page 4-25)
When you create or alter a rollback segment, you can use the
storage parameter OPTIMAL (which applies only to rollback
segments) to specify the optimal size of the segment in bytes.
If a transaction needs to continue writing rollback information
from one extent to another extent in the rollback segment,
Oracle compares the current size of the rollback segment to the
segment’s optimal size. If the rollback segment is larger than
its optimal size and the extents immediately following the
extent just filled are inactive, Oracle deallocates consecutive
nonactive extents from the rollback segment until the total size
of the rollback segment is equal to or close to but not less
than its optimal size. Oracle always frees the oldest inactive
extents, as these are the least likely to be used by consistent
reads.
</quote>

"To shrink" is the act of releasing extents that were allocated
to the rollback segment back to the free space pool.

"Without reducing <the total size fo the rollback segment...>"
means we will make the rollback segment NO SMALLER then its
optimal size.  Meaning -- the rollback segment will be "shrunk"
to be as small as possible WITHOUT being smaller then the
optimal size.
August 15, 2000 Jens -- Thanks for the question regarding "FGAC: coming in from OAS4081", version 8.1.5
You Asked
Tom,
I have enjoyed reading yours and others articles on Fine Grained
Access Control, but most of the stuff assume you issue your
selects in client/server environment. My application would be
Designer-generated packages and manually written Pl/Sql
procedures executed by accessing agents on an Oracle Application
Server 4.0.8.1. The agents are protected using Basic_Oracle
authentication with roles defined against realms. DCD username /
passwords are stored with the DCD.
I'm trying to pick up the web-server username using
OWA_UTIL.GET_CGI_ENV('REMOTE_USER'), and select this value into
a variable in my security function to define the where-predicate
for FGAC. However, I always get an ORA-28112 error, so I'm
assuming that a NO_DATA_FOUND is returned when the function
tries to build my predicate.
Question is: Can web-server username be used at all with FGAC?
Below is my function BUILD_PREDICATE, which is applied on the
IMT_WEB.EMP table, as well as the PH_SHOW_DEMO procedure that is
called from the browser via a protected url.

Please note that PH_SHOW_DEMO works fine if the call to OWA_UTIL
is taken out, and a userid is hard-coded.
Any input would be appreciated.
Regards,
Jens

function build_predicate(
                  obj_schema varchar2,
                  obj_name varchar2)
        return varchar2
   is
   my_level varchar2(10);
   retval varchar2(2000);
  my_userid varchar2(100);
begin
--if coming in from web-server:
if sys_context('userenv','ip_address') =
'<MY_WEB_SERVERS_IP_ADDRESS>' then
    select owa_util.get_cgi_env('REMOTE_USER') into my_userid
from dual;

    select accesslevel into my_level
    from sec_matrix
    where upper(table_owner) = 'IMT_WEB'
    and upper(table_name) like 'DEMO_ANS'
  and upper(bbrno)=upper(my_userid);
--below doesn't work either....
--   and
upper(bbrno)=upper(owa_util.get_cgi_env('remote_user'));

    retval := 'accesslevel='''||my_level||'''';
else
--from other machines
        retval := 'accesslevel=''none''';
end if;

    return retval;
end build_predicate;

PROCEDURE ph_show_demo IS
str varchar2(2000);
sql_stmt varchar2(100);
me varchar2(100);
BEGIN
  htp.htmlopen;
  htp.headopen;
  htp.headclose;
  htp.bodyopen;
  htp.p('Employees limited by row-level security:');
  htp.br;
  htp.br;
  htp.br;
select build_predicate('IMT_WEB','DEMO_ANS') into str from dual;
htp.p(str);
htp.br;
select owa_util.get_cgi_env('remote_user') into me from dual;
--htp.p(owa_util.get_cgi_env('remote_user'));
htp.p('I am user: ');
htp.p(me);
htp.br;
htp.br;
sql_stmt := 'select * from demo_ans';
htp.tableopen;
htp.tablerowopen;
htp.tabledata('ANSID');
htp.tabledata('NAVN');
htp.tabledata('DEPTID');
htp.tabledata('ACCESSLEVEL');
htp.tablerowclose;
    owa_util.cellsprint(sql_stmt,2000);
htp.tableclose;
htp.bodyclose;
htp.htmlclose;

END;
and we said...
The fine grained access control code is running in a different
"space" then your code.  It does not have access to your package
states and such.

You need to set the username in a context before using the FGAC.
 The application context is the way to get the state to the FGAC
routines.  Consider this small example:

ppr_test@8i> create or replace package demo_pkg
  2  as
  3      procedure set_remote_user;
  4
  5      function security_function( p_schema in varchar2,
  6                                  p_object in varchar2 )
  7      return varchar2;
  8
  9  end;
 10  /

Package created.

ppr_test@8i> create or replace context my_context
  2  using demo_pkg
  3  /

Context created.

Thats my security policy and a function to set up the
application context (and the create context).  Now I can
implement the package body.  My policy will be really simply --
I will return a predicate that is basically "where owner =
REMOTE_USERNAME"

ppr_test@8i> create or replace package body demo_pkg
  2  as
  3
  4
  5  procedure set_remote_user
  6  is
  7  begin
  8      dbms_session.set_context( 'my_context', 'remote_user',
  9            upper(owa_util.get_cgi_env('remote_user')) );
 10  end;
 11
 12
 13  function security_function( p_schema in varchar2,
 14                              p_object in varchar2 )
 15  return varchar2
 16  is
 17  begin
 18      return 'owner = '||
 19                     'sys_context( ''my_context'', ' ||
 20                     ' ''remote_user'' )';
 21  end;
 22
 23
 24  end;
 25  /

Package body created.

Notice how the procedure set_remote_user stuffs the cgi_env
into the application context (and remember - the only way to set
the context is via a procedure/function in the demo_pkg, we've
BOUND that package to that context -- there will be no
"spoofing").  The security policy on the other hand does not
refer to the cgi-env but rather the application context

Continuing on:

ppr_test@8i> create table my_table
  2  (  data        varchar2(30),
  3     OWNER       varchar2(30) default USER
  4  )
  5  /

Table created.

ppr_test@8i>
ppr_test@8i> begin
  2     dbms_rls.add_policy
  3     ( object_schema   => user,
  4       object_name     => 'MY_TABLE',
  5       policy_name     => 'MY_POLICY',
  6       function_schema => user,
  7       policy_function => 'demo_pkg.security_function',
  8       statement_types => 'select',
  9       update_check    => FALSE );
 10  end;
 11  /

PL/SQL procedure successfully completed.

Created a table and attached the policy to it.  Now lets put
some data in there (my username on the web is WEB$TKYTE)..

ppr_test@8i> insert into my_table values ( 'abc', 'WEB$TKYTE' );
ppr_test@8i> insert into my_table values ( 'abc', 'WEB$TKYTE' );
ppr_test@8i> insert into my_table values ( 'abc', 'WEB$TKYTE' );
ppr_test@8i> insert into my_table values ( 'abc', 'NOT ME' );
ppr_test@8i> insert into my_table values ( 'abc', 'NOT ME' );
ppr_test@8i> insert into my_table values ( 'abc', 'NOT ME' );

and now I create a small package for the web:

ppr_test@8i> create or replace package web_demo_pkg
  2  as
  3      procedure show_some_data;
  4  end;
  5  /

Package created.

ppr_test@8i>
ppr_test@8i>
ppr_test@8i> create or replace package body web_demo_pkg
  2  as
  3
  4  procedure show_some_data
  5  is
  6  begin
  7      htp.header( 1, 'testing' );
  8      for x in ( select * from my_table )
  9      loop
 10          htp.bold( x.data || ',' || x.owner || '<br>' );
 11      end loop;
 12  end;
 13
 14
 15  BEGIN
 16      demo_pkg.set_remote_user;
 17  end;
 18  /

Package body created.

ppr_test@8i> grant execute on web_demo_pkg to public
  2  /

Notice how I used the elaboration code in the package body to
automagically set the application context.  Every package body
may have such code -- its a snippet of code that will be
executed as the package is loaded for the first time -- its
initialization code.  It does all of the work of setting the
username for us.  Now when I run this, I get:

testing

abc,WEB$TKYTE
abc,WEB$TKYTE
abc,WEB$TKYTE

as expected....
August 15, 2000 rajendra -- Thanks for the question regarding "sql query - Q about julian dates.", version oracle 8
You Asked
can a julian date can be converted to date
and we said...
Yes -- you just need to to date it.

I've seen people call various inputs "julian dates".  The true
one is defined at:

http:
//whatis.techtarget.com/WhatIs_Search_Results_Exact/1,282033,,00.
html?query=julian+date

(the number of elapsed days since the beginning of a cycle of
7,980 years).

For that type of julian date -- a simple:

select to_date( 2450873, 'j' ) from dual;

will convert it.

Some people call a number in the format YYYYDDD a julian date --
its not but we can convert it anyway.  It would look like:

select to_date(1998059,'yyyyddd') from dual;

Both of the above queries return 28-feb-1998
August 15, 2000 Matt -- Thanks for the question regarding "Open Cursors", version 8.1
You Asked
Tom,

If have an open a cursor in my procedure and an exception occurs
,the exception handler does not explicitly
close the cursor. Will the cursor remain open until the
database is bounced ?? I ask this because we have had
a problem with max_open_cursors being exceeded.

Cheers,

Matt
and we said...
If the procedure is a database stored procedure and the cursor
is declared as a local (not a package global variable) or it is
an implicity cursor -- it'll be closed for you... (if its not
plsql -- its hard to say what the behaviour is -- depends on the
language)

HOWEVER....

there is a lot of cursor caching going on in the background.
The default of 50 for max_open_cursors is woefully small in my
opinion.  A number of 500 or 1,000 is more reasonable.  We open
cursors in groups of 64 at a time -- so having a large number
does not "preallocate" gobs of space -- we grab them 64 at a
time at runtime.

Cursors are local to a session -- so you do not need to bounce
the instance when you exceed this -- its on a per session basis.

Suggest that if you haven't, increase the limit from 50 to at
least 500.  After that, if you still have issues, look at
v$open_cursor as your session is running to see what cursors are
sticking around that you feel should not be (plsql is going to
cache some so you would be looking for NON-plsql based cursors
in there)
August 15, 2000 ade -- Thanks for the question regarding "procedure error", version 7.3.4 (with view to migrating to 8)
You Asked
i have the following message from the procedure below, but a bit
bemused as the error lines reffered to, do not exist. what may
be cuasing the error. Thank you in advance for yor continued
assistance.

Wrote file afiedt.buf

  1  CREATE OR REPLACE PROCEDURE rebuildindx as
  2  file_handle            utl_file.file_type;
  3  d_indxcur              number;
  4  d_dummy              number;
  5  index_expr            varchar2(500);
  6  cursor indx_cur is
  7  select 'alter index'||' '||index_name ||' '||'rebuild ;'
  8             from user_indexes where index_name not like
'%$';
  9  Begin
 10         file_handle := utl_file.fopen('c:\sun3k\'
,'myfile.txt', 'W') ;
 11         open indx_cur;
 12                               loop
 13                                      fetch indx_cur into
index_expr;
 14                                      exit when
indx_cur%notfound;
 15                                      begin
 16                                              d_indxcur :=
dbms_sql.open_cursor;
 17
dbms_sql.parse(d_indxcur,index_expr,DBMS_SQL.V7);
 18                                              d_dummy : =
dbms_sql.execute(d_indxcur);
 19
dbms_sql.close_cursor(d_indxcur);
 20
utl_file.putf(file_handle,'statement:  '||index_expr||' '||'was
successful')
 21                                       exception
 22                                           when no_data_found
then
 23
dbms_output.put_line('DATA ERROR!!!!......CALL SUPPORT!!');
 24                                           when
utl_file.invalid_filehandle then
 25
dbms_output.put_line('UTL_FILE HANDLE IS NOT VALID!!!');
 26                                           when
utl_file.invalid_operation then
 27
dbms_output.put_line('UTL_FILE CANNOT OPEN OR BE USED!!');
 28                                           when
utl_file.invalid_path then
 29
dbms_output.put_line('INVALID FILE PATH ERROR !!!');
 30                                           when
utl_file.write_error then
 31
dbms_output.put_line('UTL_FILE WRITE ERROR!!!');
 32                                           when others then
 33
utl_file.putf(file_handle, 'statement: '||index_expr||'
'||'failed!');
 34                                     end;
 35                                end loop  ;
 36               close indx_cur;
 37               utl_file.fclose(file_handle);
 38* end;
 39  .
SQL> start rebuildindx
Input truncated to 2 characters

Procedure created.

SQL> execute rebuildindx
BEGIN rebuildindx; END;

*
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at "SYS.UTL_FILE", line 103
ORA-06512: at "SYS.UTL_FILE", line 120
ORA-06512: at "SYS.UTL_FILE", line 218
ORA-06512: at "AMTRAK.REBUILDINDX", line 42
ORA-06512: at line 1
and we said...
before you attempt running such a script, please read through:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:457820220286
Rebuilding an index is something to be done for a specific
index, if and when you have to.  Its not something you should
do "as standard operating procedures"!

#2 -- can you verify the contents of rebuildindx for me.  I see

Wrote file afiedt.buf

at the top -- meaning the code that is listed for me is in
afiedt.buf -- not in rebuildindx.  But you start rebuildindx.
(so what is listed above is not necessarily what was executed
with the start command) I'd be more interested in the output of:

SQL> @rebuildindx
SQL> list

Or better yet:

select line, text from user_source where name = 'REBUILDINDX';

In case you are interested - you should only OPEN the cursor
once (it'll go faster) and make sure you close it (else multiple
failed alter index rebuilds will leave dangling cursors out
there and ultimately you'll hit

ORA-00604: error occurred at recursive SQL level 1
ORA-01000: maximum open cursors exceeded

from the cursor leak you have (i did).

also, you should use PUT_LINE, not PUTF.  PUTF scans the second
argument looking for %s and \n.  You'll have have any (and if
you do by accident, you didn't intend to).  If you want to use
PUTF, you should code:

utl_file.putf(  file_handle,
               'statement:  %s was successful\n',
                index_expr );

instead of:

 utl_file.putf(file_handle,'statement:  '||index_expr||' '||'was

successful')

You are not currently putting out any newlines -- hence, when
you write 1022 bytes of "log", it'll start failing with utl_file
errors (max linesize pre-8.0.5).

Lastly -- the alter index command is wrong -- NO semi-colons in
SQL (thats a sqlplus-ism only)....

If I had to write this procedure (and I would not -- its just
not right to rebuild indexes like this) I would code it like
this:

scott@ORA734.WORLD> CREATE OR REPLACE PROCEDURE rebuildindx
  2  as
  3   file_handle          utl_file.file_type;
  4   d_indxcur            number := dbms_sql.open_cursor;
  5   d_dummy              number;
  6   l_sql                  varchar2(500);
  7  Begin
  8      begin
  9        file_handle :=
 10           utl_file.fopen('/tmp/' ,'myfile.txt', 'W') ;
 11        for x in ( select index_name
 12                     from user_indexes
 13                    where index_name not like '%$' )
 14        loop
 15           l_sql := 'alter index ' || x.index_name ||
                                                   ' rebuild';
 16           dbms_sql.parse(d_indxcur, l_sql, DBMS_SQL.V7);
 17           d_dummy := dbms_sql.execute(d_indxcur);
 18           utl_file.putf(file_handle,
 19                        'statement:  %s was successful\n',
 20                         l_sql );
 21        end loop;
 22        utl_file.fclose(file_handle);
 23     exception
 24         when utl_file.invalid_path then
 25             raise_application_error(-20001,
 26         'INVALID_PATH: File loc or name was invalid.');
 27         when utl_file.invalid_mode then
 28             raise_application_error(-20002,
 29         'INVALID_MODE: open_mode in FOPEN was invalid.');
 30         when utl_file.invalid_filehandle then
 31             raise_application_error(-20002,
 32         'INVALID_FILEHANDLE: The file handle was invalid.');
 33         when utl_file.invalid_operation then
 34             raise_application_error(-20003,
 35         'INVALID_OPERATION: The file could not be opened or
 36             operated on as requested.');
 37         when utl_file.read_error then
 38             raise_application_error(-20004,
 39         'READ_ERROR: An OS error occurred during
 40             the read operation.');
 41         when utl_file.write_error then
 42             raise_application_error(-20005,
 43         'WRITE_ERROR: An OS error occurred during
 44             the write operation.');
 45         when utl_file.internal_error then
 46             raise_application_error(-20006,
 47         'INTERNAL_ERROR: An unspecified error in PL/SQL.');
 48     end;
 49
 49     -- this always executes!
 50     if( dbms_sql.is_open( d_indxcur) ) then
 51        dbms_sql.close_cursor(d_indxcur);
 52     end if;
 53  end;
 54  /
August 15, 2000 Bhavendra -- Thanks for the question regarding "Oracle OLEDB driver for Oracle 8.1.5 (Badly needed)", version 8.1.5
You Asked
Hi Tom,

I want to install oracle oledb drive for 8.1.5.
In existing product I don't find oracle oledb driver.
I have also checked oracle site, I will find only oracle oledb
for oracle 8.1.6.
So please guide me how to install that.

Thanks and regards,

Bhavendra
and we said...
The Oracle OLEDB driver is version 8.1.6.  It can be used to
access any version 7.3 or above database.  It is "middleware" --
you can have a v8.1.5 server and use this...  You want the
v8.1.6 driver (it is the only one out there until 8.1.7 comes
out)
August 15, 2000 John -- Thanks for the question regarding "Sequence vs unique number for primary key", version 8.1.6
You Asked
Tom,

What are the positive and negative ramifications of using an
Oracle 'sequence' for a primary key vs a unique number field?
Also, is the Oracle 'sequence' ANSI compliant in case the tables
should get moved to another RDBMS?

Thanks!
John
and we said...
A sequence is a database object -- its not a datatype.  A
sequence can be used to populate a number field to make it
unique.  A sequence cannot be compared to a unique number
field....

There are no ansi standards for this type of stuff (stuff you
really really need).  Virtually every database has a way of
doing this -- informix has the serial type, sqlserver the
identity type and so on.  With Oracle, you would:

create sequence your_seq_name;

create or replace trigger xxxxxx
before insert on T for each row
begin
  select your_seq_name.nextval into :new.primary_key from dual;
end;
/

to use them.  In informix you would

create table t ( primary_key serial, .... )

and so on...
August 15, 2000 -- Thanks for the question regarding "Different Index ", version 8.1.5
You Asked
Hi Tom,

I have couple of questions related to Indexing:
1. I have so many indexes in my database, how I can find out the
type of those indexes such as clustered, Non-clustered or
Bitmap.
2. I am kind of confused between so many types of Indexing such
as Bitmap, Btree, Unique, clustered and Non-clustered. Could you
please help me out to distinguish these indexes type? If you can
also give me some example. that will be awesome.

Regards,
Sanjeev
and we said...
1)

ops$tkyte@8i> select distinct index_type from dba_indexes;

INDEX_TYPE
---------------------------
BITMAP
CLUSTER
DOMAIN
FUNCTION-BASED NORMAL
IOT - TOP
LOB
NORMAL

7 rows selected.

the index_type column will tell you this.

2)

I think the concepts guide does this really well.  See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c08schem.htm#3239
it goes over the types -- with small examples and covers ones
you didn't even ask about.

If you have a specific followup after that -- I'd be glad to
answer it..
August 15, 2000 Ash -- Thanks for the question regarding "SQL Loader --- URGENT -- using recnum in sqlldr", version 8.1.5
You Asked
Tom,

      I have one big file with about 20 columns and it goes to
mutiple tables from one ctl file. one of the column which I need
to populate is not defined in the file and has to be unique for
each record , I know I can use RECNUM , but what I need to do is
that I need the same value going into other tables to, so that
it can maintain the joins within the tables.

Please advice

Thanks
and we said...
Well -- it should work OK like this then:

LOAD DATA
INFILE *
INTO TABLE t1
replace
( f1  RECNUM,
  f2  position(1:1),
  f3  position(2:2)
)
INTO TABLE t2
replace
( f1  RECNUM,
  f2  position(11:11),
  f3  position(12:12)
)
BEGINDATA
1234567890ABCDEFGHIJ
ABCDEFGHIJ0123456789

The the recnums will be consistent since they are the record
number of the input file.

does that do it for you?  If not, specify OS and repost...
August 16, 2000 Omar -- Thanks for the question regarding "Trimming special Characters", version 8.0.5
You Asked
Hi Tom,
   How could I trim a CR and LF (i.e the "Enter" key) from
within a multi-line string in a text item.

thanks
and we said...
A simple RTRIM( field, chr(13)||chr(10) ) will do that:

ops$tkyte@DEV8I.WORLD> select dump(data),
                              dump(rtrim(data,chr(13)||chr(10)))
  2   from ( select 'hello world'||chr(13)||chr(10) data
               from dual )
  3  /

DUMP(DATA)
--------------------------------------------------------------
DUMP(RTRIM(DATA,CHR(13)||CHR(10)))
--------------------------------------------------------
Typ=1 Len=13: 104,101,108,108,111,32,119,111,114,108,100,13,10
Typ=1 Len=11: 104,101,108,108,111,32,119,111,114,108,100

shows the cr||lf is removed with the rtrim...
Review & Followup
Rating: 5
Thanks for this info October 02, 2001
Reviewer: Dr Feelgood from Auckland, New Zealand
Very helpful - exactly what I needed to know.  Solved my problem in a couple of
minutes.  :-)

August 16, 2000 madhusudhana rao -- Thanks for the question regarding "Can partition key updateable ? ", version Oracle 8.0.3
You Asked
hi,
  Is it possible to update a partition key in the above mention
version or higher.

Regds.
Madhusudhana Rao.Puvulla
and we said...
It is possible to update a partition key in all releases -- what
is not possible to do prior to 8i is to update the partition key
in such a fashion as to cause it to move from partition to
partition.  For example:

ops$tkyte@8.0> CREATE TABLE partitioned
  2  ( x int,
  3    y int,
  4    z DATE
  5  )
  6  PARTITION BY RANGE (z)
  7  (
  8  PARTITION part_1 VALUES LESS
           THAN(to_date('01-jan-1995','dd-mon-yyyy')),
  9  PARTITION part_2 VALUES LESS
           THAN(to_date('01-jan-1996','dd-mon-yyyy'))
 10  )
 11  /

Table created.

ops$tkyte@8.0>
ops$tkyte@8.0> insert into partitioned values
  2  ( 1, 1, to_date('01-jan-1994','dd-mon-yyyy') );

1 row created.

ops$tkyte@8.0>
ops$tkyte@8.0> insert into partitioned values
  2  ( 2, 1, to_date('01-mar-1995','dd-mon-yyyy') );

1 row created.

ops$tkyte@8.0>
ops$tkyte@8.0> commit;

Commit complete.

ops$tkyte@8.0>
ops$tkyte@8.0> update partitioned set
  2           z = to_date('01-jan-1993')
               where z = to_date('01-jan-1994')
  3  /

1 row updated.

That shows we CAN update a partition key in 8.0

ops$tkyte@8.0> rollback;

Rollback complete.

ops$tkyte@8.0>
ops$tkyte@8.0> update partitioned set
  2  z = decode( x, 1, to_date('01-mar-1995','dd-mon-yyyy'),
  3              2, to_date('01-jan-1994','dd-mon-yyyy') )
  4  /
update partitioned set
       *
ERROR at line 1:
ORA-14402: updating partition key column would cause a partition
change

But we cannot have it migrate.  Now, in Oracle8i, release 8.1
we can:

ops$tkyte@8i> CREATE TABLE partitioned
  2  ( x int,
  3    y int,
  4    z DATE
  5  )
  6  PARTITION BY RANGE (z)
  7  (
  8  PARTITION part_1 VALUES LESS
         THAN(to_date('01-jan-1995','dd-mon-yyyy')),
  9  PARTITION part_2 VALUES LESS
         THAN(to_date('01-jan-1996','dd-mon-yyyy'))
 10  )
 11  ENABLE ROW MOVEMENT
 12  /

Table created.

Enable row movement will allow us to update a partition key
and have it move from partition to partition

ops$tkyte@8i>
ops$tkyte@8i> insert into partitioned values
  2  ( 1, 1, to_date('01-jan-1994','dd-mon-yyyy') );

1 row created.

ops$tkyte@8i>
ops$tkyte@8i> insert into partitioned values
  2  ( 2, 1, to_date('01-mar-1995','dd-mon-yyyy') );

1 row created.

ops$tkyte@8i>
ops$tkyte@8i> commit;

Commit complete.

ops$tkyte@8i>
ops$tkyte@8i> select rowid, a.* from partitioned a;

ROWID                       X          Y Z
------------------ ---------- ---------- ---------
AAAWBlAADAAAIfKAAA          1          1 01-JAN-94
AAAWBmAADAAAIgKAAA          2          1 01-MAR-95

ops$tkyte@8i> update partitioned set
  2  z = decode( x, 1, to_date('01-mar-1995','dd-mon-yyyy'),
  3              2, to_date('01-jan-1994','dd-mon-yyyy') )
  4  /

2 rows updated.

ops$tkyte@8i> select rowid, a.* from partitioned a;

ROWID                       X          Y Z
------------------ ---------- ---------- ---------
AAAWBlAADAAAIfKAAB          2          1 01-JAN-94
AAAWBmAADAAAIgKAAB          1          1 01-MAR-95

ops$tkyte@8i> commit;

Commit complete.

but -- notice the side effect -- the rows ROWID changed, one
of 2 cases in Oracle8i release 8.1 whereby for the first time a
rowid of a row will change (index organized tables are the other
case -- if you update the primary key)
Review & Followup
Rating: 5
Excellent! May 21, 2003
Reviewer: Prakash Bala from Atlanta, GA, USA
Didn't know that there was such a clause in order to enable the row movement

Rating: 5
Excellent Tom!!! September 23, 2003
Reviewer: A reader
Learnt a new thing today and implemented it too!!!

August 16, 2000 GAURANG -- Thanks for the question regarding "why pga is in shared pool in MTS ", version 8.1.5
You Asked
hi  tom .
1)Can  you tell me  why pga(or uga) is in shared pool in MTS arch?
in dedicated server process it is seperated from SGA.

2) In dedicated sever process how memorary allocated to PGA(or uga ).
is it user's session memory or it is allocated on server?
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:267215452482
for some more info but...

PGA is in the process always (stands for PROCESS global area).  The UGA is
allocated from the PGA in dedicated server mode (dynamically allocated from the
OS at runtime) since a process = a session in that mode.

In MTS mode -- a process != session so the UGA (user global area) is allocated
out of the SGA which all processes have access to.  The UGA maintains your
session type of variables -- the PGA is used for process oriented structures.
The UGA is in the shared (or better yet -- LARGE) pool in MTS so that your
session can migrate from process to process and still have access to its "state".
Review & Followup
Rating: 4
April 10, 2002
Reviewer: A reader
Simple and clear expln.

Thanks.

August 16, 2000 Bhaskara -- Thanks for the question regarding "how character, number and other data stored in oracle", version 815
You Asked
hi Tom,
   Can you explain, how the character, number and other datas
stored in oracle database?
Thanks,
Bhaskara
and we said...
A varchar is stored with a leading byte to indicate the length
and then the data.  Any varchar 250 bytes or less uses 1 byte
for the length and then the data.  Greater then 250 bytes uses 3
bytes (a flag to say "length is 2 bytes" and then the length)
followed by the data.

A char is a varchar that is always stored with blank padded
spaces at the end.  So, a char still has the leading 1 or 3 byte
field -- followed by the data -- but the length is constant for
the char type (always padded out to the max length)

A number type is stored in a packed format. See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c10datyp.htm#743
for the details.  Basically, in upto 22 bytes we store numbers
with 38 digits of precision in the range of positive numbers in
the range 1 x 10-130 to 9.99..9 x 10125 and negative numbers
from -1 x 10-130 to 9.99..99 x 10125.

Dates are stored in 7 bytes always with the Century, Year,
Month, Day, Hour, Minute, Second.  See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c10datyp.htm#796
for more details.

For the rest, just goto
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c10datyp.htm
and click on the datatype you are interested in getting more
info on...
August 16, 2000 Leon -- Thanks for the question regarding "Rollback segment and temporary tablespace usage", version 7.3
You Asked
Tom,

1) How can I know which user or session or process is
currently using TEMP tablespace for sort kind of operation?

2) Similarly, Is there any dictionary view and v$ view that
can tell me which user session or process or SQL statement
using rollback segment?

Thanks,

Leon,
and we said...
1) In 7.3, it is so difficult to determine this that I'm not
going to go into here (you can contact support and ask for note
1069041.6 which goes into it -- its messy).

The following query, while it won't tell you who is using a
given segment will tell you who is doing lots of sorts and what
kind:

SELECT  substr(vs.username,1,20) "db user",
        substr(vs.osuser,1,20)   "os user",
        substr(vsn.name,1,20)   "Type of Sort",
        vss.value
FROM    v$session vs,
        v$sesstat vss,
        v$statname vsn
WHERE   (vss.statistic#=vsn.statistic#) AND
        (vs.sid = vss.sid) AND
        (vsn.name like '%sort%')
/

In 7.3 -- thats pretty much it.  In 8.0 and up, there is a v$
view (v$sort_usage) that gives us the stuff that is really hard
to get in 7.x....

2)
SQL> select a.username, b.segment_name
  2  from v$session a, dba_rollback_segs b, v$transaction c
  3  where a.taddr = c.addr and b.segment_id = c.xidusn;

should do it...
August 17, 2000 KK -- Thanks for the question regarding "Comparison between OAS and iAS", version 4.0.8
You Asked
Is there any difference between the currently used OAS and
the new iAS (Internet Application Server)?

Which one should I use?  Will Oracle still support OAS
in the future?
and we said...
iAS is a much larger, more comprehensive offerig the OAS.  OAS
was a webserver and orb -- pure middleware.

iAS is all of the things listed at
http://www.oracle.com/ip/deploy/ias/index.html
bundled together.

Under the covers -- iAS features apache as opposed to the
spyglass webserver OAS had.  It uses the native apache module
model for distributed component -- as opposed to the ORB OAS
used.  It has the cartridges you are used to (plsql and so
on)...

OAS will continue to be supported -- contact support for exact
details.
August 17, 2000 balasubramanian -- Thanks for the question regarding "Defragmenting system objects", version 8.0.6/8.1.5
You Asked
Dear Tom,
  While operating a database, there are possibilities for
fragment spaces in datafile due to nature of activities or
physical parameter settings. The same may be possible in SYS
objects also.
My questions are:

 1.Is there any way to defragment the tables owned by
   owner 'SYS'?
 2.Is there any way to avoid fragmentation at initial stages ?
and we said...
1) no.  It never gets "fragmented".  They may go into many
extents -- and that is OK.  Fragmentation would imply that there
are lots of unusable "holes" all over the place.  Since we
never deallocate space in SYS owned objects -- there are no
holes (it only grows, it never shrinks). It is totally OK to
have lots of extents -- totally.

2) you may modify settings in the sql.bsq (script that creates
the data dictionary) file as far as initial and next go, based
on your past experience and how you use the system tables.  I've
never felt compelled to do so myself.
August 17, 2000 raj -- Thanks for the question regarding "to select subseconds from dual", version oracle 8
You Asked
thanks tom for your kind help on previous occassions...
help again...
is it possible to select subseconds from dual.

thanks..
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:341817437103,%7BMILLISECONDS%7D
for the solution(s)
August 17, 2000 Hannah -- Thanks for the question regarding "How to export the data from oracle tables to text files with delimitors?", version verion 7.3.1
You Asked
Tom,
    I want to know how to export data from oracle tables to text
files with delimitors in between the fields. Of course, it can
be done by typing select statements but I meet a problem that I
need to export many oracle tables and most of them contains many
fields. It will be v heavy loading for me to type the select
statements manually. I want to know whether there is any script
can perform this function for me. Thanks for your help!!!

Best Regards,
Hannah
and we said...
See
http://osi.oracle.com/~tkyte/flat/index.html
for a solution.
August 17, 2000 -- Thanks for the question regarding "using DISTINT with ROWNUM", version 8.0
You Asked
hi,

I had a following query.

select deptno from EMP;

dept
---
10
10
10
20
20
30
30
30

But I like output should be ..

deptno  rownum
--     -----
10       1
20       2
30       3

If this is a basic question, then just omit

thanks

regs
priya
and we said...
scott@8.0> select deptno, rownum
  2  from ( select distinct deptno from emp );

    DEPTNO     ROWNUM
---------- ----------
        10          1
        20          2
        30          3

scott@8.0>

will do it for you.
August 17, 2000 Chris -- Thanks for the question regarding "Which schema do logon triggers fire as ?", version 8.1.6
You Asked
Hi Tom,
I want to create a database security mechanism using 8.1.6 logon
triggers so that when a user attempts to connect as a schema
owner a row gets written to an auditing table /file and the user
gets kicked out. I'm thinking of creating a table is a new
schema that has a list of osusers that can connect to the
database as schema owners, obviously I want to restrict access
to this schema. Here's my conundrum, I need to be able to
reference the sucurity table in the trigger body but at the same
I don't want the dba user the trigger has fired as to be able to
see the contents of the table, what is the simplest way for me
to get around this ?. I could always hard code the osuser into
the trigger body, but this would mean that all the application
users would have to be out of the database if I / the DBA needed
to change the security policy, if I could I would like to avoid
this.

Thanks
Chris Adkin
and we said...
Unless the code is compile "authid current_user" the trigger
will fire with DEFINERS rights -- meaning the trigger will run
as the OWNER of the trigger.

The people who cause the trigger to fire will not have to have
access to the tables the trigger reads as it is firing.
August 17, 2000 Satish -- Thanks for the question regarding "regarding reorganization of table and indices", version oracle 8.0.5
You Asked
How do I reorganize a table of 14 GB at a less time and it's
indices (5 GB). Is there any way to do it in a less span of time
? Accroding to me if I get 48 hours of downtime then it can be
done. But time is the constraint. How do I do it in 6-10 hours
time.
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:365418042918,%7BREORG%7D
...

In short -- my opinion is to reorg a 14 gig table would take me
0 seconds -- because I would not consider doing it...

Indexes, rebuild them (better yet, upgrade to 8i and rebuild
them online -- no downtime).

If you have to unload and reload the table -- consider writing a
C program to unload the table to many flat files ( a couple
hundred thousand rows in each) and parallel direct path load
them back in -- should only take a very small amount of time to
reload.

Do not be afraid of hundreds of extents.
August 17, 2000 Tina -- Thanks for the question regarding "InterMedia Text Index", version 8.1.5
You Asked
Tom,

Thanks for your help last time.

I have another question about creating InterMedia text index.
I am trying to create the InterMedia text index on the one of
text
field in a table.  The field stores the URL for the document
search
on the web site.

If I create the index without define the tablespace as:

create index nmfs_url_text_indx on nmfs_url_text_t (url_text)
indextype is ctxsys.context
parameters ('datastore doc_url_datastore filter doclib_filter');

it works fine.

But I would like to create the index using the index tablespace.
 It
seems to me that we cannot create intermedia text index in
desired
tablespace:

07:49:24 SQL> create index nmfs_url_text_indx on nmfs_url_text_t
(url_text)
07:49:28   2  tablespace nstt_itmd_indx storage (initial 150k
next 150k pctincrease 0)
07:49:28   3  indextype is ctxsys.context
07:49:28   4  parameters ('datastore doc_url_datastore filter
doclib_filter')
07:49:28   5  /
indextype is ctxsys.context
*
ERROR at line 3:
ORA-02158: invalid CREATE INDEX option

Could you help us?

Thanks, Tina
and we said...
see
http://technet.oracle.com/doc/inter.815/a67843/cdatadic.htm#42459
for all of the details.  A context index is made up of a couple
of tables and indexes itself -- its not a 'single' segment like
a btree index is.  You set the storage attributes using the ctx
packages...
August 17, 2000 zeinab -- Thanks for the question regarding "oracle8 and servlet", version 8
You Asked
hello sir,
HOW I CAN ACCESS TO ORACLE DATABASE BY SERVLET PROGRAM?

THIS OPERATION NEED MANY STEPS AS FOLLOWES:
1)LOAD THE DRIVER
2) ESTABLISH CONNECTION (URL,USERNAME,PASSWORD)
3)Perform an SQL statement

BUT WE DO NOT KNOW HOW TO DO THIS IN (SERVLET )JAVA CODE WITH
ORACLE8

PLEASE GIVE US ANY INFORMATION ABOUT THIS SUBJECT.

THANK YOU
and we said...
You do it in the same fashion as you would for any jdbc
program... There is nothing special about it...

See
http://technet.oracle.com/tech/java/jroadmap/index2.htm?Info&servlets/listing.htm
for info, examples and documentation.
August 17, 2000 Frido -- Thanks for the question regarding "Cost / resource authorization", version 8.1.6
You Asked
We would like to allow users to submit whatever query they want
and reject those that are 'too expensive'

There are two possible ways to do this:

1: use optimizer statistics in conjunction with upper limits for
statement cost, number of rows etc. Problem with this is that
statement costs are not comparable between different statements

2: quit the query after a certain amount of time/cpu/... has
been consumed. This has the disadvantage that runaway queries
are started anyway, thus consuming resources until they are
aborted.

How can the idea be rescued?
and we said...
You are correct in you analysis with respect to #1.  The cost
assigned to a query may not be used to make any assumptions as
to how many resources/how long they will take.  They are only
comparable internally.

Resource profiles are a valid method.  It is true that until we
actually hit the limit -- we do not know that it will hit the
limit and hence cannot proactively "not run the query" in the
first place.  Resource profiles work until the limit is hit and
then abort the query/session.  Any work would be undone.

Another thing to consider is resource allocation -- new in 8i.
It will not prevent the queries from being run but you can
create classes of users such that "more important" people get
more resources.  If a lower priority user does submit that query
from #@#$#@ -- it will not affect the high priority users as
much. See:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/ch2.htm#140579
"database resource management".

Some query tools, such as Oracle discoverer, have "predicative"
query resource governors that might be of interest as well.
They will not run a query (optionally) that it feels is too
costly (you define that). See:
http://www.oracle.com/datawarehouse/products/bitools/discoverer/index.html?tech_over.html
for info on that.
August 17, 2000 Steven -- Thanks for the question regarding "How does Oracle know whether to check buffer cache or do I/O?", version 8.0.5 EE on HP-UX
You Asked
How does Oracle know whether a required block can be gotten from
the buffer cache or whether a physical I/O is required?  For
example, some blocks of an index are in the buffer cache, and
a query's execution plan calls for an index range scan.  How
does Oracle know whether or not the blocks in the "range" of
the range scan are in cache or not?  Alternatively, if a full-
table scan is needed, will blocks already in cache be read
from cache, or will the entire table be accessed via physical
I/O?  I apologize if I'm making this question more difficult
to understand than it actually is.

Thanks for the help you provide to the Oracle community - it's
greatly appreciated.
and we said...
Its a good question.  Each block has a DBA (data block address)
associated with it.  We hash this DBA and store the blocks in
lists according to their hashes.  When you want a block -- we
hash the dba -- look in that list and see if we can find it, if
not read it and put it into the correct list.

When we do an indexed read - we get the DBA's from the index.
We know the head DBA of the index (data dictionary tells us
that) so we can find the top of the index.  This head block will
"point" to other DBA's and we walk the tree (look at the cache
-- if found use it else read it, cache it, and then use it).

When fulling scanning -- we "synthesize" all of the DBA's we
need for the table (we know what they are from the data
dictionary by inspecting the extent layout of the table).  We do
much the same process -- goto the cache, if the synthesized DBA
is not there -- read (in this case db_file_multiblock_read_count
blocks) the block and cache it (cache THEM) and continue.  The
next N-1 reads should be cached as the next set of sequential
DBA's should already be there.

You can observe this with autotrace by noting that a FULL SCAN
does not always read from disk...  for example, the second time
around -- physical reads = 0

scott@8i> create table t1 as
  2  select *
  3    from all_objects
  4   where rownum < 1000;

Table created.

scott@8i> alter table t1 cache;

Table altered.

scott@8i>
scott@8i> set autotrace on
scott@8i> select count(*) from t1;

  COUNT(*)
----------
       999

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   SORT (AGGREGATE)
   2    1     TABLE ACCESS (FULL) OF 'T1'

Statistics
----------------------------------------------------------
        113  recursive calls
         20  db block gets
         24  consistent gets
         15  physical reads
          0  redo size
       1089  bytes sent via SQL*Net to client
        660  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
          3  sorts (memory)
          0  sorts (disk)
          1  rows processed

scott@8i> select count(*) from t1;

  COUNT(*)
----------
       999

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   SORT (AGGREGATE)
   2    1     TABLE ACCESS (FULL) OF 'T1'

Statistics
----------------------------------------------------------
          0  recursive calls
         16  db block gets
         15  consistent gets
          0  physical reads
          0  redo size
       1090  bytes sent via SQL*Net to client
        660  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          1  rows processed

scott@8i> set autotrace off
August 17, 2000 Bhavesh -- Thanks for the question regarding "THe Query", version 8.1.5
You Asked
Hi Tom:

Thanks for your help to the Oracle Community.
Here is my question..

================================
The desc of table..
SQL> desc summaryStmt
 Name                                                  Null?
Type
 ----------------------------------------------------- --------
-------------------------
 CUSTID
NUMBER(5)
 STATEMENTDATE
DATE
 STATEMENTMONTHS
NUMBER(2)
 NETSALES
NUMBER(15,2)

statementDate is the financial statement date of a company.
StatementMonths tells whether the statement is annual, semi
annual or quarterly.
12 means annual, 6 mean semi annual and 3 mean quarterly.
I can be 1,3,6,9 or 12 months.

THe data in the table...
SQL> select * from summaryStmt
   2 order by statementDate;

   CUSTID STATEMENT STATEMENTMONTHS  NETSALES
--------- --------- --------------- ---------
     1000 30-JUN-96              12     40000
     1000 31-MAR-97               9     45000
     1000 31-DEC-97               6     30000
     1000 30-JUN-98              12     67000
     1000 30-JUN-99              12     80000

Based on the data, when company have annual statement
(statementMotnhs=12)
we can determine the fiscal year of the company. In this case,
the
companies fiscal year 95 begins from 1 -july-95 and ends on
30-june-96.
Now, my query should retrun me the LATEST statement for each
fiscal year.

The fiscal year can be different for each and every company.
Most of the time it's same as the calendar year BUT NOT ALWAYS
..just like in this example.

So, my query should return me the following result..

  CUSTID STATEMENT STATEMENTMONTHS  NETSALES
--------- --------- --------------- ---------
     1000 30-JUN-96              12     40000
     1000 31-MAR-97               9     45000
     1000 30-JUN-98              12     67000
     1000 30-JUN-99              12     80000

Again, I need the most recent statement in each fiscal year.
When the statementMonths = 12, that's the year end annual
statement
of the fiscal year started previuos year! and I need it.
Otherwise
the most recent that fiscal year..

Thanks a lot, Tom
^^^^^^^^^^^^^^^^^

Bhavesh
and we said...
If we can do this for a CUSTID at a time -- yes, I believe we
can get that.

What I need to start with is a query that gives me the fy
begining and end dates for some number of year.  I can get that
for a given custid via:

system@ORA734.WORLD>
system@ORA734.WORLD> variable CUSTOMER_ID number
system@ORA734.WORLD> exec :CUSTOMER_ID := 1000

system@ORA734.WORLD> select add_months( dt, -(r)*12 ) fy_beg,
  2         add_months( dt, -(r-1)*12 ) fy_end
  3    from ( select max(statement) dt
  4             from t
  5            where statementmonths=12
  6              and custid = :CUSTOMER_ID ),
  7         ( select rownum r
  8             from all_objects
  9            where rownum < 20 )
 10  /

FY_BEG      FY_END
----------- -----------
30-JUN-1998 30-JUN-1999
30-JUN-1997 30-JUN-1998
30-JUN-1996 30-JUN-1997
30-JUN-1995 30-JUN-1996
30-JUN-1994 30-JUN-1995
30-JUN-1993 30-JUN-1994
30-JUN-1992 30-JUN-1993
30-JUN-1991 30-JUN-1992
30-JUN-1990 30-JUN-1991
30-JUN-1989 30-JUN-1990
30-JUN-1988 30-JUN-1989
30-JUN-1987 30-JUN-1988
30-JUN-1986 30-JUN-1987
30-JUN-1985 30-JUN-1986
30-JUN-1984 30-JUN-1985
30-JUN-1983 30-JUN-1984
30-JUN-1982 30-JUN-1983
30-JUN-1981 30-JUN-1982
30-JUN-1980 30-JUN-1981

19 rows selected.

Now, I can incorporate that into a larger query against T:

system@ORA734.WORLD> select *
  2    from T,
  3        ( select add_months( dt, -(r)*12 ) fy_beg,
  4                 add_months( dt, -(r-1)*12 ) fy_end
  5            from ( select max(statement) dt
  6                     from t
  7                    where statementmonths=12
  8                      and custid = :CUSTOMER_ID ),
  9                 ( select rownum r
 10                     from all_objects
 11                    where rownum < 20 ) ) A
 12  where t.custid = :CUSTOMER_ID
 13    and t.statement between a.fy_beg and a.fy_end
 14    and t.statement = ( select max(statement)
 15                          from T t2
 16                        where t2.custid = :CUSTOMER_ID
 17                          and t2.statement between a.fy_beg
 18                                               and a.fy_end )
 19  /

    CUSTID STATEMENT   STATEMENTMONTHS   NETSALES FY_BEG
FY_END
---------- ----------- --------------- ---------- -----------
-----------
      1000 30-JUN-1999              12      80000 30-JUN-1998
30-JUN-1999
      1000 30-JUN-1998              12      67000 30-JUN-1997
30-JUN-1998
      1000 31-MAR-1997               9      45000 30-JUN-1996
30-JUN-1997
      1000 30-JUN-1996              12      40000 30-JUN-1995
30-JUN-1996

If I need, I can do all customers as well:

system@ORA734.WORLD> select *
  2    from T,
  3        ( select custid,
  4                 add_months( dt, -(r)*12 ) fy_beg,
  5                 add_months( dt, -(r-1)*12 ) fy_end
  6            from ( select custid, max(statement) dt
  7                     from t
  8                    where statementmonths=12
  9                    group by custid ),
 10                 ( select rownum r
 11                     from all_objects
 12                    where rownum < 20 ) ) A
 13  where t.custid = a.custid
 14    and t.statement between a.fy_beg and a.fy_end
 15    and t.statement = ( select max(statement)
 16                          from T t2
 17                        where t2.custid = a.custid
 18                          and t2.statement between a.fy_beg
 19                                               and a.fy_end )
 20  /

    CUSTID STATEMENT   STATEMENTMONTHS   NETSALES     CUSTID
FY_BEG      FY_END
---------- ----------- --------------- ---------- ----------
----------- -----------
      1000 30-JUN-1999              12      80000       1000
30-JUN-1998 30-JUN-1999
      1000 30-JUN-1998              12      67000       1000
30-JUN-1997 30-JUN-1998
      1000 31-MAR-1997               9      45000       1000
30-JUN-1996 30-JUN-1997
      1000 30-JUN-1996              12      40000       1000
30-JUN-1995 30-JUN-1996
August 17, 2000 Jian -- Thanks for the question regarding "return result sets from procedures", version 8.1.6
You Asked
Hi Tom:

You have previously described how to return result sets from a
function.  The technique worked very well and was proved to be
very useful for developing web applications.  I have some
question related to this issue:

1) When I pass a cursor variable as a parameter to a procedure
(instead of a function), the procedure runs fine, but how do I
display the results in SQL*Plus and in JAVA or JSP?

2) Alternatively, passing PL/SQL table as a parameter to a
procedure/function can also accomplish this.  How to display the
results in SQL*Plus and how to call the procedure/function in
JAVA or JSP?

3) Is there a way of passing result sets from JAVA or JSP to
Oracle procedure, for example, a set of records need to be
updated?  Could you give an example?

Thanks in advance.
and we said...
1)

See
http://osi.oracle.com/~tkyte/ResultSets/index.html
it has examples for SQLPlus, Pro*C, Java/JDBC, ODBC, ADO/ASP,
DBI Perl and OCI (jsp = java)...

2) don't do that -- see #1.

3) see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:331217279811
for how to pass collections to/from java.
Review & Followup
Rating: 5
return result sets from procedures February 06, 2002
Reviewer: Niloufar from Austin, TX USA
Tom,

I just want to thank you for this wonderful website.
Since I've discovered your web page I visit almost
every day just to learn something new.  And here is
yet another article that has been so useful.

Thanks for all your effort.

August 17, 2000 Arindom -- Thanks for the question regarding "WebDB and SSL", version 2.2.0.0.5
You Asked
Hello,

     Is it possible to use SSL with WebDB 2.2?
     Does the Listener needs to be configured?
     If so how?

Thanks.
- Arindom
and we said...
You must use OAS or some other listener that supports SSL.
Currently, with WedDB 2.2, the most common SSL configuration is
to use OAS with the webdb cartridge....
August 17, 2000 Satish -- Thanks for the question regarding "regarding sql * net parameters", version 8.0.5
You Asked
Sql *net message from client is always 99.9 %. Can we tune sql
*net parameters so that performance can be increased ? What all
tunnings are required as far as sql * net is concerned ?

How do I decrease waiting for undo header and block ?
and we said...
The sqlnet "message to|from client" is a totally normal wait
event.  Not much you can do to tune it beyond making your end
users type faster -- this is the wait time by the
dedicated/shared server waiting for the client to tell it to do
something or the client waiting for the server to respond.  If
your application runs a query and the user spends 5 minutes
reviewing the output -- the message from client wait is just
going to keep on ticking.

Undo header - more rollback segements
Data block -- increase freelists on heavily accessed objects
(tables and indexes).  In 8.0 and before this implies a rebuild.
 In 8.1.6 you can alter the object to add freelists..
August 17, 2000 Raj -- Thanks for the question regarding "Is there a way to retrieve table DDL from the database ?", version 8.1.5 enterprise edition
You Asked
I have a table created in one db instance. Now I want to
recreate this exact same table in four different instances. I do
not have the .sql file that was originally used to create this
table. Is there a way I can generate the DDL of a table from the
database including column names, column definitions, indexes &
constraints on the table. I could then use this DDL to recreate
the table in other db instances.
NOTE: I have recently moved from Informix to Oracle. The command
in Informix was called dbschema.

Your help will be appreciated.
and we said...
Its exp / imp in Oracle.

exp userid=scott/tiger tables=emp rows=n file=emp.dmp

will do a "structural" export of the table.  then,

imp userid=scott/tiger file=emp.dmp full=y

will recreate it elsewhere.  .dmp files are binary so if you ftp
them -- make sure to "bin" it.
August 17, 2000 Larry -- Thanks for the question regarding "Sql & PL/SQL", version 8.0.5 & 8.1.5
You Asked
Tom,
Thanks for creating such a wonderful site.  I surf it every day!
I have a user who wants to select the rowid along with the table
contents (a la "select rowid, * from emp", which of course isn't
correct, but you get my drift).  How would you tackle this?  via
dynamic sql*plus or pl/sql?  Again, thanks for all your fine
efforts.  By the way, is there a way I can surf (or download)
all your past questions/answers so that I can review them later?
   Thanks very much, Larry Manns
and we said...
select rowid, emp.* from emp;

will do it.....

I currently do not have such a thing but since there are over
1,000 of these things now -- it might be time to start
organizing them differently.  Check back later for that (no
timeframe as yet...)
August 17, 2000 Ashish -- Thanks for the question regarding "What is New with Oracle release 3", version 8.1.5
You Asked
Hi Tom,

We are currently using Oracle 8.1.5. and OAS 4.0.81 on Solaris.
What is the advantage or what's the feature of 8.1.7. over 8.1.5
as well as Ias over Oas. Does 8.1.7 supports Ias? Also we are
using cron tabs for email send. I understand there is some
featue in 8.1.7 for email send program. What is the advantage?

Thanks,

ashish
and we said...
See
http://www.oracle.com/database/oracle8i/index.html?oracle8ir3.html
for a taste of whats coming in 8.1.7 (which is announced but not
shipping at this date)

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
for all of the details of whats new in 8.1.6 (including the
UTL_SMTP package which lets plsql send email directly....  thats
in 8.1.6)....

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:563823000462
for OAS/iAS related stuff.  iAS is not just a webserver,
not just the middle tier.
August 17, 2000 Rajini -- Thanks for the question regarding "Can SQL*Loader load files greater than 2 gig in size?", version 7.3.4
You Asked
Tom,
Can SQL*Loader load files greater than 2 gig in size and if so
how?
and we said...
yes, if you use a device that does not support "seeking".

What you would do is:

$ mknod input.dat p
$ cat really_big_file.dat > input.dat &
$ sqlldr .... data=input.dat

sqlldr will read off of the pipe, not the original file.  This
trick is very useful as well to perform some sort of "scrub" on
the data prior to load using cut or awk or perl or whatever as
well...
Review & Followup
Rating: 4
Extreemly cooll January 29, 2003
Reviewer: Mikey from Atlanta, GA
Thanks for posting the mknod trick it has been helpful in the past!

August 17, 2000 -- Thanks for the question regarding "comparing two schemas", version 8i
You Asked
I tried to compare two schemas in tge same database.
I used the code depot code .
at
http://www.oracle.com/oramag/code/cod03309.html
I got some error messages in creating the link.
Can you help me please ?
Is  there any other way to do it?

ERROR at line 1:
ORA-04052: error occurred when looking up remote object
NSBR.USER_TABLES@AATLNK
ORA-00604: error occurred at recursive SQL level 1
ORA-02085: database link AATLNK connects to ORCL
and we said...
Quickest workaround

alter session set global_names=false;

that'll get you going right away.

Another solution -- name the database link ORCL not AATLNK...

Another solution -- rename the database you created the dblink
to AATLNK via "alter database rename global_name to AATLNK"...
August 17, 2000 mike -- Thanks for the question regarding "Stored procedure to limit number of fetched rows with an ORDER BY statement", version 8.1.5 or 8i
You Asked
Problem:  To write a stored procedure to retrieve the most
recent 5 news articles on a news table with 1 million rows.

Given:  Table news has 1,000,000 news stories that are populated
every hour.

Basically i would like to write a stored procedure that would
give as output a result set which is the top 5 rows of
(
select * from news order by transmission_timestamp descending.
)

here's what i got so far
-----
create or replace procedure
get_news(ticker_value in varchar2, news_curs out
types.cursorType)
is
begin
  open news_curs for
  select n.news_id, n.story_headline, n.filename,
n.transmission_time, n.source_
code  from news n, ticker_news_xref t where
t.ticker=ticker_value and n.news_id=
t.news_id order by transmission_time desc;
END;
-----

But this would return 1,000,000 rows.  I would like to take the
first 5 rows.  Now, ROWNUM does not work with an order clause.
ROWNUM simply returns to you the first 5 rows without the order
by applied to it.

On a more general note, I like to know how stored procedures in
Oracle implement the equivalent of temporary tables in other
RDBMS languages like Sybase, Informix.  Secondly, is there a way
to pass a subset from say cursor1 to cursor2?  For example, in
the above problem, i can have a loop of 5 iterations on
news_curs and fetch into a row, but how could i store the 5 rows
into another cursor which i can then give back to the front end
web scripting language?

Thanks in advance.
Mike Onghai
and we said...
In Oracle8i as you have -- it would be for example:

ops$tkyte@8i> variable x refcursor
ops$tkyte@8i>
ops$tkyte@8i> begin
  2    open :x for 'select *
  3                   from ( select *
  4                            from all_users
  5                           order by created desc )
  6                  where rownum <= 5';
  7  end;
  8  /

PL/SQL procedure successfully completed.

ops$tkyte@8i>
ops$tkyte@8i> print x

USERNAME                          USER_ID CREATED
------------------------------ ---------- ---------
WEB$NKATARE                         35703 17-AUG-00
WEB$DRORHER                         35702 17-AUG-00
WEB$BJEFFRIE                        35701 17-AUG-00
WEB$ABCAMPBE                        35700 17-AUG-00
WEB$JMONCHER                        35699 17-AUG-00

You have to use dynamic sql in 8.1.5 because plsql did not quite
yet understand that you can order by a subquery ...

For temporary tables ... See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:48812348054
For how to put one cursor into "another" cursor -- we can do
that.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:139812348065
for the general mechanism.  You would use a collection type
variable and as you fetched them from the cursor -- put them
into this variable (like an array of records).  You can then
"select * from <this plsql variable>" later to re-retrieve them
(or sort them or where on them or use them in a subquery or
whatever...)
August 17, 2000 minnie -- Thanks for the question regarding "how to get the out parameter in select statement?", version oracle8i 8.1.5
You Asked
Hi,Tom:
If I have a external procedure like:
int donothing(with_context, num_in, num_in_ind, num_out,
num_out_ind)
OCIExtProcContext     *with_context;                /* With
Context */
int        num_in;
short      num_in_ind;
int      *num_out;
short    *num_out_ind;
{
  ocictx    oci_ctx;
  ocictx    *oci_ctxp = &oci_ctx;
  sb4        err;
  char        errbuf[512];

  /* Obtain OCI handle for SQL statement using the context
passed. */
  err = OCIExtProcGetEnv(with_context,                       /*
With context */
                         &oci_ctxp->envhp,
                         &oci_ctxp->svchp,
                         &oci_ctxp->errhp);
  check_err("OCIExtProcGetEnv", err, errbuf, oci_ctxp);

  *num_out = num_in;
  *num_out_ind = (short)OCI_IND_NOTNULL;     /* indicate not
null value */
  return num_in;
}

and I want to use it in a cursor in a package like this way:

create or replace package test_out_pkg is
    FUNCTION donothing(num_in IN binary_integer, num_out OUT
BINARY_INTEGER)
     return pls_integer ;

    procedure test_out;

end;
/

create or replace package body test_out_pkg is
FUNCTION donothing
  (num_in IN binary_integer, num_out OUT BINARY_INTEGER)
return pls_integer
IS EXTERNAL
NAME "donothing"
LIBRARY SELIB
WITH CONTEXT
PARAMETERS
(
    context,
         num_in                      INT,
         num_in           INDICATOR SHORT,
         num_out             int,
         num_out     INDICATOR SHORT
);

procedure test_out is
    v_num_out1    number;
    ls        number;
         cursor c1(ci_num_out out number) is
    select empNo,donothing(empNo,ci_num_out) ls
    from emp
         order by ls desc;
begin
    ls := donothing(1,v_num_out1);
    dbms_output.put_line('ls='||to_char(ls));
    dbms_output.put_line(v_num_out1);
    for c in c1(v_num_out1) loop
        dbms_output.put_line('num_in='||to_char
                  (c.mediol_case_id)
        ||' num_out='||to_char(v_num_out1)||' ls='||
                  to_char(ls));
    end loop;
end;
end;
/

The result is :
   when call the "DONOTHING" external procedure in procedure
body , I succeeded. but it failed in the cursor. My target is
call it once only in the cursor, because i need the return value
and the out parameter.

I apologize for the email sended uncompletely. By the way , I
suggest that improve the interface of this page, yesterday,
after
i typed some stuff, i used to type the TAB key and the cursor
located in TAB key, and my information just sent out. I suggest
there should be an confirm interface after submit.

Thanks

Minnie
and we said...
2 problems here:

1) You cannot call a PROCEDURE from SQL only a function.  You
have the above defined as a function but it doesn't return
anything sensible.

2) you cannot call a function that has an OUT parameter -- only
in parameters are allowed in SQL.

Your solution is easy -- use a function that returns the number.

Say you have:

   function return_number return number;

and

   function return_number return number
   as
   language C
   name "return_number"
   library demoPassing
   with context
   parameters ( CONTEXT,
                RETURN INDICATOR short,
                RETURN OCINUMBER );

And then C code like:

#ifdef WIN_NT
_declspec (dllexport)
#endif
OCINumber * return_number
 ( OCIExtProcContext * ctx,
   short *             return_i )
{
double      our_number = 123.456;
OCINumber * return_value;
myCtxStruct*myCtx;

    *return_i = OCI_IND_NULL;

    /* gets the svchp, errhp, envhp and so on... */
    if ( (myCtx = init( ctx )) == NULL ) return NULL;

    /*
     * Allocate storage for the number we are returning.  We
     * cannot just
     * use a stack variable as it will go out of scope when we
     * return.
     * Using malloc would be a cause for a memory leak.  Using a

     * static
     * variable would not work either as due to dll caching --
     * someone else
     * can come along and alter the values we are pointing to
     * after we
     * return (but before Oracle has copied the value).
     * Allocating storage is the only correct way to do this.
     */
    return_value =
             (OCINumber *)OCIExtProcAllocCallMemory(ctx,
                                     sizeof(OCINumber) );

    if( return_value == NULL )
    {
        /* a function i wrote to call the oci error function */
        raise_application_error( myCtx,
                ERROR_OCI_ERROR, "%s", "no memory" );
    }
    else
    {
        /*
         * Here we just want to return the number 123.456 --
         * nothing fancy,
         * therefore we just convert that double into an
         * OCINumber, set the
         * indicator variable and return our return_value...
         */
        if ( OCINumberFromReal( myCtx->errhp, &our_number,
                     sizeof(our_number), return_value ) !=
                                                  OCI_SUCCESS )
        {
            raise_application_error(myCtx,ERROR_OCI_ERROR,
                                    "%s",lastOciError(myCtx));
        }
        *return_i = OCI_IND_NOTNULL;
    }

    /* undoes any setup i did in init() */
    term(myCtx);
    return return_value;
}
August 17, 2000 Shalini -- Thanks for the question regarding "PL/SQL", version oracle 8i release 2
You Asked
Hi Tom,

The question i am asking is perhaps a very stupid one ..but
nevertheless..
i have been asked to build a bare frontend using pl/sql..
the first step is to provide the users a menu and ask them to
select an option .. so i use "dbms_output" statemtns to output
the menu options and then read the user input using "&" operator
.. but my problem is when i run this script, it first asks user
for input and then shows him all the options while it should be
doing exactly the opposite..is there any solution !

thanks in advance
shalini
and we said...
Sorry -- you cannot build a bare front end with PLSQL.  PLSQL
running in the database has absolutely no ability/capability
to interact with the end user whatsoever.  PLSQL running in
forms does -- but thats hardly a "bare front end".

You've been given the impossible challenge.  Now, we can do
something perhaps in SQLPlus using "prompt" and "accept" but it
will be not be very elegant or straight forward.
August 17, 2000 -- Thanks for the question regarding "eliminating rows", version 8.1.5
You Asked
Dear tom,
I have written a query to fetch the data from 6tables by using
join conditions and predicate.I am facing some problems with the
data.
My query looks like
SELECT COL1,COL2.. from TAB1,TAB2,TAB3,TAB4,TAB5,TAB6
WHERE
...JOIN CONDITIONS OF TABLES
...PREDICATE CLAUSES
AND TAB5.ADDRESS_TYPE IN ('A','B','C','D' ..);
If a person is having both the address types 'A'&'B' it will
fetch that person's data twice accor to the above query and
inturn duplicating the persons row.I want my query to fetch him
only once if he is having more than one address type also.
Suppose if address_type='A' has 100rows
and address_type='B' has 20 rows and out of those 15persons have
both the address_type 'A'&'B'.I want only (100 persons who are
not having address type as 'A'+5persons who are having address
type 'B')=105 rows instead of 120 rows according to above
query.Like wise for all the remaining address types.I can use
UNION clause to do it but it is becoming a complex query as I
have to specify the UNION clause for each address type which in
turn affects the performance.Is there any workaround for this
problem other than using UNION?
Any suggestions ...
Thanks
Kamal
and we said...
In general, lets say tab4 is joined to tab5 and the join
condition is:

and tab4.x = tab5.x
and tab4.y = tab5.y

then:

select col1, col2, .....
  from tab1, tab2, tab3, tab4, tab5, tab6
 where ..... joins & predicates ....
   and tab5.address_type in ( 'A', 'B', 'C', 'D', ... )
   and tab5.address_type = ( select MIN(A.address_type)
                               from tab5 A
                              where a.x = tab5.x
                                and a.y = tab5.y )
/

That'll get the address record for this person but only the
address record with the "min" type....  You'll send down to this
subquery any of the columns you join to tab5 with....
August 17, 2000 Ken -- Thanks for the question regarding "Select * vs. select A.columnX", version 8.1.5
You Asked
Hi Tom,

Question regarding performance of SELECTing * from A vs. Select
ColumnA, ColumnB,...etc..from A, which query is faster?
Something else along the same line, which of the following is
faster, and why?
SELECT count(1) FROM A, or SELECT count(*) FROM A;

Thanks alot..:)
Ken.
and we said...
In sqlplus or in PLSQL with an implicit cursor loop -- select *
is fine.

In a program where you are fetching into a fixed number of
columns however -- you should ALWAYS use select c1, c2, c3, ...
and never use select *.  The reason is good programing practice
-- not performance (they are equivalent performance wise).

In sqlplus -- we don't care if the number of column or the order
of columns changes -- it will adapt.

In plsql, if I'm doing something like:

  for x in ( select * from T ) loop
    ...

we don't worry -- it'll adapt.

If, on the other hand I have:

...
   cursor c1 is select * from T;
begin
   open c1;
   fetch c1 into a, b, c;
   close c1;
end;

we do care - we should NEVER code select * in that case (in the
event our table gets created with the columns in a different
order or if someone adds/drops a column.....

As for select count(*) and select count(1).  They are the same.
It is "select count(*)" vs "select count(some_column)" that
might be different:

  1* select count(*), count(1), count(x) from t
ops$tkyte@8i> /

  COUNT(*)   COUNT(1)   COUNT(X)
---------- ---------- ----------
         2          2          1

count(*) and count('Any Constant') are pretty much the same --
use count(*) -- it is what it is for.  count(some_column) is a
count of non-null values in that column -- don't use that when
you want a count of rows in the table -- only when you want a
count of rows that have that column without a NULL in it...
August 17, 2000 Manoj -- Thanks for the question regarding "Oracle XA Library Problem -- database links.", version Oracle 8.1
You Asked
Hello Tom,

We are facing a very typical problem while using the Oracle XA
Library.

We have 2 Oracle DBs - Oracle_Appln and Oracle_Data

In Oracle_Appln DB, we have created a view which is using some
table from another Oracle DB instance Oracle_Data as below :

create view TestView
as
select * from SomeTable@Oracle_Data;

Now when we try accessing this view TestView from the
application, the query fails.

The same query works when executed from SQLPLUS.

Thanks in advance for the help.

Best Regards

MS
and we said...
See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adga1_xa.htm#622487
for the answer...
August 17, 2000 Manoj -- Thanks for the question regarding "MTS Configuration", version Oracle 8
You Asked
Oracle XA documentation says that for using database links with
Oracle XA library, ur server should be MTS enabled. How can I
setup my database with MTS? And also how can check whether my
server is already MTS or not.

Thanks in advance.

Best Regards

MS
and we said...
See
http://technet.oracle.com/doc/oracle8i_816/network.816/a76933/mts.htm#450520
for the details.
August 18, 2000 Mugdha -- Thanks for the question regarding "Using DECODE", version Oracle 8
You Asked
Can you please tell me how can we use a Decode statement in a
cursor.

When I am using the following cursor in my script I get an error
such as

PLS-00402: alias required in SELECT list of cursor to avoid
duplicate column names

CURSOR CUR_INS_AVG_HUN_HDCNT IS
select Decode(TXT_NAM_ORG_LVL_3RD,
'Quality Technology Europe','Quality Technology Europe',
'Machinery VTG','Machinery VTG'),
Decode(TXT_NAM_BSIS_SAL,
'GELE Annual Salary Basis','Monthly',
'GELE Hourly','Hourly',
'GELE Monthly','Monthly'),
Decode(TXT_NAM_ORG_LVL_5TH,'FR','Full Time',
'FT', 'Co-op/Intern/Rehired Pensioner', 'PR', 'Part Time',
'PT','Full Time', 'PL', 'Part Time'),
SUM(SUM_CD_ID_PRSN)/31 as Avg_hdcnt from HRDW_HUN_HDCNT
where TXT_NAM_ORG_LVL_3RD not in('Machinery','Manufacturing')
group by TXT_NAM_ORG_LVL_3RD, TXT_NAM_BSIS_SAL,
TXT_NAM_ORG_LVL_5TH;
and we said...
PLSQL needs these fields to have a name if you are going to
fetch these into a %TYPE record (which you must be).  Therefore,
just alias the columns as you did for the SUM():

CURSOR CUR_INS_AVG_HUN_HDCNT IS
select Decode(TXT_NAM_ORG_LVL_3RD,
'Quality Technology Europe','Quality Technology Europe',
'Machinery VTG','Machinery VTG')   AS COLUMN1,
Decode(TXT_NAM_BSIS_SAL,
'GELE Annual Salary Basis','Monthly',
'GELE Hourly','Hourly',
'GELE Monthly','Monthly') AS COLUMN2,
Decode(TXT_NAM_ORG_LVL_5TH,'FR','Full Time',
'FT', 'Co-op/Intern/Rehired Pensioner', 'PR', 'Part Time',
'PT','Full Time', 'PL', 'Part Time') AS COLUMN3,
SUM(SUM_CD_ID_PRSN)/31 as Avg_hdcnt from HRDW_HUN_HDCNT
where TXT_NAM_ORG_LVL_3RD not in('Machinery','Manufacturing')
group by TXT_NAM_ORG_LVL_3RD, TXT_NAM_BSIS_SAL,
TXT_NAM_ORG_LVL_5TH;
Review & Followup
Rating: 4
March 04, 2003
Reviewer: A reader

August 18, 2000 wallacel -- Thanks for the question regarding "8.1.6", version 8.1.6
You Asked
Tom:

1.when creating table,initrans define the space reserved for
transaction entry in data block, my question is how much space
exactly it allocated?  if it is not much, I am thinking give
some
bigger value to initrans to improve performance when there are
chance lots of user use dml working on the table at same time.

2. when consider the value of initrans ,we only need to know
concurrent transaction include "update,delete and insert",
we don't need to consider "select", am i right?

Thanks,
and we said...
1) initrans is at the block level, about 23 bytes per entry.
It's not a function of how many people are using DML on that
TABLE -- but how many concurrent transactions will modify the
same BLOCK in a given table.  The larger the table --
probably the lower the initrans (your mileage may vary -- if
its a "historical" table where new data is more interesting then
old data then everyone is interested in the same small set of
rows and lots of people will hit the same blocks....)

2) Mostly correct, unless you are using isolation=serializable,
then you want initrans higher to avoid the "cannot serialize
access error" that could be caused by people reusing transaction
slots whilst your transaction is proceeding.
August 18, 2000 sivaram -- Thanks for the question regarding "extents -- what is coalesce", version 7.2.2
You Asked
what are COALESCABLE_EXTENTS?
and we said...
Extents that may be coalesced are extents that are

o not allocated to an object (free space)
o adjacent to each other physically.

adjacent free extents may be coalesced into one larger free
extent.
August 18, 2000 balasubramanian -- Thanks for the question regarding "Undocumented init.ora parameters,converting log file", version 8.0.6/8.1.5
You Asked
Dear Tom,

  I have two questions.

1.I read in a book saying that there are some undocumented
parameters such as '_CORRUPTED_ROLLBACK_SEGMENTS' and
'_OFFLINE_ROLLBACK_SEGMENTS' are exisiting and we can use those
paremeters at emergency time (while debugging the database).Is
there any reference available in oracle web-site for those
un-documented init.ora parameters.

2.In some other database (such as SYBASE), there are some tools
available to convert redo log files into text file which will
contain all the sql statements executed. In case of any failure
or for doing some reasearch, that text file will be much useful.
In ORACLE is there any facility to convert log files into
sql-text files?
and we said...
1) undocumented parameters are to be used at the guidance of
support.  The above are not for "debugging" purposes but to be
used as a last ditch "get some of my data out of this failed
instance" when working with support (and all else has failed).
There are many things that should be tried prior to setting
those (once you use some of these -- your database is toast and
must be rebuilt) and what you need to try depends on your
circumstances and varies from release to release.

2) logminer does that.
http://technet.oracle.com/doc/server.815/a68020/ch2.htm#141051
...
August 18, 2000 raj -- Thanks for the question regarding "pl\sql", version oracle 8.0.3
You Asked
hi tom.thank u for your help.
i created database triggers which fire ,if inserted or updated
or
deleted from my base tables. and the effected data is pudhed
into
temp tables.i have few parent child tables. the problem is, the
frontendiam using to enter data is saving the  parent data when
i
move from parent screen to child  to enter data  ,which creates
new
rec in my temp table,and it also saves the parent record  along
with
child recordwhich creates a update record in my temp table which
is
unwanted. i  created a trigger after insert  to delete this
update
record, when actually updating the record, that update record is

also being deleted.is there way out.
help me tom.
bye
and we said...
Not following you here 100%.  Is what you want a method to
detect if a record is actually modified before logging it?  If
so, try:

ops$tkyte@8i> create table t ( x int, y int );
Table created.

ops$tkyte@8i> insert into t values ( 1, 1 );
ops$tkyte@8i> insert into t values ( 2, null );
ops$tkyte@8i> insert into t values ( null, 3 );
ops$tkyte@8i> insert into t values ( null, null );

ops$tkyte@8i> create or replace trigger t_trigger
  2  after update on t for each row
  3  begin
  4      dbms_output.put_line
  5      ( 'Checking to see if records are modified' );
  6      dbms_output.put_line
  7      ( 'Old (x,y) = ("'||:old.x||'","'||:old.y||'")');
  8      dbms_output.put_line
  9      ( 'New (x,y) = ("'||:New.x||'","'||:New.y||'")');
 10
 11      for x in ( select * from dual
 12                  where NOT exists
 13                      ( select :new.x, :new.y from dual
 14                        INTERSECT
 15                        select :old.x, :old.y from dual )
 16               )
 17      loop
 18          dbms_output.put_line
 19          ( 'Records HAVE in fact been updated...' );
 20      end loop;
 21  end;
 22  /

Trigger created.

ops$tkyte@8i> update t set x = x;
Checking to see if records are modified
Old (x,y) = ("1","1")
New (x,y) = ("1","1")
Checking to see if records are modified
Old (x,y) = ("2","")
New (x,y) = ("2","")
Checking to see if records are modified
Old (x,y) = ("","3")
New (x,y) = ("","3")
Checking to see if records are modified
Old (x,y) = ("","")
New (x,y) = ("","")

4 rows updated.

ops$tkyte@8i> update t set x = x+1;
Checking to see if records are modified
Old (x,y) = ("1","1")
New (x,y) = ("2","1")
Records HAVE in fact been updated...
Checking to see if records are modified
Old (x,y) = ("2","")
New (x,y) = ("3","")
Records HAVE in fact been updated...
Checking to see if records are modified
Old (x,y) = ("","3")
New (x,y) = ("","3")
Checking to see if records are modified
Old (x,y) = ("","")
New (x,y) = ("","")

4 rows updated.

ops$tkyte@8i>

The for loop will either execute 1 time or NEVER.  If the
records are IDENTICAL (including nulls and all) the loop does
NOT execute (so put your "audit" logic in there).  If the
records differ at all -- the loop will execute exactly 1 time
(unless someone adds a row to dual in which you have much larger
problems then this ;)
August 18, 2000 Nenuka -- Thanks for the question regarding "Data Encryption", version oracle8
You Asked
In which way can i use data encryption in oracle.
How to encrypt data.
and we said...
Unfortunately -- you only put "Oracle8" in the version -- not
the exact release....

In 8.1.6 there is a package that does this, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:95412348059
for more info.

Prior to that, you can add your own via external procedures. To
see what an external procedure looks like, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:341817437103
...
August 18, 2000 Bala -- Thanks for the question regarding "Naming Export dmp files in NT", version 8.0.5
You Asked
Hi Tom,

I read your answer for a similar Question, but that was for
Unix. But in Windows NT, if i want to name the export dump files
with filename + sysdate how can achieve that.

In NT Shell script, i can't directly export the sysdate to a
variable.

Thanks
Bala.
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:612348047
...
August 18, 2000 Ryno -- Thanks for the question regarding "Rollback segments offline when service reboot", version 8.0.5
You Asked
Hi Tom,

I have a question for you that have been bugging us here at the
office for a while.  We have and Oracle 8.0.5 db on an NT4 SP5
Compact server.  In the init.ora fiel for the db we specified
rollback_segments = (rb01,rb02,rb03,sysroll) with the idea that
the rollbacks will be online when we reboot the machine.

Q1.  How do you specify that the rollback segments must be
on-line whne you reboor the machine.

Thanks, regards
Ryno

PS.  We have ask Oracle SA and they suggested the above sessing
in the init file.
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:524422255507
In short, if you create the rollback segments as PUBLIC rollback
segments, you do not need list them.  If they are not public,
you do need to list them.
August 18, 2000 Mona -- Thanks for the question regarding "oracle8 with servlet", version oracle8
You Asked
Hello sir,

I wrote servlet program (java code), this program make access to
database (oracle),for this program i need to define the oracle
derive and the URL for the DB .

i do not know what the correct command  by java to do this .

so , i want know this command ? please

Thanks

Mona
and we said...
depends on whose/what type of jdbc driver you are using.

If you have a jdbc thin driver from Oracle -- the url will be:

"jdbc:oracle:thin:@HOSTNAME:PORT:ORACLE_SID"

If you are using our OCI driver it will be:

"jdbc:oracle:oci8:@TNS_CONNECT_STRING"

where the text in uppercase would be replaced with the
appropriate values.
August 18, 2000 Pam -- Thanks for the question regarding "Running from a UNIX script", version Oracle 7.3.4.5. & V8 soon
You Asked
Is there a simple way to get the associated count from an SQL or
PL/SQL select statement out to the UNIX script calling it?  In
COBOL I could use SQLERRD(3) so it would seem to be possible.

The only solution suggested so far is hacking about with a count
in a spool file which would work but it seems very clumsy. Also
I think it means that I would have to scan the database twice as
my output is a report for clerical use. The number of rows
selected will vary from none to hundreds or even thousands and I
need to warn the operators to check large runs with Support as
it may, or may not, need printing

Thanks

Pam
and we said...
Well, the sqlerrd structure is part of the SQLCA -- a
datastructure we explicitly use to communicate to your Cobol
program whats going on.  Its not applicable to an environment
like SQLPlus (which is not a programming environment).

What you can do is use grep or egrep to find information out.
For example:

-----------------------------------------------
#!/bin/csh

sqlplus / <<EOF | egrep '(^CNT|rows selected.$)'
set echo on
show spool

select * from all_users where rownum < 10;

set serveroutput on

begin
    --- your code here.  sql%rowcount or a counter
    -- can be used
    dbms_output.put_line( chr(10)||'CNT= 1000' );
end;
/
spool off
exit

EOF

----------------------------------------------

When that is run, we get:

$ test.csh
9 rows selected.
CNT= 1000

So, with a little grep, sed, and or awk -- you can get what you
need.

SQLPLUS does have the ability to exit with a return code which
is another option:

-----------------------------------
#!/bin/csh

sqlplus -s / <<EOF
exit $1
EOF

echo $status from SQLPlus
-----------------------------------

But with this you can only really get numbers 0..255 out (limit
of the sh, nothing we can do).  So, here are the results when
you exit with 1, 255, 256, and 257:

$ test.csh 1
1 from SQLPlus
$ test.csh 255
255 from SQLPlus
$ test.csh 256
0 from SQLPlus
$ test.csh 257
1 from SQLPlus
$

notice how the number just wraps at 256 -- thats the shell, it
only reports back 1 byte of the exit code from a process.  You
might be able to use this to exit with a "small", "med" and
"large" number or something similar.
August 18, 2000 Kasthuri -- Thanks for the question regarding "java.sql.SQLException: No suitable driver", version 8.1.5
You Asked
Hi Tom,

 I have a SelContrib.java inside which i use something like
this:
 {
.......
  String driver_class = "oracle.jdbc.driver.OracleDriver";
  String connect_string = "jdbc:oracle:thin:@sun1:1521:pyu1";

  Connection conn;
        try {
           Class.forName(driver_class);
           conn = DriverManager.getConnection( connect_string,
"user","pass");
........
  }

 This works fine when i compile and execute
when i load this class into oracle and use a function with call
spec and then call it, it gives me the
"java.sql.SQLException: No suitable driver" Exception
If i use,
  conn = new OracleDriver.defaultConnection(), then load the
class and call it,it works fine.

 we dont want to import oracle.jdbc.driver.*; There is nothing
wrong with the url or connect string since other programs that
use it work good. It is only when i use a call spec and call it
from my function in oracle that it gives a prob.

it would be helpful if you can throw some light on this

Thanks & Regards
J.Kasthuri
and we said...
You are using the wrong driver -- here is how:

ops$tkyte@8i> create or replace and compile java source
                                               named "test3"
  2  as
  3  import java.io.*;
  4  import java.sql.*;
  5
  6  class test3
  7  {
  8
  9  public static void test()
 10  throws SQLException, ClassNotFoundException
 11  {
 12      Connection connection = null;
 13
 14      Class.forName( "oracle.jdbc.driver.OracleDriver" );
 15
 16      connection =
 17        DriverManager.getConnection
 18        ( "jdbc:oracle:kprb:", "", "" );
 19
 20      Statement stmt = connection.createStatement();
 21      ResultSet rset = stmt.executeQuery
 22                       ( "select user from dual" );
 23
 24      while ( rset.next() )
 25          System.out.println( rset.getString(1) );
 26
 27      rset.close();
 28      stmt.close();
 29  }
 30
 31
 32  }
 33  /

Java created.

ops$tkyte@8i>
ops$tkyte@8i> create OR replace procedure test3
  2  as
  3  language java
  4  name 'test3.test()';
  5  /

Procedure created.

ops$tkyte@8i>
ops$tkyte@8i> exec dbms_java.SET_OUTPUT( 1000000 )

PL/SQL procedure successfully completed.

ops$tkyte@8i> exec test3
OPS$TKYTE

PL/SQL procedure successfully completed.
August 18, 2000 C -- Thanks for the question regarding "Meaning of Values for Privileges in ALL_TAB_GRANTS", version Oracle Server 7.3.2.2.0
You Asked
I'm new to Oracle and have been looking at ALL_TAB_GRANTS to
review current permissions.  What is the meaning of the value
'A' in INSERT_PRIV or UPDATE_PRIV or in any other field?  The
'Y' and 'N' seem obvious as Yes and No, but the 'A' is unknown
to me.  My guess was Audit, for a setting that would allow the
privilege but also log it.  Actually my first guess was that 'A'
stood for Application, meaning that you could perform the
function only thru the application and not thru SQL*Plus, but
that's been ruled out by my boss.

I thought I would be able to find something like this quickly in
an Oracle book, but have been unsuccessful.  Thanks for any
enlightenment you can provide.
and we said...
ALL_TAB_GRANTS is a holdover table from v6 of the database - not
used in 7.x or 8.x. "A" was for GRANTED with the ADMIN option
(so I can grant it to others).

It is not relevant.  ALL_TAB_PRIVS is what you want instead.
Some databases still have an ALL_TAB_PRIVS for backwards
compatibility with really old scripts -- but most do not.


Subject | Article | Last Updated (East coast time)
Using a matrix for input to table | article only | Aug 19, 2000 12:15 pm
insert clob in a preparestatement in java | article only | Aug 19, 2000 02:02 pm
Stored Procedure with Activex Dll and Visual Basic... | article only | Aug 20, 2000 08:57 am
DRIVER IN ORACLE | article only | Aug 20, 2000 09:01 am
Is it a must to run pupbld.sql as system | article only | Aug 20, 2000 09:25 am
Regarding Password Decryption. | article only | Aug 20, 2000 09:27 am
oracle file very large | article only | Aug 20, 2000 09:29 am
Establish a connection to Oracle Database Server ??? | article only | Aug 20, 2000 09:33 am
Custom database startup script for Oracle on NT | article only | Aug 20, 2000 09:34 am
API for messaging | article only | Aug 20, 2000 02:24 pm
useing nls in devolper 2000 | article only | Aug 20, 2000 02:38 pm
jdbc program | article only | Aug 20, 2000 03:56 pm
The nature of result fetches/temp space | article only | Aug 20, 2000 05:34 pm
How to load the XXXYY.msg files (error codes and messages) into the database | article only | Aug 20, 2000 07:15 pm
Cluster Index | article only | Aug 21, 2000 07:01 am
export table more than 2 GB | article only | Aug 21, 2000 07:02 am
configure WebDB(HP Unix) with Microsoft IIS 3.0 | article only | Aug 21, 2000 07:05 am
Quering a table -- getting the N'th row | article only | Aug 21, 2000 07:10 am
DBLink -- can you have one from 7.2 to 8 or 8i? | article only | Aug 21, 2000 07:20 am
SQL -- how to assign rownum after a sort. | article only | Aug 21, 2000 10:22 am
Selecting last 2 rows when you don't know how many are being selected. | article only | Aug 21, 2000 03:00 pm
Export , Rollback Segment | article only | Aug 21, 2000 03:38 pm
Query to retrieve specific set of duplicate values | article only | Aug 21, 2000 03:45 pm
Redo Log and Control files: Software mirror and hardware mirror | article only | Aug 21, 2000 03:57 pm
TKPROF | article only | Aug 21, 2000 05:02 pm
Special Characters -- in a create user command | article only | Aug 21, 2000 06:50 pm
Invoking htp packages | article only | Aug 21, 2000 08:38 pm
doing a hit counter on the web. | article only | Aug 22, 2000 06:59 am
Oracle office Application Program interface | article only | Aug 22, 2000 07:04 am
Client Certificate -- using with OAS | article only | Aug 22, 2000 07:37 am
PL/SQL server pages | article only | Aug 22, 2000 07:52 am
Migrating FOXPRO database to Oracle | article only | Aug 22, 2000 07:54 am
Maintaining count of detail records online, redudantly | article only | Aug 22, 2000 12:35 pm
PL/Sql -- generating the last day of a month given a range. | article only | Aug 22, 2000 03:42 pm
Logging out from OAS | article only | Aug 22, 2000 03:57 pm
datafile size > 2Gig | article only | Aug 22, 2000 04:08 pm
Create a database | article only | Aug 22, 2000 04:20 pm
Passing an array of strings to a where clause -- for us in an in list | article only | Aug 22, 2000 04:26 pm
UTL_FILE - how to use it? | article only | Aug 22, 2000 04:28 pm
RAID configuration ? | article only | Aug 22, 2000 04:37 pm
Number matching query -- sort of a tricky one... | article only | Aug 22, 2000 07:53 pm
Re-create Index | article only | Aug 23, 2000 08:05 am
Tips Related to Database Tuning | article only | Aug 23, 2000 08:13 am
Online Help | article only | Aug 23, 2000 09:20 am
How to pass a Blob buffer between C external procedure and pl/sql? | article only | Aug 23, 2000 10:29 am
Java Sored Procedure - Oracle | article only | Aug 23, 2000 10:39 am
Application Servers - Submitting SQL querys -- getting a result set from cold fusion. | article only | Aug 23, 2000 02:21 pm
IMPORT | article only | Aug 23, 2000 03:44 pm
Loading Lobs Using SQL Loader | article only | Aug 23, 2000 08:19 pm
Shrinking High Water Mark | article only | Aug 23, 2000 08:27 pm
any simple way to export ORACLE connections in UNIX? | article only | Aug 24, 2000 08:37 am
Knowling the size of the table in BYTES | article only | Aug 24, 2000 08:44 am
upgradation | article only | Aug 24, 2000 08:49 am
SQL Loader / Import | article only | Aug 24, 2000 09:05 am
SQLJ, no output and error codes always 0 | article only | Aug 24, 2000 10:21 am
The different values of the OPTIMIZER_MODE column in V$SQLAREA | article only | Aug 24, 2000 10:59 am
QUERY_STRING | article only | Aug 24, 2000 11:13 am
SQLJ, no output and error codes always 0 PT 2 | article only | Aug 24, 2000 11:52 am
Batch Webdb -- exporting more then 1 object | article only | Aug 24, 2000 12:15 pm
Dropping / Altering a Directory | article only | Aug 24, 2000 12:47 pm
Creating additional database instances on UNIX. | article only | Aug 24, 2000 02:38 pm
OCI | article only | Aug 24, 2000 02:42 pm
Primary and Foreign Keys | article only | Aug 24, 2000 04:08 pm
ALTERNATIVE SOLUTION for Standby Database | article only | Aug 24, 2000 07:23 pm
check list | article only | Aug 24, 2000 07:50 pm
Particiones y/o volumenes logicos | article only | Aug 25, 2000 08:11 am
check the performance of the website and how many people have visited the website | article only | Aug 25, 2000 08:15 am
Database Backup on Linux | article only | Aug 25, 2000 08:29 am
REGARDING CHANGE OF PASSWORD | article only | Aug 25, 2000 10:20 am
Creating Table same as existing table. | article only | Aug 25, 2000 10:25 am
"Random Sample" | article only | Aug 25, 2000 03:01 pm
Function Index not being used | article only | Aug 25, 2000 03:12 pm
performance en OPS | article only | Aug 25, 2000 03:24 pm
Returning a table from a procedure. | article only | Aug 25, 2000 03:28 pm
Shell scritps from OAS. | article only | Aug 25, 2000 04:05 pm
Data Import. | article only | Aug 25, 2000 04:09 pm
Instance | article only | Aug 25, 2000 06:41 pm
alert file | article only | Aug 25, 2000 07:08 pm
disk i/o | article only | Aug 25, 2000 07:11 pm
pl/sql | article only | Aug 25, 2000 07:39 pm
PIM | article only | Aug 25, 2000 07:47 pm
row(s) 1 - 81 of 81
August 19, 2000 Alex -- Thanks for the question regarding "Using a matrix for input to table", version Forms 6
You Asked
We are facing a problem in using a matrix as a basis to input
data to a table.

The table will have the following structure ;-

Doc_Num varchar2(20)
Line_No number(3)
Item_Code varchar2(10)
Color varchar2(10)
Size varchar2(10)
Quantity number(7,2)

To ease data entry we intend to put up a form that looks like
this

Doc Num : ______________
Line No : ___

Item Code : _________
+------+---+---+---+---+---+
|Color |  3|  4|  5|  6|  7|
+------+---+---+---+---+---+
|      |   |   |   |   |   |
+------+---+---+---+---+---+
|      |   |   |   |   |   |
+------+---+---+---+---+---+
|      |   |   |   |   |   |
+------+---+---+---+---+---+
|      |   |   |   |   |   |
+------+---+---+---+---+---+

where each line_no will contain variable number of sizes and
colors. The different sizes are entered in the Item master file
when new items are added.

The problem is that we are not able to build the matrix for data
input. We are able to understand however how to extract existing
data from a table and present it in the matrix but how can I do
it the other way round, that is to use the matrix as a basis for
data entry.

Thank you in advance.
and we said...
So, if I understand, you have something like:

doc num:    ______1
line num:   ______1
Item Code:  ____ABC

      1"    2"    3"    4"     (size in inches for example)
RED   5     6     7     8
GREEN 9     1     2     3
BLUE  4     5     6     7

correct?

You can do this in one of two ways.

1) you can use ON-INSERT, ON-UPDATE, ON-DELETE, ON-LOCK and so
on triggers within forms to do the DML your self

2) you can create a view which makes the matrix for you and then
use instead-of trigger (Oracle8.0 and up) in the database.

Here is an example using instead of triggers.  The logic I have
in the triggers is similar to what you will put in the ON-*
triggers in the form if you go down that path.

ops$tkyte@8i> create table t
  2  ( doc_num   varchar2(20),
  3    line_no   number(3),
  4    item_code varchar2(10),
  5    color     varchar2(10),
  6    item_size varchar2(10),
  7    quantity  varchar(2) );

Table created.

[some inserts into T go here...]

ops$tkyte@8i> create or replace view V
  2  as
  3  select doc_num, line_no, Item_code, color,
  4  max( decode( item_size, '1"', quantity, null ) )"1 INCH",
  5  max( decode( item_size, '2"', quantity, null ) )"2 INCH",
  6  max( decode( item_size, '3"', quantity, null ) )"3 INCH",
  7  max( decode( item_size, '4"', quantity, null ) )"4 INCH"
  8    from t
  9   group by doc_num, line_no, Item_code, color
 10  /

View created.

ops$tkyte@8i>
ops$tkyte@8i> select * from v;

DOC LINE_NO ITEM_CODE  COLOR 1  2  3  4
--- ------- ---------- ----- -- -- -- --
1         1 ABC        BLUE  4  5  6  7
1         1 ABC        GREEN 9  1  2  3
1         1 ABC        RED   5  6  7  8

ops$tkyte@8i> create or replace trigger v_trigger_INSERT
  2  instead of INSERT on V
  3  begin
  4      insert into t
  5      (doc_num,line_no,item_code,color,item_size,quantity)
  6      values
  7      (:new.doc_num,:new.line_no,:new.item_code,:new.color,
  8       '1"',:new."1 INCH" );
  9
 10      insert into t
 11      (doc_num,line_no,item_code,color,item_size,quantity)
 12      values
 13      (:new.doc_num,:new.line_no,:new.item_code,:new.color,
 14       '2"',:new."2 INCH" );
 15
 16      insert into t
 17      (doc_num,line_no,item_code,color,item_size,quantity)
 18      values
 19      (:new.doc_num,:new.line_no,:new.item_code,:new.color,
 20       '3"',:new."3 INCH" );
 21
 22      insert into t
 23      (doc_num,line_no,item_code,color,item_size,quantity)
 24      values
 25      (:new.doc_num,:new.line_no,:new.item_code,:new.color,
 26       '4"',:new."4 INCH" );
 27  end;
 28  /

Trigger created.

ops$tkyte@8i> show err
No errors.
ops$tkyte@8i> create or replace trigger v_trigger_DELETE
  2  instead of DELETE on V
  3  begin
  4      delete from t
  5        where doc_num      = :old.doc_num
  6          and line_no      = :old.line_no
  7          and item_code    = :old.item_code
  8          and color        = :old.color;
  9  end;
 10  /

Trigger created.

[Left the update trigger up to you -- its very much the same as
the insert trigger but you'll referece :old in the WHERE clause
and :new in the SET clause]

ops$tkyte@8i> insert into v
  2  values ( 2, 2, 'DEF', 'RED', 55, 66, 77, 88 );

1 row created.

ops$tkyte@8i> insert into v
  2  values ( 2, 2, 'DEF', 'GREEN', 55, 66, 77, 88 );

1 row created.

ops$tkyte@8i> insert into v
  2  values ( 2, 2, 'DEF', 'BLUE', 55, 66, 77, 88 );

1 row created.

ops$tkyte@8i>
ops$tkyte@8i> select * from v;

DOC LINE_NO ITEM_CODE  COLOR 1  2  3  4
--- ------- ---------- ----- -- -- -- --
1         1 ABC        BLUE  4  5  6  7
1         1 ABC        GREEN 9  1  2  3
1         1 ABC        RED   5  6  7  8
2         2 DEF        BLUE  55 66 77 88
2         2 DEF        GREEN 55 66 77 88
2         2 DEF        RED   55 66 77 88

6 rows selected.

ops$tkyte@8i>
ops$tkyte@8i> delete from v
  2  where doc_num = 2
  3  /

3 rows deleted.

ops$tkyte@8i>
ops$tkyte@8i> select * from v;

DOC LINE_NO ITEM_CODE  COLOR 1  2  3  4
--- ------- ---------- ----- -- -- -- --
1         1 ABC        BLUE  4  5  6  7
1         1 ABC        GREEN 9  1  2  3
1         1 ABC        RED   5  6  7  8

ops$tkyte@8i>
Review & Followup
Rating: 4
It helps for many situations, we can consider it as a ROLE MODEL September 17, 2001
Reviewer: J'Sri from USA

Rating: 4
Thanks Tom May 21, 2003
Reviewer: Pawan from US
I have trying to write a code where data is pulled from multiple tables and
finally needs to go to Excel into multiple sections. I tried using multiple
cursors in UTL_FILE but could not but this helped me.

August 19, 2000 Chitao -- Thanks for the question regarding "insert clob in a preparestatement in java", version 8.1.6
You Asked
in java, I use prepared statement to do the insertion.
I use instanceof to judge the type of parameters. (see following
code)

but how can I set the type for clob type? for long type, it is
ok to set it as string. but for clob, there is a maximum limit
on the size, I have a clob colum is over 10k which can not be
inserted into my table.

Do you have any suggestion?

    if( inArgs != null ) {
       Object obj;
                        for (int i = 0; i < inArgs.length; i++)
{                                        &#9617;
             obj = inArgs[i];

             if( obj == null || obj instanceof String ) {
                         &#9617;
                 stmt.setString(i+1, (String)obj);
                         &#9617;
             } else if( obj instanceof Integer ) {
                         &#9617;
                 stmt.setInt(i+1, ((Integer)obj).intValue());
                         &#9617;
             } else if( obj instanceof ByteArrayOutputStream ) {
                         &#9617;
                 stmt.setBytes(i+1,
((ByteArrayOutputStream)obj).toByteArray());          &#9617;
             } else {
                         &#9617;
                 throw new SQLException( "internal error:
unsupported datatype
             }
                         &#9617;
         }
                         &#9617;
     }
                         ¨€
and we said...
Blobs and Clobs must be treated "special" in all Jdbc
implementations.  They are done via streams -- not via stmt.set*
calls (although in jdbc 2 you have a setClob and setBlob -- they
are much the same -- see the last referenced link below pointint
to technet.  The mechanics are nearly identical -- insert
empty_clob(), retrieve it, and then stream it).

Here is an example -- it inserts an empty_clob() and then gets
it back out -- you have to select OUT (or use the insert into
... returning clob_column into :bind_variable) lob locator and
cast as a stream.  This shows how to read and write clobs.
There :

import java.lang.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.*;

public class movelr
{
    public static void main(String[] args) throws Exception
    {
        int    length;

        DriverManager.registerDriver (new OracleDriver());

        Connection conn73 = DriverManager.getConnection
              ("jdbc:oracle:oci8:@ora8idev","scott","tiger");
        Connection conn81 = DriverManager.getConnection
              ("jdbc:oracle:oci8:@ora8idev","scott","tiger");

        conn73.setAutoCommit (false);
        conn81.setAutoCommit (false);
        System.out.println( "connected..." );

        // Create statements
        PreparedStatement pstmt = conn73.prepareStatement
                   ("select image from image@slack" );

        System.out.println( "prepared statement for v7.3..." );

        PreparedStatement insertStmt = conn81.prepareStatement
               ("insert into blob_demo ( x, y ) " +
                "values ( ?, empty_blob() )");
        System.out.println
           ( "prepared statement for v8.x BLOB insert..." );

        PreparedStatement getStmt = conn81.prepareStatement
             ("select y from blob_demo where x = ? for update");
        System.out.println
           ( "prepared statement for v8.x BLOB select..." );

        ResultSet rset73 = pstmt.executeQuery();
        System.out.println
           ( "executed statement for v7.3 select..." );

        for( int i = 0; rset73.next(); i++ )
        {
            System.out.println( "looping..." );
            InputStream is = rset73.getBinaryStream(1);
            System.out.println( "Got v7.3 LONG RAW stream..." );

            // Insert a new row and get select
            // back the BLOB column
            insertStmt.setInt(1, i);
            insertStmt.executeUpdate();
            getStmt.setInt(1, i);
            OracleResultSet rset81 =
                 (OracleResultSet) getStmt.executeQuery();

            rset81.next();
            OutputStream os =
                rset81.getBLOB(1).getBinaryOutputStream();
            System.out.println( "Got v8.x BLOB stream..." );

            System.out.println( "Moving data from IS to OS..."
);
            byte buffer[] = new byte[1024];
            while ((length = is.read (buffer,0,1024)) != -1)
            {
                os.write( buffer, 0, length );
            }

            is.close();
            os.close();
            rset81.close();
        }
        rset73.close();
        insertStmt.close();
        getStmt.close();
        pstmt.close();
        conn81.commit();
        conn73.close();
        conn81.close();
    }
}

See also:
http://technet.oracle.com/doc/oracle8i_816/java.816/a81354/oralob2.htm#1043351
for more details.
August 20, 2000 Sachi -- Thanks for the question regarding "Stored Procedure with Activex Dll and Visual Basic...", version xxx
You Asked
Hi,
  I need to call a Dll from Stored Procedure .It is possible in
sql Server. Will it is possible from Orcale.
   Will I be able to create triggers on the fly from Visual
Basic?

Looking for your reply....

with Regards
Sachi
Scapevelocity.com
and we said...
Yes.

In Oracle8.0 and up there is a feature called EXTERNAL
PROCEDURES.  On Windows these are implemented as DLL callouts.

See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adg11rtn.htm#1656
for details.

As for creating triggers on the fly from visual basic -- Yes,
you can do that.  You will just pass through execute "create
trigger ...." statements.
August 20, 2000 ZEINAB -- Thanks for the question regarding "DRIVER IN ORACLE", version ORACLE8
You Asked
HELLO SIR,
{
Loading JDBC Drivers
The first step includes making sure that the jar file that contains the driver
classes is included in your classpath.
}

WHAT DOES THIS STATMENT MEAN ? AND HOW I CAN  JDBC DRIVER IN ORACLE8?

THANKS
and we said...
That means that java uses an environment variable called $CLASSPATH much like
DOC or Unix shells use the PATH environment variable.

My CLASSPATH environment variable on Unix is currently:

$ echo $CLASSPATH
/export/home/oracle8i/jdbc/lib/classes111.zip:/export/home/tkyte/j:/export/home/o
racle8i/sqlj/lib/runtime.zip:.

When a programmer does something like:

....
    DriverManager.registerDriver
          (new oracle.jdbc.driver.OracleDriver());

...

the java runtime will search through my classpath for a class OracleDriver in a
package oracle.jdbc.driver.  It'll go through all of the directories and jar
files in my classpath to resolve this.  Much like the shell or DOS does to find
a program.

As for "AND HOW I CAN  JDBC DRIVER IN ORACLE8?"  you'll have to re-ask that with
more details as I do not understand the question.
August 20, 2000 Ravi -- Thanks for the question regarding "Is it a must to run pupbld.sql as system", version 8044
You Asked
Tom,

I create databases then I run the catalog.sql and catproc.sql.
Sometimes, I donot run pupbld.sql. Users may get warning message
but they could login and work.

But, My friend says that if pupbld.sql is not run as system then
users will get the error messages and they cannot log into the
database at all.  Is it true.

Is it a must to run the pupbld.sql.  I could not see in the
documentation, whether it is a must. If, it is a must, how I am
able to login.

Is this being called by anyother script like catalog.sql,
catproc.sql.  I grepped both the files for pupbld.sql. It does
not exist.

Please clarify.

Regards
Ravi
and we said...
It is not true.  PUBBLD stands for "Product User Profile BuiLD".
 This table has meaning only to sqlplus and no other
interface.  SQLPlus will print a warning message when you
log in but will still log in.

You do not need it.

pubbld.sql is in $ORACLE_HOME/sqlplus/admin -- it is only for
sqlplus and nothing else.
August 20, 2000 Farhad -- Thanks for the question regarding "Regarding Password Decryption.", version 8.1.5
You Asked
Hi Tom,
   Last time u had told me regarding Password Decryption in
Oracle 8i.What about in Oracle8? How do u decrypt the password
in Oracle8?

 Thanks,
 Farhad.
and we said...
In all versions of Oracle -- I myself would not store an
encrypted password but rather a digested or hashed password.
That way, no one can EVER snoop the passwords out of my database
but I can still validate a given username/password pair.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:95412348059
for my approach.
August 20, 2000 razvan -- Thanks for the question regarding "oracle file very large", version 7.3.2
You Asked
Dear Tom,

Because an oracle file become very large the tar don't want to
put this file on a tape.I made a full backup system for entire
file system every night and because this file is very big the
tar don't function for this file and so i don t have a copy for
it in case of a crash.
I have thinked to make a split with comand unix split and then
to make a tar for this files but i am not sure if split work
with binary files and how can i put togher this files to formed
the initial files from tape?
Please, help me.
O mention that the company want to make full system backup with
tar.

thanks a lot
razvan
and we said...
Split works just fine for binary data.  I use it with my exports
(they are binary).  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:122612348063
for my method.

A similar approach will work with a datafile but, you'll
need to split the file before you tar it.

Better yet -- you should just stick with datafiles that are less
then 2gig if your tools do not support files >2gig.
August 20, 2000 Tuan -- Thanks for the question regarding "Establish a connection to Oracle Database Server ???", version 8
You Asked
Dear sir,
I has been learned oracle for 2 weeks. I setup Oracle8i on Linux
platform. It's seem work normally. Now I want to write a Java
program that can connect to Database server.
My Oracle Database Server runs on host: 172.16.10.2
My program runs on host: 172.16.10.25
I have many difficulty:
  + I don't know the name of the oracle samples database when
first installed.
  + What the default port number that server listen on ???
  + What the default user name & password of oracle that can
access to samples database.
  + I created an user: oracle ;passwd: ora. That user can
startup,open Oracle server
  + How can I write the URL for getConnection() ???

Here this is my program

import java.net.URL;
import java.sql.*;
import java.lang.*;
public class test_one
{
   public static void main(String argv[])
   {
      String url="??????";
      System.out.println(" Establishing connection - Please wait
");
      try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      Connection
con=DriverManager.getConnection(url,"oracle","ora");
      System.out.println("Connection Established");
      }
      catch (SQLException e) {
      System.out.println("Error"+e );
      }
    }
}

This is my first step to learn Oracle but I get stuck on it.
Could you please help me to solve this problem ?
Thank you very much !
Your sincerly
Tuan.N.A
and we said...
Well, I don't know what the url for the Sun jdbc driver is -- I
do for the Oracle one...

The url for the Oracle thin driver (available from
http://technet.oracle.com/
) is:

"jdbc:oracle:thin:@HOSTNAME:PORT:ORACLE_SID"

where

o hostname = hostname of the server

o port     = port the listener is running on.  See
             $ORACLE_HOME\network\admin\listener.ora to see
             what port you configured when you installed.  It
             is normally 1521

o ORACLE_SID = sid of the database.  When logged in as the
               person who starts the database, just echo
               $ORACLE_SID to discover this.
August 20, 2000 Amit -- Thanks for the question regarding "Custom database startup script for Oracle on NT", version 8.1.6 on NT4
You Asked
Hi Tom

I have a custom script that pins objects into the
shared pool I would like to run upon database startup.

What is the recommended way in the NT4 environment to
have a custom script run upon database startup ?

In database startup I mean when it is started with
standard methods like via the NT services / OEM + intelligent
agent etc.

Thanks ..
Amit
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:263215360334
for how to do this best on 8i & NT.  Using a startup trigger is
the easiest, robust method...
August 20, 2000 N -- Thanks for the question regarding "API for messaging", version d2k
You Asked
What is API. And how can i use it?
and we said...
An API stands for Application Program Interface.  Examples of
APIs include:

o ODBC -- an API for interfacing to databases
o JDBC -- likewise
o OCI  -- the Oracle Call Interface, provides an API for C
          programs to call the database.

If you are looking for an Oracle API to messaging that would be
Advanced Queuing.  See
http://technet.oracle.com/
for all online documentation.  In particular, for AQ, see
August 20, 2000 Hazem -- Thanks for the question regarding "useing nls in devolper 2000", version sql 3.3 - forms 5 - report3
You Asked
hi tom;
how are you my boos;
how i can use 2 nls_date in one table?
i want make a program use tow defrance date gorgeian date &
arabic date in one application. the date in arabic date today is
(20-jumada ii-1421)and the gorgian date today is(20-august-2000)
pls; tom i need your help becuse it's very important to this
program.
finaly thank you a lot of much
Hazem Badawy
and we said...
Well, you don't really mena "nls_date" but "nls_calendar".

I think we can do this in a database function.  for example:

ops$tkyte@8i> create or replace
  2  function to_string( p_date in date,
  3                      p_fmt in varchar2,
  4                      p_cal in varchar2 ) return varchar2
  5  as
  6      l_return_string varchar2(255);
  7  begin
  8      execute immediate
  9         'alter session set nls_calendar = '''||p_cal||'''';
 10      l_return_string := to_char( p_date, p_fmt );
 11      execute immediate
 12         'alter session set nls_calendar = ''Gregorian''';
 13      return l_return_string;
 14  end;
 15  /

Function created.

ops$tkyte@8i>
ops$tkyte@8i> begin
  2      dbms_output.put_line( sysdate );
  3      dbms_output.put_line( to_string( sysdate,
  4                                     'dd-month-yyyy',
  5                                     'Arabic Hijrah' ) );
  6  end;
  7  /
20-AUG-00
19-????? ?????? -1421

PL/SQL procedure successfully completed.

Now, EXECUTE IMMEDIATE is new to Oracle8i release 8.1 but you
don't specify a version.  You'll have to write your own
execute_immediate procedure in 8.0 and before using DBMS_SQL.
It'll resemble:

create or replace
procedure execute_immediate( p_sql in varchar2 )
is
    cursor_name     pls_integer default dbms_sql.open_cursor;
    ignore          pls_integer;
BEGIN
    dbms_sql.parse(cursor_name, p_sql, dbms_sql.native);
    ignore := dbms_sql.execute(cursor_name);
    dbms_sql.close_cursor(cursor_name);
END;
/
August 20, 2000 Mona -- Thanks for the question regarding "jdbc program", version oracle8.1.5
You Asked
hello sir ,

i wrote java program to test DB, i mean , this program  make
load for oracle driver , and make connections , and print result
from the database.

I have problems : the program can not load the oracle driver ,
when i compile the program there no any error , but when i
execute it,the excpetion give me message "it can not load the
driver" .

i don't no this problem from what? if that need some package
like oracle.jdbc.deriver , please tell me from where i can
download it ?

please give the solution ...
Note: I USE jdk1.1.8 .

thanks
and we said...
You need to get the Oracle thin jdbc driver (or the oci driver,
upto you)

That is available at
http://technet.oracle.com/
  -> Follow the Software link on the left hand side
    -> on the drop down list that says "select a utility
       or driver", choose ORACLE JDBC DRIVERS

and then pick the one you want.
August 20, 2000 steve -- Thanks for the question regarding "The nature of result fetches/temp space", version 8.16.0.0
You Asked
Hi Tom,

I would like to establish what exactly happens when a
cursor is opened in a bid to predict temp space usage.
(and just general curiosity).

A scenario: a pl/sql session opens three multi-join cursors
with, for example, one having an order by.

How might you predict the amount of space required?, I
understand the rows have been identified when the open
returns, but is the fetch then fetching from some result
set written to the temp area?

Thanks,

Steve
and we said...
Maybe its fetching from temp -- maybe not.

Lets say you have tables t1, t2, t3.  t1.x = t2.y, t2.z = t3.a
are the join conditions.   Order by t1.x is the order by.  There
are indexes on t1(x), t2(y) and t3(a).

That query will most like use no temporary space.  It might
read t1 ordered by the index on t1(x), it'll then read t2 by the
index on t2(y) and then t3 by the index on t3(a).  You'll get
the very first record almost immediately.  No temp space
required.

On the other hand, lets say the index on t1(x) did not exist.
It might decide to SORT t1 and the columns you select from it
into temp and then do the index reads into t2 and t3 -- the
amount of temp space required = the number of columns you
selected from T1 plus space for a temporary index on X.

On the other hand, lets say again the index on t1(x) did not
exist.  It might decide to join t1 to t2, t2 to t3 and then sort
that result.  The amount of temp would be the size of the entire
select list plus some temporary index.

Then again, it might decide to sort merge join all of them.

Then again, it might decide to hash join them.

And so on.  There is no truely predicative way to estimate the
temp space an arbitary query will need -- only if you gave a
specific QUERY PLAN could you predict the amount needed -- and
then thats a function of your sort_area_size and such as well
(whether it will even allocate temp space)...
August 20, 2000 Ashwin -- Thanks for the question regarding "How to load the XXXYY.msg files (error codes and messages) into the database", version Oracle 7.3
You Asked
 Hi Tom,

   I have created a table to transfer the Oracle Help like
ORA, DBA, FRM errors to  this table now I have all these
errors in oracle help now how do i transfer these into text and
transfer to the table I have created. At Present I have created
a form and saving these records but it is very hard to type all
the 20000 records one by one into the form and save it to the
table. If U can tell me How do I transfer these type of Error
messages into the table it will be helpful.

  The ORA errors are in the Form like Oracle help file ie. it is

the oracle errors help file so i would like to export only
the ora errors to a table that i have created in my database.

 Regards
 ash.
and we said...
Here is what I would do:

o load the msg file into a table, for example to get the US
version of the ORA-XXXXX messages, i would load
$ORACLE_HOME/rdbms/mesg/oraus.msg into a table virtually "as is"
(just the relevant lines)

o I would use a stored procedure to massage the data and make it
"relational".

For example, I would have 2 tables:

create TABLE temp_table
(
  seqno      number primary key ,
  text       varchar2(4000)
)
/

create table msg_table
( err_code number,
  err_type varchar2(3),
  err_msg  varchar2(255),
  err_text varchar2(4000),
  primary key(err_code,err_type)
)
/

I would load the TEMP_TABLE using:

LOAD DATA
REPLACE
INTO TABLE temp_table
when (1:2) = '//'
(
  text       position(1:4096) ,
  seqno      recnum
)
INTO TABLE temp_table
when (1:1) <> '/'
(
  text       position(1:4096) ,
  seqno      recnum
)

with a sqlldr command line like:

$ sqlldr userid=u/p control=load.ctl
data=$ORACLE_HOME/rdbms/mesg/oraus.msg

(thats on one line of course)...

And then using a stored procedure like:

create or replace procedure move_data( p_err_type in varchar2 )
as
    l_last_err_code number;
    l_last_err_msg  varchar2(255);
    l_last_err_text varchar2(4000);
    l_n             number;
    l_sep           char(1);
begin
    for x in ( select * from temp_table order by seqno )
    loop
        if ( x.text not like '//%' ) then
        begin
            if ( l_last_err_code is NOT NULL ) then
                insert into msg_table
                ( err_code, err_type, err_msg, err_text )
                values
                ( l_last_err_code, p_err_type, l_last_err_msg,
                  l_last_err_text );
            end if;

            l_n := instr( x.text, ',' );
            l_last_err_code := substr( x.text, 1, l_n-1 );
            x.text := substr( x.text, l_n+1 );

            l_n := instr( x.text, ',' );
            l_last_err_msg := substr( x.text, l_n+1 );

            l_last_err_text := NULL;
            l_sep := NULL;
        exception
            when others then
                dbms_output.put_line( x.text );
                raise;
        end;
        else
            l_last_err_text := l_last_err_text || l_sep ||
                            x.text;
            l_sep := chr(10);
        end if;
    end loop;

    if ( l_last_err_code is NOT NULL ) then
        insert into msg_table
        ( err_code, err_type, err_msg, err_text )
        values
        ( l_last_err_code, p_err_type, l_last_err_msg,
          l_last_err_text );
    end if;

end;
/

I can format the data correctly by executing:

SQL> exec move_data( 'ORA' );

Now, I can:

ops$tkyte@8i> select * from
  2  msg_table where err_code = 54 and err_type= 'ORA';

  ERR_CODE ERR
---------- ---
ERR_MSG
-----------------------------------------------------------------
-----------------------------------
ERR_TEXT
-----------------------------------------------------------------
-----------------------------------
        54 ORA
 "resource busy and acquire with NOWAIT specified"
// *Cause:  Resource interested is busy.
// *Action: Retry if necessary.

which is the same answer I get with

ops$tkyte@8i> !oerr ora 54
00054, 00000, "resource busy and acquire with NOWAIT specified"
// *Cause:  Resource interested is busy.
// *Action: Retry if necessary.
Review & Followup
Rating: 5
* * * * * January 12, 2003
Reviewer: jonathan
what should i say? - amazing idea, great help and follow-up
i'm using the code now.

Rating: 5
January 12, 2003
Reviewer: A reader
Tom --
I linked to the the above link, and did the load etc.
-- and it flies! I didn't really understand your formating
procedure, nor the reason for the massive error count, but
I continued on -- w/great results. Perfect. You ought to
copywrite that procedure.

August 21, 2000 Tet Cheng -- Thanks for the question regarding "Cluster Index", version 7.2/7.3 and 8
You Asked
Hi Tom,

What is cluster index and how to you use them?

Tet Cheng
and we said...
First, you must understand what a cluster is in Oracle.

A cluster is simply a method for storing more then 1 table on
the same block.  Normally -- a block contains data for exactly 1
table. In a cluster -- you have data from many tables sharing
the same block.

For example -- if you join the data from EMP and DEPT by DEPTNO
frequently -- you might consider clustering this data by DEPTNO.
 In that fashion all of the rows from EMP for deptno=10 and the
row in DEPT for deptno=10 will reside on the same exact block
(one IO to get all of the data instead of some IO's to EMP and
DEPT).

In order to organize data in such an object, we create a cluster
KEY -- deptno in our above example.  We must index this cluster
key.  This index on deptno in the cluster is called a CLUSTER
INDEX and is used to locate the blocks that contain data about
deptno=10 (for example).

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c08schem.htm#12872
for more details.
August 21, 2000 Taufik SN -- Thanks for the question regarding "export table more than 2 GB", version version 8.0.5
You Asked
Hi Tom,
I saw on the archive about ex/imp exceeding file size 2GB almost
on database or a file. But how if the object is a table?
Thanks a lot Tom
and we said...
Regardless of whether it is the entire database that causes the
DMP to exceed 2 gig or a single table -- the method described in
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:122612348063
works just fine.
August 21, 2000 raghu babu -- Thanks for the question regarding "configure WebDB(HP Unix) with Microsoft IIS 3.0", version version 2.1
You Asked
I have installed Oracle 8i (8.1.5) and WebDB(2.1) on HP
Unix(11.X)
With this configuration I am able to work without any porblems.
Now,
I want to configure the Webdb(on Unix) with Microsoft IIS(on
NT).
Please let me know the solutions/steps that how to configure
this ?

Regards.

Raghu.
and we said...
Well, webdb is made of 2 components

o the PLSQL code that is WebDB.  This is stored in the database.
 This is easily installed on your HP/UX database.

o the lightweight listener that is used by default to run WebDB
stored procedures.  This includes a cartridge for use with
OAS4.x and a cgi-bin executable for use with other webservers.

So, you would do an install of webdb on the NT box and this will
give you a cartridge you can use with OAS4 and OAS4 can be used
with MSIIS -- or you can configure the cgi-bin version of webdb
to run with MSIIS.

The next release of WebDB (Oracle Portal) will provide support
for Apache in the form of an Apache Module.
August 21, 2000 Sumeru -- Thanks for the question regarding "Quering a table -- getting the N'th row", version 7.3
You Asked
My Table contains 20 rows.
How do I select the 12th row?
and we said...
In Oracle7.3 as you have, the following will work:

select *
  from ( select a.*, rownum rnum
           from ( YOUR_QUERY ) a
          where rownum <= :MAX_ROWS )
 where rnum >= :MIN_ROW_TO_FETCH
/

that'll work as long as your_query does not have an order by
in it..

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:286015972532
for some other ideas
August 21, 2000 sivaram -- Thanks for the question regarding "DBLink -- can you have one from 7.2 to 8 or 8i?", version 7.2.2
You Asked
Can I have dblink between 7.2.2 to 8 or 8i.
and we said...
Yes, you can have a database link from 7.2.2 to 8 or 8i.   I no
longer have a 7.2 instance to test with but 7.1.6 and 7.3.4 both
work fine.
August 21, 2000 Damaraju -- Thanks for the question regarding "SQL -- how to assign rownum after a sort.", version 8.1.5
You Asked
I have a table say EMP with filed EMPCODE,NAME,DEPT

I want to write a Select statment like this

Select rownum,empcode, name,dept from EMP order by NAME. The
result I should get is Rownum should start from 1,2 , 3 ... and
the records should be sorted by NAME field.

Will u please help me in this regard
and we said...
select rownum, a.*
  from ( select empcode, name, dept
           from emp
          order by name ) A
/

will do it.  You must assign rownum AFTER the sort. This works
in Oracle8i release 8.1 and up only (order by in a subquery)
August 21, 2000 Bruno -- Thanks for the question regarding "Selecting last 2 rows when you don't know how many are being selected.", version 7.3.4
You Asked
Tom -
  I have looked at all of your comments regarding row selections, but can't find
one that cures my problem ?

Here is my query -

select    person_id,
    employer_name
from     employment
where     upper(employer_name) not like  upper('%UNEMPLOYED%')
and    person_id in
    (select person_id
     from     employment
     where     occupation_end_date is not null
     group     by person_id having count(*) > 2)
order

Here is the result -

PERSON_ID EMPLOYER_NAME
--------- --------------------
    30975 Waiter Street Hotel
    30975 Bus Person
    30975 Clerk

Here is the question -
    I don't know how many rows I am fetching, but I only want the last 2.  Is
there an easy way to do this ?
and we said...
Ok, if you have data such as:

ops$tkyte@8i> select * from employment;

PERSON_ID EMPLOYER_N OCCUPATIO
---------- ---------- ---------
         1 a          13-MAY-00
         1 b          22-JUN-00
         1 c          01-AUG-00
         2 a          13-MAY-00
         2 b          22-JUN-00
         2 c          01-AUG-00

6 rows selected.

Then, the following query will do it for you:

ops$tkyte@8i> select person_id,
  2   employer_name,
  3   occupation_end_date,
  4   rowid
  5  from  employment
  6  where  upper(employer_name) not like  upper('%UNEMPLOYED%')
  7  and person_id in
  8   (select  person_id
  9    from     employment
10    where  occupation_end_date is not null
11    group  by person_id having count(*) > 2)
12   and 2 <= ( select count(*) from employment A
13               where a.person_id = employment.person_id
14                 and a.occupation_end_date <=
                               employment.occupation_end_date )
15  order by occupation_end_date
16  /

PERSON_ID EMPLOYER_N OCCUPATIO ROWID
---------- ---------- --------- ------------------
         1 b          22-JUN-00 AAAWGIAADAAAAjKAAB
         2 b          22-JUN-00 AAAWGIAADAAAAjKAAE
         1 c          01-AUG-00 AAAWGIAADAAAAjKAAC
         2 c          01-AUG-00 AAAWGIAADAAAAjKAAF
August 21, 2000 Howie -- Thanks for the question regarding "Export , Rollback Segment", version 7.3.4.5.0
You Asked
1. What is the difference between cumulative & incremental
export of a database ?

2. What is wrap & shrink in case of rollback segments ?

3. What is the sequence of ONLINE REDO LOG, ROLLBACK segment &
datafile writes while processing one transaction. I mean to ask
in what order/fashion entries goes to these structures.

I have read concept manual but unable to understand these
concepts properly, please explain in detail.

Thanks In advance

Howie
and we said...
1) an incremental only exports tables that have been modified
since the last incremental, cummulative or full export.  A
cumulative on the other hand exports all tables since the last
cumulative or full export -- it ignores any incrementals that
took place in between.  That allows you to discard all of the
incrementals since that last cumulative or full export.

2) wrap is what it sounds like. rollback segments are used in a
circular fashion.  When we get to the end of a rollback segment
we will either:

  a) extend it if we cannot reuse the "head" of the rollback
segment because its still being used.
  b) fail because we cannot extend it and we needed to (lack of
space, max extents hit, etc)
  c) WRAP back to the head and start reusing space since no one
else is.

shrink is what it sounds like too.  We will occasionally shrink
a RBS back down to its optimal size if we extended it past that
for some long running transaction - it reclaims the space and
makes it available for other things.

3) The are all intermingled and constantly happening.  We'll
write to datafiles -- generating rollback -- both of which are
simultaneously logged.  It would be safe to safe that REDO would
in general be PHYSICALLY written to prior to data and rollback.
There is no way to judge which gets physically written first --
RBS or data as they are just managed in a big buffer.  There is
no simple "linear" explaination of it.
August 21, 2000 indraneel -- Thanks for the question regarding "Query to retrieve specific set of duplicate values", version 8.0.5.0.0
You Asked
I would like to retrieve a specific set of duplicate
values from one field in a table.

For eg:In table T1 with field F1 if i have the
following entries:
i.e in table T1 under field F1:

 1
 1
 1
 2
 2
 3
 3
 3

I would like to retieve only those set of values which
have an entry 3 times.
i.e desired result should be:

 1
 1
 1
 3
 3
 3

Thanks in advance
Indraneel
and we said...
ops$tkyte@8.0> select * from T;

        F1
----------
         1
         1
         1
         2
         2
         3
         3
         3

8 rows selected.

ops$tkyte@8.0> select *
  2    from T t1
  3   where 3 = ( select count(*)
  4                 from T t2
  5                where t2.f1 = t1.f1 )
  6  /

        F1
----------
         1
         1
         1
         3
         3
         3

6 rows selected.

or...

ops$tkyte@8.0> select t.f1
  2    from t, ( select f1, count(*) cnt
  3                from t
  4               group by f1 ) A
  5   where a.f1 = t.f1
  6     and a.cnt = 3
  7  /

        F1
----------
         1
         1
         1
         3
         3
         3

6 rows selected.
August 21, 2000 Leon -- Thanks for the question regarding "Redo Log and Control files: Software mirror and hardware mirror", version 7.3
You Asked
Hi Tom,

Some Oracle books mention the concept of SOFTWARE
MIRROR and HARDWARE MIRROR when multiplexing redo
log files and control files.

What do these concepts exactly mean? Can you give me
more detail explanation and some examples?

Thanks,

Leon,
and we said...
Oracle does software based mirroring of its online redo logs
(you create multiple members in the same group -- we write to
them simultaneously and keep them in sync).  We do this via
software (LGWR does it).

There are hardware oriented solutions as well (which are really
software driven under the covers ;).   You can by raid arrays
that support mirroring not at the OS level but at the device
level.  You issue one write -- it multiplexes the writes to many
devices.  This is outside the control of the OS itself -- the
hardware just does it.

We recommend for redo and control files that you allow us to
mirror them if at all possible.
August 21, 2000 Jin -- Thanks for the question regarding "TKPROF ", version Oracle8.0.4
You Asked
Hi, Tom:

I want to use Sql trace facility and TKPROF to monitor the
performance of the Oracle server.
After I enabled the SQL trace and run issue the command I want
to analyze, I can not locate the trace file I have created.
Could you tell where and how to locate the trace file? How to
run the TPPROF program?

Thank you very much.

JIN
and we said...
To find out where the trace files are going, inspect your
USER_DUMP_DESTINATION init.ora parameter.  That tells us where
to put them.  They will be in that directory.

For info on running and interpreting the output of tkprof, see:
http://technet.oracle.com/doc/server.804/a58246/strace.htm#1018
...
Review & Followup
Rating: 4
thanks December 28, 2001
Reviewer: K. Sadeghi from Germany
thanks one more time.

August 21, 2000 subhakar -- Thanks for the question regarding "Special Characters -- in a create user command", version 8.1.6
You Asked
How can I pass special characters into a procedure in a varchar2
variable? It comes out with an error "ORA-911 Invalid character"

For Example:

I have a procedure "create_user" to create the user and store
the username and password of this user in a separate table. This
procedure takes two input variables (username and password). I
need to pass special characters into the password variable. So,
when I pass these special characters it comes out with this
ORA-911 error. Am I clear???

Thanks in advance....
Subhakar
and we said...
An Oracle password has the following rules:

o Passwords must be from 1 to 30 characters long.
o Passwords cannot contain quotation marks.
o Passwords are not case sensitive.
o A Password must begin with an alphabetic character.
o Passwords can contain only alphanumeric characters and the
  underscore (_), dollar sign ($), and pound sign (#). Oracle
  strongly discourages you from using $ and #..
o A Password cannot be an Oracle reserved word (eg: SELECT).

Passwords cannot have "special" characters -- they follow the
same rules all Identifiers do in the database.  You are passing
the varchar2 in with the "special characters" -- that part is
working just fine.  It is the actual create user command that is
failing due to an invalid character in the password OR because
you have placed a semi colon at the end of the create user
command.

Here is an example of the types of errors you can expect with
invalid passwords:

tkyte@ORACLE8I> create or replace
  procedure create_user( p_uname in varchar2, p_pw in varchar2 )
  2  as
  3  begin
  4      execute immediate
  5      'create user ' || p_uname || ' identified by ' || p_pw;
  6  end;
  7  /

Procedure created.

tkyte@ORACLE8I>
tkyte@ORACLE8I> exec create_user( 'test', '1wrong' );
BEGIN create_user( 'test', '1wrong' ); END;

*
ERROR at line 1:
ORA-00988: missing or invalid password(s)
ORA-06512: at "TKYTE.CREATE_USER", line 4
ORA-06512: at line 1

tkyte@ORACLE8I> exec create_user( 'test', 'wrong;again' );
BEGIN create_user( 'test', 'wrong;again' ); END;

*
ERROR at line 1:
ORA-00911: invalid character
ORA-06512: at "TKYTE.CREATE_USER", line 4
ORA-06512: at line 1

tkyte@ORACLE8I> exec create_user( 'test',
'this_is_really_wrong!' );
BEGIN create_user( 'test', 'this_is_really_wrong!' ); END;

*
ERROR at line 1:
ORA-00922: missing or invalid option
ORA-06512: at "TKYTE.CREATE_USER", line 4
ORA-06512: at line 1

The only solution is to use a valid Oracle password in the
create user command.
August 21, 2000 Sam -- Thanks for the question regarding "Invoking htp packages", version 8.1.6 Rel 2
You Asked
Hi tom,

I have an oracle database 8.1.6 Rel 2 running on a solaris
platform.
I have troubles in compiling procedures that has htp/htf calls.

As an experiment, I ran the following create procedure

create or replace procedure helloworld is
begin
   htp.htmlopen;
   htp.title('hello world');
   htp.bodyOpen('BGCOLOR=#FFFFF');
   htp.print('Hello World');
   htp.bodyClose;
   htp.htmlClose;
END;

as a user with the connect and resouce privileges. After
compiling I'm getting the
following errors:
SQL> @helloworld

Warning: Procedure created with compilation errors.

Errors for PROCEDURE HELLOWORLD:

LINE/COL ERROR
--------
-----------------------------------------------------------------

3/4      PLS-00201: identifier 'HTP.HTMLOPEN' must be declared
3/4      PL/SQL: Statement ignored
4/4      PLS-00201: identifier 'HTP.TITLE' must be declared
4/4      PL/SQL: Statement ignored
5/4      PLS-00201: identifier 'HTP.BODYOPEN' must be declared
5/4      PL/SQL: Statement ignored
6/4      PLS-00201: identifier 'HTP.PRINT' must be declared
6/4      PL/SQL: Statement ignored
7/4      PLS-00201: identifier 'HTP.BODYCLOSE' must be declared
7/4      PL/SQL: Statement ignored
8/4      PLS-00201: identifier 'HTP.HTMLCLOSE' must be declared

LINE/COL ERROR
--------
-----------------------------------------------------------------

8/4      PL/SQL: Statement ignored

My question here is that do I have to execute any .sql script to
create these packages.
On that case what should I be executing?

I was under the impression the pubuild, and catproc would create
these packages, when they
were to get invoked initially after the creation of the
database.

Could you pl. advice me on what to do?

Thanx,
Sam
and we said...
These packages are only installed with OAS, WebDB or iAS.  They
are part of the webserver toolkit right now (8.1.7 will change
that).

So, for now, you need one of OAS or WebDB to get these packages
(and since only OAS and WebDB can make use of the output from
these packages -- if you don't have them, you don't have any
need for htp/htf)...
August 22, 2000 wallacel -- Thanks for the question regarding "doing a hit counter on the web.", version 8.1.6
You Asked
Tom:

I have a project in which user keep updateing a table.
let's say we want to know how many hits our home page.

let's say table A(a int);
at the begining we have 0,
each time a user hits the homepage, we update table to a+1;
I was wondering how maby concurrent hits we can handle.
so I write a test program like this:

for i in 1..100000
update A set a:=a+1;

it takes me 50 second to finish it, does that mean
I need 50 second to handle 100,000 user who concurrent
hits the table?

(My real situation maybe not the same, but my request is
almost like this: if every process keep updating a table,
how many concurrent processes our server can handle by how long
time. )

Thanks,
and we said...
Don't use a table -- In your example at most you will have 1
concurrent hit!!!!  If you update a row, it will lock it and no
one else can update it until you commit.

Your test above is somewhat flawed in general though as a test
to measure concurrency.  You are trying to measure a metric that
will be done in parallel (lots of clients hitting "go") using a
serial (loop) process.  You would need to emulate the number of
concurrent clients you expected to hit to see how long it would
take -- not count how long it takes serially.... anyway...

The way I do this is to use one of two methods:

o for a simple counter simply:

  create sequence my_seq cache 100;

and then pin the sequence, see:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:263215360334
for details on doing that.  Then my hit counter becomes:

   select my_seq.nextval into :HIT_COUNT from dual;

thats it -- very fast, very concurrent.  I use cache 100
understanding that when I shutdown -- I might lose upto 100
entries (i'll inflate my hit count by upto 100).  At that point
however, I don't really care because if adding 100 hits to my
count materially affects my counts -- my page isn't really
getting any traffic anyway.....

o use the logging method.  I would:

  insert into log ( .... ) values
  ( remote_addr, http_user_agent, http_referer,
    sysdate, <other details> );

where remote_addr and http_user_agent were gotten from the
cgi-environment.  log is a totally unindexed table (maybe an
index on the sysdate column).  the insert is very fast, it is
very concurrent (create the log with freelists=20 or so to make
it even more so).  To get the hit count -- you count rows in
here.  You can use a materialized view to update the hit count
every N minutes or so in the background.  That and you get lots
more info about how is using your site (browser wise, where they
come from and so on)
August 22, 2000 N -- Thanks for the question regarding "Oracle office Application Program interface", version 8/8i
You Asked
Oracle 7 server has a feature oracle office API which can be
used to send and receive mails. If i want to use that feature
(sending and receiving mails) how do i do it in oracle 8/8i.
and we said...
Oracle Office (now Oracle Internet Messaging) still exists
however its an entire email server in the database.  Its not a
lightweight solution -- if you just want to send an email.  Its
designed to be the email server for 10's of thousands of
concurrent users.

In 8.0 and 8.1, there are many ways to send email from the
database.  If I had to support both -- an EXTERNAL procedure
would probably be the best approach since both 8.0 and 8i
support extprocs.  In this fashion, I can write a C subroutine
to send email and then call this C subroutine from PLSQL. See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adg11rtn.htm#1656
for info on that feature

In 8i, I would use java or in 8.1.6 I might use UTL_SMTP.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:255615160805
for more info on that.
August 22, 2000 Cyndi -- Thanks for the question regarding "Client Certificate -- using with OAS", version OAS 4.0
You Asked
We are incorporating PKI based security within our appl. Please
help by telling us how to do the following :

1. request the client certificate from OAS
2. receive the client certificate
3. pass the client certficate to the application

Thank you.
and we said...
1) see
http://www.olab.com/doc/books/admin/appconf.htm#1017174
for info on that.  You configure that at the OAS
level.

2) OAS processes the certificate for you.

3) this is not possible.  It violates the very premise of the
PKI infrastructure.  3'rd parties simply cannot pass the
certificate along to someone else.  If they could -- then PKI
would be useless as an Identification mechanism.  If I could
simply "pass" your certificate along to someone else -- and
pretend to be you (man in the middle) I would have subverted the
entire scheme....

Now, what is possible is for you to write a C Cartridge in the
middle tier that gets the certificate, uses the SSLeay public
domain libs to decode the certificate (to find out who is on the
other end) and then tell some other application who it should
run as.  The application would have to be coded to "trust" you
(in the middle).  OAS gets the certificate, gives it to you, you
decode it, and you tell the application "please pretend its 'so
and so'".

For example, I've written a cartridge that works very much like
the PLSQL cartridge does.  We added support for a client for
certificate based authentication.  The cartridge gets the client
cert, extracts the common name from it, and uses that name to
log into the database using the equivalent of OCI's ntier
authentication (see:
http://osi.oracle.com/~tkyte/Misc/OCI-N-Tier.html
for details on N-tier).

So, for example, in my C routine that logged into the database,
I have code such as:

if ( ( userid == NULL ) && ( password == NULL ) )
{
   debugf( ctx, "Attempting to login using certificate" );
   WRB_getClientCert( ctx->WRBCtx, &cert_buffer, &cert_len );
   debugf( ctx, "certification length is %d bytes", cert_len );

   userid = ParseCert( ctx, cert_buffer, cert_len );
   password = get_hashed_password( ctx, userid );

   debugf( ctx, "userid = '%s', password = '%s'",
                userid, password );
}

It uses the WRB_getClientCert call to retrieve the certificate.
ParseCert is simply:

static char * ParseCert(myctx * ctx, char* pCertData,
                         int pCertDataLen)
{
BIO     *pCertBio = NULL;
X509    *pParsedCert = NULL;
BUF_MEM mb;
char   * cp;

  pCertBio=BIO_new(BIO_s_mem());
  mb.data=pCertData;
  mb.length= pCertDataLen;
  BIO_set_mem_buf(pCertBio,&mb,BIO_NOCLOSE);

  pParsedCert=d2i_X509_bio(pCertBio,NULL);

  cp = strstr( pParsedCert->name, "/CN=" );

  if ( !cp  )
  {
   debugf( ctx, "unable to find /CN=" );
   return NULL;
  }

  cp += 4;
  strtok( cp, "/" );
  debugf( ctx ,
      "parsed certificate, /CN= part after adj, is '%s'", cp );

  cp = heap_strdup( cp );

  X509_free( pParsedCert );
  if (pCertBio !=NULL) BIO_free(pCertBio);

  debugf( ctx ,"parsed certificate, returning '%s'", cp );
  return cp;
}

That uses the SSLeahy routines to decode the certificate and
extract the common name.  We had implemented a hashing algorithm
based on the common name+"magic salt" to generate passwords for
all users so I could now log into the database as them (this was
in 8.0 so I didn't have nTier authentication yet).  In 8i, i
would use nTier authentication and skip the hashing of a
password and just log in on their behalf....

Hope this helps.
Review & Followup
Rating: 2
Use of PKI in Oracle Forms applications October 22, 2001
Reviewer: Todd Langille from New Hampshire, USA
When I searched for digital signatures, I did not get any hits, so I tried PKI,
and got this hit.  This answer indicates that there is some level of support for
PKI in OAS, but I think I need a higher level response before we get into the
details.  How do I submit a question of my own ?  I can't find a link to a
"Submit Question" page.

August 22, 2000 Tamas -- Thanks for the question regarding "PL/SQL server pages", version Oracle 8iR2 or R3
You Asked
Hi Tom,

I heard that Oracle 8iR2 or R3 handles PL/SQL server pages.
Could you point me to some technical paper on this subject?

TIA,

Tamas Szecsy
Geometria GIS Systems House Ltd.
and we said...
Thats Oracle8i release 2 (8.1.6).

See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adgweb.htm#1002508
for the details.
August 22, 2000 Gajanan -- Thanks for the question regarding "Migrating FOXPRO database to Oracle", version oracle8.1.5
You Asked
Hi tom
Can you please tell me how to migrate FOXPRO database to
Oracle8.1.5 or oracle8 on NT4.0.

Thanks and Regards
Gajanan
and we said...
I probably don't know all of the ways but I guess I would use
ODBC to open a cursor on foxpro and then insert into Oracle.

See
http://technet.oracle.com/tech/migration/toolkits/files/foxpro/intro.htm
for more info as well.
August 22, 2000 Sybrand -- Thanks for the question regarding "Maintaining count of detail records online, redudantly", version 7.3.4.5 for NT
You Asked
Hi Tom,

I'm struggling with the following generic problem. I will
transpose it to scott terminology, in order to avoid to explain
dutch table and column names.

Suppose we have a table emp, a table projects, and a junction
table, maintaining the n:m relation, called emp_projects (or
whatever). Between the emp and emp_projects table there is a
foreign key on delete cascade, between projects and emp_projects
a foreign key on delete restrict. (Previously the constraints
were maintained by triggers, we are converting to 'real'
constraints now).
For some mysterious reason the designers included a count of
projects in the employee table (so this is really redundant) and
a count of employees in the projects table (again redundant).
The previously used triggers were maintaining this online.
Using constraints in combination with stripped triggers, when I
delete a record from emp, I will delete the record in
emp_projects automatically, which should result in the projects
table to be updated. You can easily guess what happens: ora-4091
mutating table. I know about the generic solution, however for
some reason this just doesn't work, probably because when you
update the projects table the relationship with the emp_projects
table is checked and the table found to be mutating. I know I
could avert this by upgrading to Oracle 8 and make my
constraints deferred, however this upgrade probably will happen
somewhere near the end of the year.
Please help!!!

Thanks in advance,

Sybrand Bakker, Oracle DBA
and we said...
I believe we can do this with triggers easily enough.  For the
case where we update the association table from emp to projects
-- it is straightforward enough.  It is when we delete from the
emp or projects table we have an issue -- thats when we get the
mutating table error.  In that case -- we'll just catch that
error an ignore it.  We'll use triggers on the parent tables to
process those modifications.

Here is the example:

tkyte@ORA734.US.ORACLE.COM> create table emp
  2  ( empno int primary key,
  3    proj_cnt int
  4  );

Table created.

tkyte@ORA734.US.ORACLE.COM> create table projects
  2  ( projid int primary key,
  3    emp_cnt int
  4  );

Table created.

tkyte@ORA734.US.ORACLE.COM> create table emp_projects
  2  ( empno int,
  3    projid int,
  4    primary key(empno,projid),
  5    foreign key(empno)
  6       references emp(empno) on delete cascade,
  7    foreign key(projid)
  8       references projects(projid) on delete cascade,
  9    constraint reverse_key unique(projid,empno)
 10  );

Table created.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> create or replace package state_pkg
  2  as
  3      type myArray is table of number
  4         index by binary_integer;
  5
  5      modEmpnos  myArray;
  6      modProjids myArray;
  7      empty      myArray;
  8
  8      do_not_recurse boolean default FALSE;
  9
  9      procedure init;
 10      procedure add_empno( p_empno in int );
 11      procedure add_projid( p_projid in int );
 12      procedure do_updates;
 13  end;
 14  /

Package created.

tkyte@ORA734.US.ORACLE.COM> create or replace package body
state_pkg
  2  as
  3      procedure init
  4      is
  5      begin
  6          if ( not DO_NOT_RECURSE ) then
  7              modEmpnos := empty;
  8              modProjids := empty;
  9          end if;
 10      end;
 11
 11      procedure internal_add( p_id in int,
 12                              p_tbl in out myArray )
 13      is
 14          l_found boolean := false;
 15      begin
 16          for i in 1 .. p_tbl.count loop
 17              l_found := true;
 18              exit when ( p_tbl(i) = p_id );
 19              l_found := false;
 20          end loop;
 21          if ( not l_found ) then
 22              p_tbl( p_tbl.count+1 ) := p_id;
 23          end if;
 24      end;
 25
 25      procedure add_empno( p_empno in int )
 26      is
 27      begin
 28          internal_add( p_empno, modEmpnos );
 29      end;
 30
 30      procedure add_projid( p_projid in int )
 31      is
 32      begin
 33          internal_add( p_projid, modProjids );
 34      end;
 35
 35      procedure do_updates
 36      is
 37          mutating  exception;
 38          pragma exception_init( mutating, -4091 );
 39      begin
 40          do_not_recurse := TRUE;
 41
 41          for i in 1..modEmpnos.count loop
 42              update emp
 43                 set proj_cnt =
 44                      ( select count(*)
 45                          from emp_projects
 46                         where empno = modEmpnos(i) )
 47               where empno = modEmpnos(i);
 48          end loop;
 49          for i in 1..modProjids.count loop
 50              update projects
 51                 set emp_cnt =
 52                      ( select count(*)
 53                          from emp_projects
 54                         where projid = modProjids(i) )
 55               where projid = modProjids(i);
 56          end loop;
 57
 57          modEmpnos := empty;
 58          modProjids := empty;
 59          do_not_recurse := FALSE;
 60
 60      exception
 61          when mutating then
 62              do_not_recurse := FALSE;
 63              -- this happens with the ON DELETE
 64              -- cascade.  We'll do do updates in
 65              -- triggers on the parent tables instead
 66          when others then
 67              do_not_recurse := FALSE;
 68              raise;
 69      end;
 70  end;
 71  /

Package body created.

now, here come the triggers.  The before insert or update or
delete on emp_projects will reset the package state above (empty
the tables and such) UNLESS we are being fired recursively

tkyte@ORA734.US.ORACLE.COM> create or replace trigger
emp_projects_biud
  2  before insert or update or delete on emp_projects
  3  begin
  4      state_pkg.init;
  5  end;
  6  /

Trigger created.

This trigger captures the row level changes -- it remembers
the projects and empno we need to go back and update the counts
for...

tkyte@ORA734.US.ORACLE.COM> create or replace trigger
emp_projects_aiud_fer
  2  after insert or update or delete on emp_projects
  3  for each row
  4  begin
  5      if ( NOT state_pkg.do_not_recurse )
  6      then
  7          if ( inserting or updating ) then
  8              state_pkg.add_empno(:new.empno);
  9              state_pkg.add_projid(:new.projid);
 10          end if;
 11          if ( updating or deleting ) then
 12              state_pkg.add_empno(:old.empno);
 13              state_pkg.add_projid(:old.projid);
 14          end if;
 15      end if;
 16  end;
 17  /

Trigger created.

Now, we need to process these updates after any insert or
update or deletes to the association table...

tkyte@ORA734.US.ORACLE.COM> create or replace trigger
emp_projects_aiud
  2  after insert or update or delete on emp_projects
  3  begin
  4      state_pkg.do_updates;
  5  end;
  6  /

Trigger created.

And after deletes on the parent table (mutating table would
have prevented it from working after the above trigger...

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> create or replace trigger emp_ad
  2  after delete on emp
  3  begin
  4      state_pkg.do_updates;
  5  end;
  6  /

Trigger created.

tkyte@ORA734.US.ORACLE.COM> create or replace trigger
projects_ad
  2  after delete on projects
  3  begin
  4      state_pkg.do_updates;
  5  end;
  6  /

Trigger created.

the following just verifies it all works.... (and it does)

tkyte@ORA734.US.ORACLE.COM> insert into emp
  2  select rownum, 0 from all_users ;

10 rows created.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> insert into projects
  2  select -rownum, 0 from all_users;

10 rows created.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> -- give everone a single project in
a
tkyte@ORA734.US.ORACLE.COM> -- mass insert
tkyte@ORA734.US.ORACLE.COM> insert into emp_projects
  2  select rownum, -rownum from all_users ;

10 rows created.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> select * from emp;

     EMPNO   PROJ_CNT
---------- ----------
         1          1
         2          1
         3          1
         4          1
         5          1
         6          1
         7          1
         8          1
         9          1
        10          1

10 rows selected.

tkyte@ORA734.US.ORACLE.COM> select * from projects;

    PROJID    EMP_CNT
---------- ----------
        -1          1
        -2          1
        -3          1
        -4          1
        -5          1
        -6          1
        -7          1
        -8          1
        -9          1
       -10          1

10 rows selected.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> -- give everyone N-1 more projects,
N= #rows
tkyte@ORA734.US.ORACLE.COM> -- in all_users...
tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> begin
  2      for x in ( select * from emp ) loop
  3          for y in ( select * from projects ) loop
  4              if ( x.empno != -y.projid )
  5              then
  6                  insert into emp_projects
  7                  ( empno, projid )
  8                  values
  9                  ( x.empno, y.projid );
 10              end if;
 11          end loop;
 12      end loop;
 13  end;
 14  /

PL/SQL procedure successfully completed.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> select * from emp;

     EMPNO   PROJ_CNT
---------- ----------
         1         10
         2         10
         3         10
         4         10
         5         10
         6         10
         7         10
         8         10
         9         10
        10         10

10 rows selected.

tkyte@ORA734.US.ORACLE.COM> select * from projects;

    PROJID    EMP_CNT
---------- ----------
        -1         10
        -2         10
        -3         10
        -4         10
        -5         10
        -6         10
        -7         10
        -8         10
        -9         10
       -10         10

10 rows selected.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> -- do a mass update
tkyte@ORA734.US.ORACLE.COM> update emp_projects
  2    set projid = decode( projid, -10, -9, -9, -10 )
  3   where projid in ( -9, -10 )
  4  /

20 rows updated.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> select * from emp;

     EMPNO   PROJ_CNT
---------- ----------
         1         10
         2         10
         3         10
         4         10
         5         10
         6         10
         7         10
         8         10
         9         10
        10         10

10 rows selected.

tkyte@ORA734.US.ORACLE.COM> select * from projects;

    PROJID    EMP_CNT
---------- ----------
        -1         10
        -2         10
        -3         10
        -4         10
        -5         10
        -6         10
        -7         10
        -8         10
        -9         10
       -10         10

10 rows selected.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> -- do some deletes...
tkyte@ORA734.US.ORACLE.COM> delete from emp_projects where
projid < -5;

50 rows deleted.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> select * from emp;

     EMPNO   PROJ_CNT
---------- ----------
         1          5
         2          5
         3          5
         4          5
         5          5
         6          5
         7          5
         8          5
         9          5
        10          5

10 rows selected.

tkyte@ORA734.US.ORACLE.COM> select * from projects;

    PROJID    EMP_CNT
---------- ----------
        -1         10
        -2         10
        -3         10
        -4         10
        -5         10
        -6          0
        -7          0
        -8          0
        -9          0
       -10          0

10 rows selected.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> -- do some more updates..
tkyte@ORA734.US.ORACLE.COM> update emp_projects
  2    set projid = projid - 5
  3  /

50 rows updated.

tkyte@ORA734.US.ORACLE.COM> select * from emp;

     EMPNO   PROJ_CNT
---------- ----------
         1          5
         2          5
         3          5
         4          5
         5          5
         6          5
         7          5
         8          5
         9          5
        10          5

10 rows selected.

tkyte@ORA734.US.ORACLE.COM> select * from projects;

    PROJID    EMP_CNT
---------- ----------
        -1          0
        -2          0
        -3          0
        -4          0
        -5          0
        -6         10
        -7         10
        -8         10
        -9         10
       -10         10

10 rows selected.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> -- now show the delete from parent
tkyte@ORA734.US.ORACLE.COM> -- tables works OK
tkyte@ORA734.US.ORACLE.COM> delete from emp where mod(empno,2) =
1;

5 rows deleted.

tkyte@ORA734.US.ORACLE.COM> delete from projects where
mod(-projid,2) = 1;

5 rows deleted.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> select * from emp;

     EMPNO   PROJ_CNT
---------- ----------
         2          3
         4          3
         6          3
         8          3
        10          3

tkyte@ORA734.US.ORACLE.COM> select * from projects;

    PROJID    EMP_CNT
---------- ----------
        -2          0
        -4          0
        -6          5
        -8          5
       -10          5

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> select empno, count(*) from
emp_projects group by empno;

     EMPNO   COUNT(*)
---------- ----------
         2          3
         4          3
         6          3
         8          3
        10          3

tkyte@ORA734.US.ORACLE.COM> select projid, count(*) from
emp_projects group by projid;

    PROJID   COUNT(*)
---------- ----------
       -10          5
        -8          5
        -6          5

tkyte@ORA734.US.ORACLE.COM>
Review & Followup
Rating: 5
How to find out the count of the number of times a comma occurs in a string, using sql November 06, 2001
Reviewer: Nag
Tom

I want to know using sql, how can I find out
how many times the ',' occurs in the following string.
Can you give your idea on this.

l_string:='43434,34343,434343,54545,43,343,343,'

August 22, 2000 Sonja -- Thanks for the question regarding "PL/Sql -- generating the last day of a month given a range.", version 8.0.5
You Asked
I have a report that is tricky, think I need to program my way
around it:

The users want to input 2 dates, which could be from different
years, and they want the report to be able to show the values
from every last day in every month in that time period they've
entered together with the total for the time period.

So, I need a function to find the last day (28th, 30th, 31th) in
every month in the timeperiod and find the value they want from
that day.

Any elegant suggestions that don't slow down my reports to much?

Thanks,

Sonja Cassidy Ones
and we said...
You can use the following query to generate the list of last
days of the month.  You just need a table that has more rows
then your maximum time period (you might want to create a
special 1 column table for just such a purpose -- you'll only be
selecting rownum from it so it doesn't matter whats in it).

You can use the query below in an "IN" statement effectively
(and efficiently)....

tkyte@ORACLE8I> exec :begin_date := '01-nov-1999'
PL/SQL procedure successfully completed.

tkyte@ORACLE8I> exec :end_date   := '01-mar-2000'
PL/SQL procedure successfully completed.

tkyte@ORACLE8I>
tkyte@ORACLE8I>
tkyte@ORACLE8I> select add_months(
  2           last_day(to_date(:begin_date,'dd-mon-yyyy')),
  3           rownum-1 )
  4    from all_objects
  5   where rownum <= months_between(
  6                     to_date(:end_date,'dd-mon-yyyy'),
  7                     to_date(:begin_date,'dd-mon-yyyy'))+1
  8  /

ADD_MONTHS(
-----------
30-nov-1999
31-dec-1999
31-jan-2000
29-feb-2000
31-mar-2000

Replace all_objects with a reference to your own table with
enough rows if you like -- all_objects usually has enough rows
for this to work well though (but it adds to the complexity of
the query plan so you might use a simple table)
August 22, 2000 Ashish -- Thanks for the question regarding "Logging out from OAS", version 8.1.5
You Asked
Hi TOM,

We are using Oracle 8.1.5 and OAS 4.0.8.1 for our web site. We
are using Basic Oracle authentication. I had asked you last time
about Log out. Our site has a Login facility but none for Log
out. I was thinking of creating a button on the page. Pressing
the button will call a procedure which will do ' alter system
kill session'. Would you suggest this method as I am not able to
find any other. Most of the sites running on oAS doesn't have it
either. Does IAS supports Log out facility?

regards,

ashish
and we said...
Logging out is not something that is easy to provide (and it
cannot technically really be done).

There is no logout mechanism and doing a "kill session" won't do
it (it would just terminate you current call -- each web page is
a brand new session).

The reason we cannot "logout" is cause OAS doesn't do the
Logging in -- the browser is the one caching your username and
password -- not us.  We need to convince the browser that your
username and password is "incorrect" (but they aren't really)
and you would have to enter another that is actually "incorrect"
but that OAS would say "ok" for (to trick the browser into
forgetting the OLD username and password that really works and
remembering the NEW username and password that doesn't really
work).

The only way to log out of BASIC authentication -- when the
browser is the one caching the username and password -- is to
exit the browser.  Why the browser makers never added a "logout"
feature is beyond me (everyone asks for it)...
August 22, 2000 Irshad -- Thanks for the question regarding "datafile size > 2Gig", version 8.1.5
You Asked
I would like to know the best possible way of database backup
procedure if the database file size > 2 GB.

Thanks.
and we said...
Use RMAN.  It will do it.

Unix DD has no problems with files >2 gig as far as I know.

I myself prefer to never let a file get >2gig.  No reason to let
it get >2gig (the largest extent we support is 2gig).  I cannot
think of any valid reason to let them get that big myself (only
makes them that much harder to backup and restore.  In the event
of a failure of a single datafile -- you have 1 really big one,
i have a couple of smaller ones -- faster to recover as well)
August 22, 2000 Dario -- Thanks for the question regarding "Create a database", version version 8.1.5 Enterprise Edition
You Asked
I've looked everywhere and no one has the simple code to create
a new database. I need to create it so I can transfer tables
from another database. Can you please help me by sending the
code to create a new database. Thank-you. It will much
appreciated.
and we said...
The database assistant does this for you.  It'll either create
the database or just generate the scripts that will create a
database for you.

Chapter 2 of the Admin guide has all of the step by steps as
well with examples...
August 22, 2000 John -- Thanks for the question regarding "Passing an array of strings to a where clause -- for us in an in list", version Oracle 7.3.4
You Asked
Hi Tom,

I need to pass an array of strings to a where clause(i.e.)
where <value> in :<value>  One problem I am running into is
that the resultant <value> string turns out to be more than
2000 bytes(more close to around 10,000 to 12,000 bytes). Is
there
a way around this. We are using Oracle v7.3.4.

Thanks.
and we said...
se
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:110612348061
for why a single string won't work (and a great way to do this
in 8.0 and up)

And then see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:139812348065
for how to do this in 7.x and 8.x
August 22, 2000 Luis -- Thanks for the question regarding "UTL_FILE - how to use it?", version Version 8
You Asked
How i use the utl_file
and we said...
read
http://technet.oracle.com/doc/oracle8i_816/server.816/a76936/utl_file.htm#998101
various examples at:
http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:utl_file
....
August 22, 2000 Leon -- Thanks for the question regarding "RAID configuration ?", version 7.3
You Asked
Hi Tom,

Here are my questions:

1) How can I know whether an Oracle database uses
RAID technigue (configiration) for control file and
redo log files multiplexing? Is there any commands
to verify (check) these from Unix and Oracle Server
Manager or some system file storing the information?

2) What happends if one of members in a redo log
group fails (disk failure)? Will the instance be
crash or continue to write redo information to
other memeber of the same redo log group? and report
error in alert.log file? How about the similar situation
for control file ?

3) The situation is that the destination disk for
archived redo log files is full (or crach) which
cause the database hangs? Does ARCH will be down
in this case? Do I need to restart ARCH process
after resolving the disk problem. What is the best
procedure to follow?

Thanks,

Leon,
and we said...
1) it varies from OS and OS and Oracle cannot tell the
difference.  To use a raid volume is a volume is a volume.  We
don't care, nor do we inspect for it.  We don't know.

2)

redo - message in alert and processing continues.

see
http://technet.oracle.com/doc/server73x/SCN73/ch22.htm#toc156
and search for "The Mechanics of a Multiplexed Online Redo Log"

control - database shuts down.

see
http://technet.oracle.com/doc/server73x/SCN73/ch22.htm#toc158
and search for "Multiplexed Control Files"

3) is the destination is full or unavailable, arch will wait
till it frees up/becomes available and they start going again by
itself.

see
http://technet.oracle.com/doc/server73x/SCN73/ch22.htm#toc157
for more info on that.
August 22, 2000 -- Thanks for the question regarding "Number matching query -- sort of a tricky one...", version Oracle 7.3.4
You Asked
We have a list of telephone numbers:

0000000000
99999999996666
555555555500
3333333

As you can see, the numbers are from around the world and may
contain missing data or extensions.

The main thing we want to do is take every possible 6 number
subset of each number and collect the count of 6 number matches
between every other telephone number in the database.

0123456789 could have the following matches that would need to
be counted:

012345
123456
234567
345678
456789

A report of each number that contained at least one of these
subsets and the count of how many subsets is needed.
This will be true for every number in the table.

Original Number  Matching Number  Number of Hits
123456789        0123456          2

Is this possible with just straight SQL?  What might be the best
way to approach the problem?
and we said...
Yes, I believe so but for a large table -- this will get
exponentially slower and slower....

tkyte@ORA734.US.ORACLE.COM> create table r
  2  as
  3  select rownum x from all_objects where rownum < 100;

Table created.

The number of rows in R must be > max length of your telephone
numbers!

tkyte@ORA734.US.ORACLE.COM> create table t ( tel# varchar2(25)
);
Table created.

tkyte@ORA734.US.ORACLE.COM> insert into t values ( '123456789'
);
1 row created.

tkyte@ORA734.US.ORACLE.COM> insert into t values ( '0123456' );
1 row created.

There are your numbers.. Now to see how this works, we'll
start with what will become my inner most query:

tkyte@ORA734.US.ORACLE.COM> select t.tel#,
                             substr( t.tel#, r.x, 6 ), r.x
  2    from t, r
  3   where length( substr( t.tel#, r.x, 6 ) ) = 6
  4  /

TEL#                      SUBSTR          X
------------------------- ------ ----------
123456789                 123456          1
0123456                   012345          1
123456789                 234567          2
0123456                   123456          2
123456789                 345678          3
123456789                 456789          4

6 rows selected.

That generates all of the 6 character substr's of our phone
numbers for it.  2 of them for 0123456 and 4 of them for
123456789

tkyte@ORA734.US.ORACLE.COM> select a.tel#, a.piece, b.tel#,
b.piece
  2  from (
  3  select t.tel#, substr( t.tel#, r.x, 6 ) piece, r.x
  4    from t, r
  5   where length( substr( t.tel#, r.x, 6 ) ) = 6
  6       ) a,
  7       (
  8  select t.tel#, substr( t.tel#, r.x, 6 ) piece, r.x
  9    from t, r
 10   where length( substr( t.tel#, r.x, 6 ) ) = 6
 11       ) b
 12   where a.tel# <> b.tel#
 13     and a.piece = b.piece
 14  /

TEL#                      PIECE  TEL#                      PIECE
------------------------- ------ -------------------------
------
0123456                   123456 123456789
123456
123456789                 123456 0123456
123456

Now, we just join the synthesized table with itself.  We want
any row where the Tel# are different but some piece of them are
the same....

tkyte@ORA734.US.ORACLE.COM> select greatest( tel#1, tel#2 ),
least( tel#1, tel#2 ), count(*)
  2  from (
  3  select a.tel# tel#1, a.piece, b.tel# tel#2, b.piece
  4  from (
  5  select t.tel#, substr( t.tel#, r.x, 6 ) piece, r.x
  6    from t, r
  7   where length( substr( t.tel#, r.x, 6 ) ) = 6
  8       ) a,
  9       (
 10  select t.tel#, substr( t.tel#, r.x, 6 ) piece, r.x
 11    from t, r
 12   where length( substr( t.tel#, r.x, 6 ) ) = 6
 13       ) b
 14   where a.tel# <> b.tel#
 15     and a.piece = b.piece
 16           )
 17  group by greatest( tel#1, tel#2 ), least( tel#1, tel#2 )
 18  /

GREATEST(TEL#1,TEL#2)     LEAST(TEL#1,TEL#2)          COUNT(*)
------------------------- ------------------------- ----------
123456789                 0123456                            2

Go one step further to aggregate and count the hits....

I think thats what you want....
August 23, 2000 Shaharidan -- Thanks for the question regarding "Re-create Index", version 7.3.3.6
You Asked
Hi,

I'd like to know what is the appropriate new storage (initial
and
next) size if I want to re-create the index. The index and
tablespace
freespace info as below:

The Index information
========================

Segment         EXTENTS INITIAL_EXTENT NEXT_EXTENT     BYTES
-------------- ------- --------------  -----------  ---------
PS1SH_AR_TRAN    19         2,228,224     106,496   4,464,640

The TBS Freespace information
=============================

Tablespace   FILE_ID  BLOCK_ID     BYTES    BLOCKS

---------- --------- --------- --------- ---------

PSINDEX            5      3636     16384         2

                   5     14803     24576         3

                   5     12424     32768         4

                   5     14583     65536         8

                   5     57487    122880        15

                   5     19671   1966080       240

                   5     45581   1966080       240

                   5     88262  10485760      1280

                   5     79352  22978560      2805

                   5     96917 149782528     18284

I'll do a drop index PS1SH_AR_TRAN then create index
PS1SH_AR_TRAN
on PS_AR_TRAN (col1, col2,col3) tablespace PSINDEX
storage (initial ? next ? maxextents 505 pctincrease 0).

What is the right size for initial and next ?

Thanks.
and we said...
It depends on who you ask and how this index grows.

Since it is a tiny 4meg index -- I would just let it be.  Having
many extents (upto hundreds) is not bad, its perfectly OK.
What is a problem here is the use of pctincrease -- I personally
do not like or use pctincrease myself.

I like to use fixed size extents -- that way I don't end up with
wierd sized free extents (eg: when you drop or rebuild that
index -- you might end up with some 16k, 24k, 32k, 64k "holes"
in your PSINDEX tablespace that no one will ever be able to use.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:228413960506
for more info on that.

Now, back to this index.  It is 4 meg (small, almost tiny).
Once I knew how it grew -- I would know what to do with it.
Let's say we expect it to grow by 1meg / year.  I would assign
this object to a "small extent" tablespace -- a tablespace that
allocated extents 256k at a time with pctincrease = 0 and
initial=next=256k.  It'll start off with 16 extents more or less
and add 4 extents / year (meaning it'll take 20years to get over
100 extents).

I would have other tablespaces that allocated object 1/2 meg at
a time, 1meg at a time, 5meg, 10meg and so on (depending on my
needs).

If I ever needed to rebuild that index for whatever reason (rare
to have to rebuild an index -- never ever need to rebuild a
regular table) -- I would use the alter index rebuild.  That
will use the existing index (already sorted and all) to rebuild
itself in that tablespace -- as it frees up its already
allocated extents - they will become available to ANY object in
that tablespace since EVERY object in that tablespace uses the
same size extents (no fragmentation ever -- no reorgs
ever)...
August 23, 2000 Ramesh -- Thanks for the question regarding "Tips Related to Database Tuning", version 8.0.5
You Asked
Dear Tom,

I would like to have some good scripts other than the one in
tips 2000 to study the database and to tune the database in an
efficient manner.

Kindly do the need full.

Thanks & Regards

Ramesh
and we said...
You want the statspack then
http://www.oracle.com/oramag/oracle/00-Mar/o20tun.html
There is a special version for 8.0 and the regular version for
8.1 and up.
August 23, 2000 Roop -- Thanks for the question regarding "Online Help", version Designer 2000 R 2.1; Forms Builder v 5.0.6.14.2
You Asked
Hi Tom,

I am using Designer 2000 R 2.1, Forms builder 5. to develop
an application.

I am documenting every attributes and functions in Designer
2000.

I want to provide an online help in my forms.

What are the various way of doing it and how to do it ?

Thanks

Roop
and we said...
I asked someone who uses designer much more then me and he says:

...
For the first one - if he is generating his Forms from Designer
he has several options.

Designer includes an Microsoft Help generator. I've never used
it and therefore can't offer any useful commentary other than to
say not to use this option if the Forms will eventually be run
on the Web.

The other option is to use what Designer calls a Help Form.
Basically each item on the Form module has an area to enter help
text. This help text will be displayed in the 'Help Form' which
is specified by the generator preference HLPFRM. There is a
default help form that ships with Designer, or the user can
create their own help form. For more information on this option
the best thing is to look in Designer's Help system. From the
Designer Front Panel select 'Help'. From the help window click
on the 'Index' tab. From there search for 'help in generated
applications' and then double click on Form Builder.
..
August 23, 2000 minnie -- Thanks for the question regarding "How to pass a Blob buffer between C external procedure and pl/sql?", version oracle8i 8.1.5
You Asked
hi,Tom:
   say there are table test has a BLOB column(already has a
        row which BLOB column has values):
         create table test
         (
              c1       number;
              c2       Blob;
         );
   and a function:
    FUNCTION extCalculateScoreByBlob
      (
        buffer        in     RAW
    )
    RETURN DOUBLE PRECISION
    IS EXTERNAL
    NAME "CalculateScoreByBlob"
    LIBRARY SELIB
    WITH CONTEXT
    PARAMETERS
    (
        context,
        buffer        by reference    RAW,
        buffer        LENGTH,
        buffer        INDICATOR             SB4
    );

   and a C external procedure:
        double CalculateScoreByBlob
        ( with_context,
          buf_in, buf_len, ind_buf
        )
        OCIExtProcContext *with_context;
        unsigned char       *buf_in;
        ub4           *buf_len;
        sb4           *ind_buf;
       {
        .................
       }

  and all the staff are used in a PL/SQl procedure like:

       create or replace test_p is
    v_blob_online    BLOB;
    read_amount           BINARY_INTEGER := 32767;
    read_offset           INTEGER := 1;
    buffer        RAW(7332);
         v_rtn             number;
       begin
    select c2 into v_blob_online
    from test
    where c1 =1;

    read_amount :=DBMS_LOB.GETLENGTH(v_blob_online);

    dbms_output.put_line('read_amount='||read_amount);

    read_offset := 1;

    DBMS_LOB.READ (v_blob_online, read_amount ,
                       read_offset, buffer);

         v_rtn :=extCalculateScoreByBlob(buffer);
       end;

   when executed, there are an error like :
   ORA-01460: unimplemented or unreasonable conversion
              requested;

   I think this must be caused by incorrect declared
   C prototype parameters.

   Could you please correct it for me?
and we said...
Ok, I show you how to do the RAW but I'll also make you see the
right datatype to use as well (BLOB directly to OCI).  Offhand,
I do not see your ORA-1460 but I cooked up this example:

drop table t;

create table t ( x blob );

declare
   l_raw   long raw;
   l_blob  blob;
   l_blob_size number := 5000;
begin
    for i in 1 .. l_blob_size loop
       l_raw := l_raw || hextoraw(to_char(mod(i,256), 'fmXX'));
    end loop;
    insert into t values ( empty_blob() )
             returning x into l_blob;
    dbms_lob.writeappend( l_blob, l_blob_size, l_raw );
    commit;
end;
/

So, that created a 5,000 byte blob.  It has every character we
can have from chr(0) to chr(255).  We know the SUM of the bytes
in this raw is:

629,476

that is -- if we

tkyte@TKYTE816> declare
  2    sum_of_bytes double precision := 0;
  3  begin
  4    for i in 1 .. 5000 loop
  5          sum_of_bytes := mod(i,256)+sum_of_bytes;
  6    end loop;
  7          dbms_output.put_line( sum_of_bytes );
  8  end;
  9  /
629476

PL/SQL procedure successfully completed.

we get that sum... Thats what our C code will do as an example
(sum the bytes)....

So, here is the package I want to implement:

create or replace package demo_passing_pkg
as
    function pass_lob( p_in in BLOB ) return double precision;

    function pass_raw( p_in in RAW ) return double precision;

end demo_passing_pkg;
/

I'm going to have one for a RAW and another for a blob.  My body
for that is:

create or replace package body demo_passing_pkg
as
    function pass_lob(  p_in in  blob ) return double precision
    as
    language C
    name "pass_lob"
    library demoPassing
    with context
    parameters ( CONTEXT,
                 p_in  OCILOBLOCATOR,
                 p_in  INDICATOR short,

                 return INDICATOR short );

     -- void pass_clob
     --   (
     --  OCIExtProcContext  *,  /*   1 : With-Context  */
     --      OCILobLocator  *,  /*   2 : P_IN  */
     --              short   ,  /*   3 : P_IN (Indicator) */
     --              short  *,  /*   4 : RETURN (Indicator) */
     --   );

    function pass_raw(  p_in  in  raw ) return double precision
    as
    language C
    name "pass_raw"
    library demoPassing
    with context
    parameters ( CONTEXT,
                 p_in  RAW,
                 p_in  INDICATOR short,
                 p_in  LENGTH int,
                 RETURN INDICATOR );

     -- void pass_long_raw
     --   (
     --  OCIExtProcContext  *,  /*   1 : With-Context  */
     --      unsigned char  *,  /*   2 : P_IN  */
     --              short   ,  /*   3 : P_IN (Indicator) */
     --                int   ,  /*   4 : P_IN (Length) */
     --              short  *,  /*   5 : RETURN (Indicator) */
     --   );

end demo_passing_pkg;
/

I like to be verbose.  I want to be able to return NULL from
this function (if for example, my inputs are NULL).  Therefore,
I need the return indicator.  We don't need to pass the raw by
reference (just makes it harder to read the length and all)
since raws are already sent to us as a pointer -- so I won't...

My C code for these two functions is then:

#include <oci.h>

#ifdef WIN_NT
_declspec (dllexport)
#endif
double pass_raw
 ( OCIExtProcContext * ctx     /* CONTEXT */,

   unsigned char *  p_iraw     /* RAW */,
   short            p_iraw_i   /* INDICATOR short */,
   int              p_iraw_l   /* LENGHT INT */,
   short *          return_i   /* return indicator */
 )
{
double           sum_of_bytes = 0;
unsigned char*   cp;
int              i;

    if ( p_iraw_i == OCI_IND_NOTNULL )
    {
        for( cp = p_iraw, i = 0; i < p_iraw_l; i++, cp++ )
        {
           sum_of_bytes += (double) *cp;
        }
        *return_i = OCI_IND_NOTNULL;
    }
    else
    {
        *return_i = OCI_IND_NULL;
    }
    return sum_of_bytes;
}

#ifdef WIN_NT
_declspec (dllexport)
#endif
double pass_lob
 ( OCIExtProcContext * ctx        /* CONTEXT */,

   OCILobLocator *    p_in    /* OCILOBLOCATOR */,
   short              p_in_i  /* INDICATOR short */,
   short *            return_i   /* return indicator */
 )
{
ub4                 lob_length;
unsigned char *     cp;
double              sum_of_bytes;

OCIEnv *            envhp;    /* OCI environment handle */
OCISvcCtx *         svchp;    /* OCI Service handle */
OCIError *          errhp;    /* OCI Error handle */

    if ( OCIExtProcGetEnv( ctx, &envhp,
                           &svchp, &errhp ) != OCI_SUCCESS )
    {
         OCIExtProcRaiseExcpWithMsg(ctx,20000,
               "failed to get OCI Connection",0);
         return 0;
    }

    if ( p_in_i == OCI_IND_NOTNULL )
    {
        if ( OCILobGetLength ( svchp, errhp, p_in,
                               &lob_length ) != OCI_SUCCESS)
        {
            OCIExtProcRaiseExcpWithMsg(ctx,20000,
                 "failed to get lob length",0);
            return 0;
        }

        if ( (cp = OCIExtProcAllocCallMemory( ctx,
                                      lob_length )) == NULL )
        {
            OCIExtProcRaiseExcpWithMsg ( ctx, 20001,
                                        "No memory", 0 );
        }
        else
        {
            if ( OCILobRead( svchp,  errhp, p_in, &lob_length,
                         1, (dvoid *) cp,
                         (ub4) lob_length, (dvoid *)0,
                          NULL, (ub2) 0,
                         (ub1) SQLCS_IMPLICIT) != OCI_SUCCESS )
            {
               OCIExtProcRaiseExcpWithMsg(ctx,20000,
                                  "failed to read lob",0);
            }
            else
            {
               for( ; lob_length; lob_length-- )
                  sum_of_bytes += (double) *(cp+lob_length-1);
               *return_i = OCI_IND_NOTNULL;
            }
        }
    }
    else
    {
        *return_i = OCI_IND_NULL;
    }
    return sum_of_bytes;
}

Now, the blob code looks more complex however, if you look at
the plsql code for interfacing with each one:

tkyte@TKYTE816> declare
  2          sum_of_bytes double precision;
  3          l_blob    blob;
  4          l_raw     raw(32000);
  5          l_offset  number default 1;
  6          l_amt     number;
  7  begin
  8          select x into l_blob from t;
  9          l_amt := dbms_lob.getlength( l_blob );
 10
 11          dbms_lob.read( l_blob, l_amt, l_offset, l_raw );
 12
 13          sum_of_bytes := demo_passing_pkg.pass_raw( l_raw );
 14
 15          dbms_output.put_line( sum_of_bytes );
 16  end;
 17  /
629476

PL/SQL procedure successfully completed.

tkyte@TKYTE816>
tkyte@TKYTE816> declare
  2          sum_of_bytes double precision;
  3          l_blob    blob;
  4  begin
  5          select x into l_blob from t;
  6          sum_of_bytes := demo_passing_pkg.pass_lob( l_blob
);
  7
  8          dbms_output.put_line( sum_of_bytes );
  9  end;
 10  /
629476

PL/SQL procedure successfully completed.

You can see we just moved complexity from PLSQL into C or vice
versa (someone has to do the work).  The added benefit of the
LOB implementation will come in for blobs >32k.  It will take
repeated calls to the extproc to process the entire blob, if we
pass the blob, we can use OCILobRead to piecewise read it in C
instead of PLSQL (as plsql will limit you to a 32k raw)....
August 23, 2000 Vladimir -- Thanks for the question regarding "Java Sored Procedure - Oracle", version 8i
You Asked
I am trying to access files from a Java stored procedure using
UNC pathnames of the form

\\server\shares\dir\file

but can't seem to get it to work.  Does the Aurora JVM support
file names of this kind?  My code works when I use convention
file names like

c:\dir\file

Thanks!
and we said...
NT Networked Directories
------------------------

When an oracle instance is created the services that support it
are setup to "Log On As" the SYSTEM (or operating system)
account, this account has very few privileges and no access to
NT Domains. To access another NT machine the OracleServiceXXXX
must be setup to logon to the appropriate NT Domain as a user
who has access to the required location.

To change the default logon for the Oracle services, go to :

  -> Control Panel
     -> Services
        -> OracleServiceXXXX (where XXXX is the instance name)
           -> Startup
              -> Log On As

Choose the "This Account" radio button, then complete the
appropriate domain login information. Once the services have
been setup as a user with the appropriate privileges , it should
work better.
August 23, 2000 Ian -- Thanks for the question regarding "Application Servers - Submitting SQL querys -- getting a result set from cold fusion.", version 8.0.5
You Asked
Having targeted a SQL Server database from Cold Fusion using
Stored Procedures to return query results to a HTML page, my
question is: How do I do the same for Oracle? Procedures don't
seem to return values, and Functions seem to need to be called
within a statement. I am looking at submitting SQL queries from
outside the database (maybe via EJBs, from an application
server), but am unsure how to continue. I am in the process of
trying to port the database from SQLServer to Oracle, and have
tried Oracle Migration Workbench, which, while successful in
moving the tables and the data, had trouble with the SPs. In any
case, can they be called from outside Oracle?

Kind regards,

Ian
and we said...
See
http://osi.oracle.com/~tkyte/ResultSets/index.html
I do not have a cold fusion example but it'll get you pointed in
the right direction.  We call them REF CURSORS and I know Cold
fusion supports them, actually I found this on their web site at
the url:
http://www.allaire.com/Handlers/index.cfm?ID=13754&Method=Full
Oracle Reference Cursor Support

This release supports the return of result sets via Oracle
Reference Cursors through the Oracle 8 native driver and the
ColdFusion stored procedure interface.

The example below shows both the PL/SQL necessary for creating a
procedure to return a result set and the CFML necessary for
executing the procedure in ColdFusion. The example uses the
Oracle SCOTT/TIGER login sample data. The final ColdFusion
documentation for this release will contain additional
information and examples.

Example: Return of all rows in the DEPT table entirely through a
package.

PL/SQL
=============

CREATE OR REPLACE PACKAGE dept_data AS
    TYPE DeptTyp IS REF CURSOR RETURN dept%ROWTYPE;
    PROCEDURE refcurproc(pParam1 in out DeptTyp);
END dept_data;

CREATE OR REPLACE PACKAGE BODY dept_data AS
    PROCEDURE refcurproc(pParam1 in out deptTyp) IS
    BEGIN
        OPEN pParam1 FOR select * from dept;
    END refcurproc;
end dept_data;

CFML
===========

<cfstoredproc    procedure="dept_data.refcurproc"
                datasource="my_oracle80_test"
                username = scott
                password = tiger
                RETURNCODE="no"
>
<cfprocparam type="Out" cfsqltype="CF_SQL_REFCURSOR"
variable="param1">
<cfprocresult     name = rs1>
</cfstoredproc>
<b>The first result set:</b><br>
<hr>
<cfoutput query = rs1>
#dname#,#deptno#
</cfoutput>
August 23, 2000 GAURANG -- Thanks for the question regarding "IMPORT", version 8.1.5
You Asked
hi tom.
Can we import oracle 7.3.4 database export file in oracle 8.1.5?
and we said...
Yes.

export/import are backwards compatible.

An export from version X can be imported into version Y as long as X <= Y.

That export cannot be imported if X > Y (eg: 8.0 cannot be imported into 7.3).
In order to go that direction, you must use the export tool from Y (7.3 for
example) against the X version database (8.0).  There is a catexp7.sql you can
run in a v8.x instance in support of this.
August 23, 2000 Krishna -- Thanks for the question regarding "Loading Lobs Using SQL Loader", version 8i
You Asked
Hi,
I need some help here. I am trying to load a text document in to

a table . Structure of my table is as follows.
 LOB_ID           VARCHAR2(1)
 MY_LOB           CLOB
 This is my control file.
load data
infile 'h:\roy\sqlldr\dat\clob.dat'
replace
into table test_lob
fields terminated by ','
(
 lob_id char(1),
  MY_LOB LOBFILE("h:\roy\doc\acct.txt") TERMINATED BY EOF
 )
 This is clob.dat
1,
2,

and I get the following error
SQL*Loader-416: SDF clause for field MY_LOB in table TEST_LOB
references
 a non existent field.

I created controlfile, data file using an exaple from oracle
online doc.
     Thank you so much
Krishna P Roy
and we said...
load data
infile *
replace
into table test_lob
fields terminated by ','
(
 lob_id char(1),
 lob_file FILLER char,
  MY_LOB LOBFILE(lob_file) TERMINATED BY EOF
 )
begindata
1,h:\roy\doc\acct.txt
2,h:\roy\doc\acct.txt

will work.

or if you really want to load the same file for all rows

  LOBFILE( CONSTANT h:\roy\doc\acct.txt ) TERMINATED ....

will do it (need keyword CONSTANT and no quotes)
Review & Followup
Rating: 5
text loading December 04, 2001
Reviewer: raghunath from Blore , India
good , one of the best forums for data loading problems

August 23, 2000 Lindsay -- Thanks for the question regarding "Shrinking High Water Mark", version 8.1.6.1
You Asked
I have noticed that the HWM will only go down if the table is
truncated.  If I do the following will it lower the HWM:

CREATE TABLE temp AS SELECT * FROM table_name;

TRUNCATE table_name;

INSERT INTO table_name SELECT * FROM temp;

COMMIT;

This has been successful at times in lowering the HWM and other
times not.  I am wondering why the inconsistency?

Is there a better way?

I am measuring the used blocks with the following:

select count(distinct dbms_rowid.rowid_block_number(rowid) ||
dbms_rowid.rowid_relative_fno(rowid)) "Used"
from table_name;

Thanks
and we said...
Thats not a good way to measure used blocks.  It ignores block
chaining and row migration completely.  It ignores blocks that
were used but aren't anymore (eg: put a million rows in a table,
commit, delete from table, commit, run your process above --
it'll say "zero" but used blocks is actually quite high).  It
can be widely inaccurate. See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
for a better way to measure used blocks in a table...

The CTAS/truncate/INSERT will lower the high water mark as much
as possible (down to MINEXTENTS on the table anyway).  It might
appear to not work for you since your method of counting used
blocks doesn't work (especially if you have rows that span
blocks -- you are only counting the head pieces.  If you do this
with a table that has say a 4,000 byte width and you have a 2k
blocksize -- a row might be on 3 blocks, you could be off by a
factor of 3 or more in that case).

In 8.1 and up (which you have), look at ALTER TABLE T move
storage (...)  as a way to avoid lots of moves -- just remember
to alter index rebuild for all indexes on the table afterwards.
This'll work with RI and all intact.

Must be a strange application that you need to lower a HWM
frequently -- perhaps a candidate for rolling partition windows?
 Sounds like you might be adding and purging lots of data --
perhaps a partition can be used more efficiently to avoid this?
Also -- unless you full scan the table frequently -- why do you
care about the HWM?  We'll reuse that space over time so unless
you full scan it lots -- why bother?
August 24, 2000 Bojan -- Thanks for the question regarding "any simple way to export ORACLE connections in UNIX?", version oracle 7.3.2
You Asked
Tom,
I have ORACLE installed on IRIX machine. What I need is: how to
make liaison between ORACLE connections and UNIX (IRIX)
proceses.

I can find all my ORACLE connections using sqlplus query.

I can find all my UNIX proceses using adequate commands.

But...When I am logged as ORACLE user (or dba) I cannot invoke
cron or any script from UNIX, and vice versa.

Questions:

a) is there any simple way to export ORACLE connections (with
usernames and login times) periodicaly (for example, every two
or three minutes)?

b) is there any software tool providing such service (connecting
ORACLE connections to adequate UNIX proceses)?

Thank you
Bojan
and we said...
a) sqlplus can do stuff like that -- just dump a query to text.
Or you can use DBMS_JOB to schedule a stored procedure that uses
UTL_FILE to write an OS file every N minutes.  Search for
dbms_job or utl_file on my search screen for many examples of
using them.

b) in DEDICATED server mode, it is trivial.  In MTS
(multi-threaded server) mode it is impossible (as there is not a
1-1 mapping anymore between a user and a process).

In dedicated server mode, a script run in sqlplus on the machine
with the database like this:

----------------------------------------------
set heading off
set feedback off
set termout off
spool tmp.sh

select 'echo Database User:' || replace( a.username, '$', '\$')
|| chr(10) ||
       'ps ' || b.spid
  from v$session a, v$process b
 where a.username is NOT NULL
   and a.paddr = b.addr
/
spool off
host sh tmp.sh

set heading on
set feedback on
set termout on
------------------------------------------

Will create output like:

ops$tkyte@8i> @showprocs

Database User:CTXSYS
   PID TT       S  TIME COMMAND
   552 ?        S  0:06 oracleora8i
(DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq)))

Database User:OPS$TKYTE
   PID TT       S  TIME COMMAND
 13521 ?        S  0:00 oracleora8i
(DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq)))

Database User:WEB$SB_PUBLIC
   PID TT       S  TIME COMMAND
 15062 ?        O  0:00 oracleora8i
(DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq)))
ops$tkyte@8i>

Is that what you want?
August 24, 2000 Sumesh -- Thanks for the question regarding "Knowling the size of the table in BYTES", version 8.0.3
You Asked
Which view should I use to know the size of a tables having n
numbers of records .
If you can write the query also , it will be better for me .
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
it shows you various ways to get the information you are after.
August 24, 2000 t.siva rama -- Thanks for the question regarding "upgradation", version 7.2.2
You Asked
i wanted to upgrade the current version (7.2.2) to 8 or 8i.

can you guide me how should i approach in the DB upgradation
from
lower version to higher version.
and we said...
See the Oracle8i server migration guide.  It covers all of the
requisite steps.
http://technet.oracle.com/doc/oracle8i_816/server.816/a76957/toc.htm
please migrate to 8i, 8.0 is an old version (you would just be
upgrading to software that is already out of date).  You should
go for the latest release...
August 24, 2000 Mario -- Thanks for the question regarding "SQL Loader / Import", version 8.1.5
You Asked
Hi!

I want to import an ascii based data file which has
variable-length data fields (seperated by TAB).
But I don't need all the fields/columns in my database.
How can I specify, which fields I don't want to import?

Data example: (columns:  nr1, name, nr2)

1234    "Mr.X"    5678
34567453    "Mr.Z"    4566

I'm only interested to import column 'name'.

Thanks
    M.Hessler
and we said...
In Oracle8i, release 8.1, use the FILLER keyword (in releases
before that, see
http://osi.oracle.com/~tkyte/SkipCols/index.html
for various methods)

Your control file in 8.1.5 will be:

LOAD DATA
INFILE *
REPLACE
INTO TABLE T
FIELDS TERMINATED BY X'9'
( dummy1 FILLER ,
  NAME   "trim( chr(34) from :name )",
  dummy2 FILLER
)
BEGINDATA
1234    "Mr.X"  5678
34567453    "Mr.Z"  4566

Note: there is an issue with FIELDS TERMINATED BY <tab>
OPTIONALLY ENCLOSED BY <something> in 8.1.  It only affects tab
delimited data -- hence my use of TRIM() instead of optionally
enclosed by.  If this data is comma separated (or something
else) you can use optionally enclosed by instead of TRIM()
August 24, 2000 steve -- Thanks for the question regarding "SQLJ, no output and error codes always 0", version jdeveloper 3.1 + 8.1.6.0.0
You Asked
Hi Tom,

Two questions in one here on some new SQLJ technology.
The following class is deployed to the server and invoker
via PL/SQL wrapper.

Problem 1 - println output never appears.
            I have done:
              set serveroutput on size 5000;
              CALLDBMS_JAVA.SET_OUTPUT(5000);

Problem 2 - (Showstopper!), e.getErrorCode() is always 0.

Example code follows:

import java.sql.SQLException;
import oracle.sql.* ;
import java.math.*;
import java.io.*;
import java.util.*;
import oracle.sqlj.runtime.Oracle;
import sqlj.runtime.*;

public class test_app_locking {

public static int nowt() throws Exception
{
oracle.sql.CHAR discard;

// DROPME HAS SEVERAL ROWS, SO TOO_MANY_ROWS EXCEPTION EXPECTED
try
{
#sql
{
SELECT 'X'
INTO :discard
FROM DROPME
};
}

catch( SQLException e )
{
// OUTPUT NEVER APPEARS
System.out.println ("SQLState: " +
e.getSQLState ());
System.out.println ("Message: " + e.getMessage ());
System.out.println ("Vendor:" + e.getErrorCode ());
// return(e.getErrorCode()); //THIS IS ALWAYS ZERO
return(-678);
}
catch( Exception e )
{
return(-1);
}

return -127;
}
} // end app_lock class
and we said...
Well, there are two problems here:

o your call to dbms_java didn't seem to work
o return code = 0 from getErrorCode.

I'll guess that you forgot to put "/" or ";" at the end of call
dbms_java.set_output(5000).  If you have a script like:

...
set serveroutput on
call dbms_java.set_output(5000)

begin
    .....
end;
...

The call statement just gets "eaten" up and never executed -- it
was put into the run buffer but you never ran it.

For number 2, believe it or not, this is the expected behaviour
for your example.  The issue is that getErrorCode in SQLJ is
defined as:

<quote sqlj doc>
o getErrorCode()
If the error originates in the SQLJ runtime, this method returns
no meaningful information. If the error originates in the JDBC
driver or RDBMS, it returns the five-digit ORA number.
</quote>

A select into isn't really done in SQL.  A Select Into tells the
preprocessor -- please generate code like this for me:

   cursor c1 is select 'X' from dropme;
   open C1;
   fetch C1 into :some_host_variable;
   if ( c1%notfound ) then
       raise an error, no data found
   end if;
   fetch C1 into :dummy;
   if ( c1%found ) then
       raise an error, too many rows
   end if
   close C1;

So, the select into returning too many rows is not an error in
either the JDBC driver nor the RDBMS -- it is a SQLJ runtime
error.  I modified your code to print the stack trace and we see
from that:

java.sql.SQLException: multiple rows found for select into
statement
at sqlj.runtime.error.Errors.raiseError(Errors.java)
at sqlj.runtime.error.Errors.raiseError(Errors.java)
at
sqlj.runtime.error.RuntimeRefErrors.raise_MULTI_ROW_SELECT_INTO(R
untimeRefErrors.java)
at test_app_locking.nowt(test_app_locking:54)

which just shows that this is a SQLJ runtime error -- not a
jdbc/rdbms error.

If I change your example slightly to raise a DATABASE error, we
get the error code.

Below is your example, showing the results getting printed in
SQLPlus, then I'll show you how to modify this example to see
that getErrorCode works when a DATABASE error happens:

ops$tkyte@ORA816> create table dropme ( x char(1) );
Table created.

ops$tkyte@ORA816> insert into dropme values ( 'a' );
1 row created.

ops$tkyte@ORA816> insert into dropme values ( 'b' );
1 row created.

ops$tkyte@ORA816.US.ORACLE.COM> create or replace and compile
  2  java source named "test_app_locking"
  3  as
  4  import java.sql.SQLException;
  5  import oracle.sql.* ;
  6  import java.math.*;
  7  import java.io.*;
  8  import java.util.*;
  9  import oracle.sqlj.runtime.Oracle;
 10  import sqlj.runtime.*;
 11
 12  public class test_app_locking
 13  {
 14
 15     public static int nowt() throws Exception
 16     {
 17     oracle.sql.CHAR discard;
 18
 19     // DROPME HAS SEVERAL ROWS,
 20     // SO TOO_MANY_ROWS EXCEPTION EXPECTED
 21     try
 22     {
 23         #sql { SELECT 'X' INTO :discard FROM DROPME };
 24     }
 25     catch( SQLException e )
 26     {
 27        // OUTPUT NEVER APPEARS
 28        System.out.println ("SQLState: " + e.getSQLState ());
 29        System.out.println ("Message: " + e.getMessage ());
 30        System.out.println ("Vendor:" + e.getErrorCode ());
 31        // return(e.getErrorCode()); //THIS IS ALWAYS ZERO
 32            e.printStackTrace();
 33
 34        return(-678);
 35
 36     }
 37     catch( Exception e )
 38     {
 39        return(-1);
 40     }
 41     return -127;
 42     }
 43  } // end app_lock class
 44  /
Java created.

ops$tkyte@ORA816.US.ORACLE.COM> create or replace
  2  function test_app_locking return number
  3  as
  4  language java
  5  name 'test_app_locking.nowt() return java.lang.Int';
  6  /
Function created.

ops$tkyte@ORA816.US.ORACLE.COM> set serveroutput on size 5000
ops$tkyte@ORA816.US.ORACLE.COM> call dbms_java.set_output( 5000
)
  2  /

Call completed.
I believe you were missing this SLASH

ops$tkyte@ORA816.US.ORACLE.COM> begin
  2    dbms_output.put_line( 'RETURN CODE ---> ' ||
  3                           test_app_locking );
  4  end;
  5  /
SQLState: 21000
Message: multiple rows found for select into statement
Vendor:0
java.sql.SQLException: multiple rows found for select into
statement
at sqlj.runtime.error.Errors.raiseError(Errors.java)
at sqlj.runtime.error.Errors.raiseError(Errors.java)
at
sqlj.runtime.error.RuntimeRefErrors.raise_MULTI_ROW_SELECT_INTO(R
untimeRefErrors.java)
at test_app_locking.nowt(test_app_locking:54)
RETURN CODE ---> -678

PL/SQL procedure successfully completed.

So, the stacktrace I added shows this error eminated from the
SQLJ runtime engine -- not jdbc, not rdbms -- hence getErrorCode
is meaningless.

Now, if I change your SQL Query to cause it to generate a
runtime RDBMS error as follows, we'll see that the error code is
filled in appropriately

ops$tkyte@ORA816.US.ORACLE.COM> create or replace and compile
  2  java source named "test_app_locking"
  3  as
  4  import java.sql.SQLException;
  5  import oracle.sql.* ;
  6  import java.math.*;
  7  import java.io.*;
  8  import java.util.*;
  9  import oracle.sqlj.runtime.Oracle;
 10  import sqlj.runtime.*;
 11
 12  public class test_app_locking
 13  {
 14
 15     public static int nowt() throws Exception
 16     {
 17     oracle.sql.CHAR discard;
 18
 19     // DROPME HAS SEVERAL ROWS,
 20     // SO TOO_MANY_ROWS EXCEPTION EXPECTED
 21     try
 22     {
 23         #sql { SELECT to_char(to_number(x))
 24                                  INTO :discard
 25                                  FROM DROPME
 26                             where rownum = 1 };
 27     }
 28     catch( SQLException e )
 29     {
 30        // OUTPUT NEVER APPEARS
 31        System.out.println ("SQLState: " + e.getSQLState ());
 32        System.out.println ("Message: " + e.getMessage ());
 33        System.out.println ("Vendor:" + e.getErrorCode ());
 34        // return(e.getErrorCode()); //THIS IS ALWAYS ZERO
 35            e.printStackTrace();
 36
 37        return(-678);
 38
 39     }
 40     catch( Exception e )
 41     {
 42        return(-1);
 43     }
 44     return -127;
 45     }
 46  } // end app_lock class
 47  /

Java created.

In this case, the select will fail because 'a' is not a number
and the to_number() will raise the error in the database

ops$tkyte@ORA816.US.ORACLE.COM> set serveroutput on size 5000
ops$tkyte@ORA816.US.ORACLE.COM> call dbms_java.set_output( 5000
)
  2  /

Call completed.

ops$tkyte@ORA816.US.ORACLE.COM> begin
  2    dbms_output.put_line( 'RETURN CODE ---> ' ||
  3                           test_app_locking );
  4  end;
  5  /
SQLState: 42000
Message: ORA-01722: invalid number
Vendor:1722
oracle.jdbc.driver.OracleSQLException: ORA-01722: invalid number
at oracle.jdbc.kprb.KprbDBAccess.check_error(KprbDBAccess.java)
at oracle.jdbc.kprb.KprbDBAccess.fetch(KprbDBAccess.java)
at
oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement
.java)
at
oracle.jdbc.driver.OracleStatement.doExecute(OracleStatement.java
)
at
oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleSta
tement.java)
at
oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePr
eparedStatement.java)
at
oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePre
paredStatement.java)
at
sqlj.runtime.profile.ref.RTStatementJDBCBase.executeRTQuery(RTSta
tementJDBCBase.java)
at
sqlj.runtime.profile.ref.RTStatementWrapper.executeRTQuery(RTStat
ementWrapper.java)
at
oracle.sqlj.runtime.OraRTStatement.executeRTQuery(OraRTStatement.
java)
at
sqlj.runtime.ExecutionContext$StatementFrame.executeQuery(Executi
onContext.java)
at
sqlj.runtime.ExecutionContext.executeQuery(ExecutionContext.java)

at test_app_locking.nowt(test_app_locking:39)
RETURN CODE ---> -678

PL/SQL procedure successfully completed.

ops$tkyte@ORA816.US.ORACLE.COM>
August 24, 2000 Renauld -- Thanks for the question regarding "The different values of the OPTIMIZER_MODE column in V$SQLAREA", version version 8.0.5
You Asked
Hi Tom,

I was looking at the V$SQLAREA table when I saw
"MULTIPLE CHILDREN PRESENT" in the OPTIMIZER_MODE
column.

I spent sometimes through the doc and the net
but have not find any kind of explaination.

Could you give a word on this ? and perhaps
a good place to read through.

Regards
Renauld Chapellier
and we said...
Finding this value in optimizer_mode column of v$sql means that
the same query was executed at least twice with a slightly
different executing environment which caused the optimizer to
choose a different execution path.

Some examples:

- Two people selecting from different private tables named emp.

- Same query but are using different session optimizer_mode
  setting.

- Both queries are using cost based, but with a different
  session value for sort_area_size or other CBO related
  parameters.
August 24, 2000 Mark -- Thanks for the question regarding "QUERY_STRING", version 4.0.7
You Asked
Tom,

Thanks for all you help on getting my download to work.  Upon
upload of the
data I used a temporary table to convert the long raw input to
blob
and create a download routine that read the blob and piece-wise
sent it
back to the browser.  I have code examples if you have other
people in
need of this capability.

Another Question.  The QUERY_STRING seems to be missing from oas
4.0.x when using the
owa_util.get_cgi_env('VARIABLE') in the PL/SQL cartridge. It
seems
as though all of the other environment variables are there but
not
QUERY_STRING.
Do you know of any patches or alternative routines or function
calls to get the query_string
 (or parameter names and values passed to the plsql routine).

Thanks,

p.s.  Have you thought about using the wrap="VIRTUAL" parameter
on this text area.  It would automatically wrap the text of the
question
within the area.
and we said...
wrap = virtual answer:  got it, it is there now.  did not
realize that was an issue as my browser wraps for me "as is" --
it did not need the wrap=virtual.  Netscape 4.61 apparently did
and maybe others do as well so its there now.

Query_string.  The query_string is never set -- it never needs
to be.  OAS will call a procedure in one of 2 ways:

o formal named parameters -- you KNOW all of the variable value
pairs and don't need a query string to parse!  We already did
that.  You have all of the inputs in formal named parameters

o "flexible parameter passing".  If you define your routine as

proc_name(
    num_entries  IN NUMBER,
    name_array   IN OWA.vc_arr,
    value_array  IN OWA.vc_arr,
    reserved     IN OWA.vc_arr)

then OAS will send you all inputs in these arrays.  The NAME
array will have all of the names that were in the URL, the value
array has their corresponding values.  reserved and num_entries
can be ignored.

See
http://www.olab.com/doc/books/plsql/pl_invk.htm#1014574
for more info on that.  You can build the query string from that
simply with:

   qstring := 'QUERY_STRING=';
   l_sep := null;
   for i in 1 .. name_array.count loop
     qstring := qstring || l_sep ||
                    name_array(i) || '=' ||
                    urlencode(value_array(i));
      l_sep  := '&';
   end loop;

where urlencode is:

create or replace function urlencode( p_str in varchar2 ) return
varchar2
as
    l_tmp   varchar2(6000);
    l_len   number default length(p_str);
    l_hex   varchar2(16) default '0123456789ABCDEF';
    l_num   number;
    l_bad   varchar2(100) default ' >%}\~];?@&<#{|^[`/:=$+''"'
|| chr(10);
    l_char  char(1);
begin
    if ( p_str is NULL ) then
        return NULL;
    end if;

    for i in 1 .. length(p_str) loop
        l_char :=  substr(p_str,i,1);
        if ( instr( l_bad, l_char ) > 0 )
        then
            l_num := ascii( l_char );
            l_tmp := l_tmp || '%' ||
                substr(l_hex, mod(trunc(l_num/16),16)+1, 1 ) ||
                substr(l_hex, mod(l_num,   16)+1, 1 );
        else
            l_tmp := l_tmp || l_char;
        end if;
    end loop;

    return l_tmp;
end;
/

but if you use the flexible arguments -- you don't need query
string, just pass the 2 arrays around.
August 24, 2000 steve -- Thanks for the question regarding "SQLJ, no output and error codes always 0 PT 2", version 8.16.0.0
You Asked
Hi Tom,

Thanks for the response to my question, but I couldn't find
any way to respond to it, I guess you don't want to get
into discussion but I still have a pressing issue:

I can see how a SQLJ runtime error doesn't set that
error code but it begs two further questions:

Why does it (too_many_rows) raise a *SQLException* with
a meaningless error code, and how would I discover
(other than display debug) what the error was?

Obviously, in a production environment, I need to check
an error code somewhere rather than monitor debug output.

So..... I get TOO_MANY_ROWS, how do I tell?

Thanks

Steve
and we said...
Its not that I don't want to get into a discussion but when I
feel I've answered the question and want to "publish" the
article, I freeze it.  It would not look right to have a
published article with followup questions (that I haven't
answered or reviewed, I only want publicly available things I
have personally reviewed for appropriateness).

I frequently have questions in a conversation mode (right now I
have 34 of them).  There, I put questions into a status that
allows you to update them and when you do update them -- I get
notified.

The two questions:

Why does it (too_many_rows) raise a *SQLException* with
a meaningless error code, and how would I discover
(other than display debug) what the error was?

It raises a SQLException because thats the only exection SQLJ
raises.

The error code (which is a JDBC, RDBMS error code) is
meaningless in this case for the simple reason that getErrorCode
is defined to return only JDBC or RDBMS errors.  This is a SQLJ
runtime error.  The set of errors for JDBC, RDBMS and SQLJ
comprise the set of SQL errors you can get.

How to discover the error -- It is in your example already.  The
SQLState is the right way to get SQLJ errors:

<quote sqlj manual>
o getSQLState()

If the error originates in the SQLJ runtime, this method returns
a five-digit code indicating the SQL state. If the error
originates in the JDBC driver, it returns no meaningful
information. If the error originates in the RDBMS, it returns
the
five-digit SQL state. Your code should be prepared to handle a
null return.
</quote>

The meaning of SQLState 21000 is

21000 cardinality violation

(see chapter 9 in the Pro*C manual for the list of SQLStates
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76942/pc_09err.htm#3146

if the errorCode is 0 (SQLJ runtime error) go for SQLState
August 24, 2000 Erin -- Thanks for the question regarding "Batch Webdb -- exporting more then 1 object", version 2.2
You Asked
Tom,
 Is it there away to import/export Webdb coomponents in
 batch as opposed to selecting ONE report or frame at a time??
 (The way Webdb offers).  I tried using the Oracle
import/export,
 but that had some problems, when I called support they informed
me
they don't support this at all.  Thanks for any help.  Erin
and we said...
What does work, I've seen others use it, is to use SQLPLUS and
call the webdb export routines directly.  It would look like:

You could write a sql script like this...

set serverout on size 100000
set linesize 1000
set trimspool on
set feedback off

begin
 WEBDB.wwv_component_control.export_component
     ( p_module_id => 12345, p_version => 6 );
end;
/
spool /tmp/filename1.sql
exec owa_util.showpage;
spool off

begin
WEBDB.wwv_component_control.export_component
     ( p_module_id => 67890, p_version => 11 );
end;
/

spool /tmp/filename2.sql
exec owa_util.showpage;
spool off

...

You'll have to get the correct module_id and version for the
objects you want.  You can get that off the any URL that is
editing that object.
Review & Followup
Rating: 4
Table to get MODULES IDs & VERSION January 08, 2002
Reviewer: Joao Paulo Lunardelli from Sao Paulo, SP BRAZIL
Is there a TABLE that I can get all the modules ids and versions to generate
this script automatically?

Is this work for WebDB 2.2?

Thanks in advance,

August 24, 2000 Thiruvaiyaru -- Thanks for the question regarding "Dropping / Altering a Directory ", version 8.1.6
You Asked
Tom,

Thanks for your help on SQL*Net Connections.

When I try to drop a directory it gives the
following error :-

drop directory test_dir;
*
ERROR at line 1:
ORA-04043: object TEST_DIR does not exist

I checked the dba_directories view and the
directory_name was in the same case(lower) as I
used in the drop statement.
I tried dropping it through sys and system
and as well as the user that uses the directory.
It gives the same error.

Also, Is there a way to alter a directory.

It would be useful if you can give me some
suggestions.

Thanks
Sai
and we said...
If the directory is stored in lower case, then :

SQL> drop directory "test_dir";

You need to quote the identifier to preserve the case.  When it
was created, they must have issues:

SQL> create or replace directory "test_dir" ....;

There is no alter - you can create or replace the directory
(nothing to alter but the directory is points to and create or
replace covers that)
August 24, 2000 Irshad -- Thanks for the question regarding "Creating additional database instances on UNIX.", version 8.0 & 8.1
You Asked
Hi,

Is there an equivalent of Instance Manager ( of NT ) on UNIX
(Sun Solaris 2.6). All I want to do is to create additional
databases on a UNIX machine. From the documents I have read that
in order to create a new database, we have to create a new
instance first that shall ultimately mount that new database.
Correct me if I am wrong please.

Also once I create additional databases, how do I connect to a
specific database. Do I have to change the environment variables
everytime.

On NT, I have done this using Instance Manager ( oradim80), but
how to go about UNIX.

Thanks very much.

Irshad.
and we said...
In Oracle8.0, you can use the character mode installer to create
a new database or a new database instance.

In Oracle8i, you can use the dbassist tool (as you would on NT)
to create a new database|instance.

To connect to a specific instance, yes, you either change the
ORACLE_SID or use a Net8 connect string on the connection and
sqlnet into the database.
August 24, 2000 Friedl -- Thanks for the question regarding "OCI", version 8.1.5
You Asked
Where can i find some detailt information about OCI.
Some Companies have the possibilitie to connect to
my central Oracle Database over OCI.

I know that OCI is Oracle call interface but that´s all.

Older Programms used ODBC or SQLNET.

What are the advantage an disadvantage off OCI.
And How can somebody transfer some Data over OCI from there
data pool to my Central database.

Thanks

Friedl
and we said...
OCI predates ODBC by some number of years actually -- and to
compare OCI to SQLnet is like comparing apples and oranges.

OCI is a C call level interface (api) to Oracle.  ODCB is a C
call leverl interface as well.  OCI and ODBC are very similar
with the exception that ODBC is typically built as a layer on
TOP of OCI - OCI is our direct API.

To read about OCI, what it is, how to use it, see:
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76975/toc.htm
...
August 24, 2000 Keith -- Thanks for the question regarding "Primary and Foreign Keys", version Oracle8i
You Asked
If changing data in a primary key, is there any way to have the
data in a foreign key referencing that primary key to be changed
automatically to reflect the change of the data in the primary
key?
and we said...
Well, if you are changing it -- its not really a primary key.
Primary keys are imutable -- they are not ever supposed to
change....

If the foreign key is deferable -- (you specified that upon
creation) you can update the "primary key" and then update the
foreign key.  Its hard to do in a trigger -- but it can be done.

See
http://osi.oracle.com/~tkyte/update_cascade/index.html
for a way to do it via triggers if you are interested (it
generates the code for you -- you just tell it the parent table
you want update cascade support for).
August 24, 2000 Sanjeev -- Thanks for the question regarding "ALTERNATIVE SOLUTION for Standby Database", version 8.1.5
You Asked
Tom:

In one of Oracle Documentation I found Oracle Parallel Server is
a ALTERNATIVE SOLUTION for Standby Database. Can you tell me
conceptually, how Oracle Parallel Server is going to work as a
ALTERNATIVE SOLUTION of Standby Database. And for doing this
what kind of Oracle Parallel Server configuration is required.

Regards,
Sanjeev
and we said...
See
http://www.oracle.com/oramag/oracle/00-May/o30tom.html
I wrote up an article on this not too long ago.
August 24, 2000 Fernando -- Thanks for the question regarding "check list", version 8i
You Asked
estoy planeando una base de datos para posteriormente crearla ..
mas que una pregunta .. me gustaria me ayudaras con un chek list
para la planeacion y creacion de la base de datos. Gracias
and we said...
The things you need to consider prior to creating the database,
and the steps to create the database are to be found at:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76956/create.htm#997674
...
August 25, 2000 -- Thanks for the question regarding "Particiones y/o volumenes logicos", version 8i
You Asked
Tom ... voy a crear una base  de datos sobre unn sistema
operativo HP-UX pero tengo duda sobre las particiones y/o
volumenes logicos .. si son diferentes cual es la mejor opcion?
and we said...
The difference between a raw partition and a logical volume will
be neglible today.  Unless you are using OPS, I would suggest
using a logical volume manager for its flexibility.  Many volume
managers allow you to configure the disks as if they were raw
partitions even, adding more flexibility.
August 25, 2000 kaiquan -- Thanks for the question regarding "check the performance of the website and how many people have visited the website", version oracle8.1.6 & oas4.0.8
You Asked
Dear sir,
Please tell me how can I check the performance of the website
and how many people have visited our website.

My database is oracle8.1.6 and the oas is 4.0.8 for unix.

I sincerely appreciate your help.

Best regards

John Chen
and we said...
Well, for how many people have visited -- you can check your
logs.  OAS stored at least a record per visit in a log file in
the OS.  You can even load those into a database using their
tools and analyze the data as well.

See
http://www.olab.com/doc/books/admin/logging.htm

See
http://www.olab.com/doc/books/perf/dms.htm
for monitoring performance.
August 25, 2000 Anand -- Thanks for the question regarding "Database Backup on Linux", version 8.1.5 under Linu x
You Asked
We have a production database on our aol web server, we are
using it for storing data of e-commerse site.
I want to take off - line backup with minimum downtime.
Using export complete database one time and a single tablespace
every day.
How to achive this and optimally how much time it should take .
Suggest the best strategy.
Specification : 8.1.5 Oracle, on 2- processor (intel) with 500
mhz on linux 6.2.

Thanks in advance
Regards
Anand.
and we said...
1) export is not a backup tool.  Do not use export for
backups.

2) you don't need to take a database offline to back it up.
Every production database must be running in ARCHIVELOG mode (if
not, you will LOSE data someday -- I can assure you of that).
When running in archive log mode, you can backup the database
"hot", while it is running.  There should be no downtime
whatsoever for backing up.

Please see
http://technet.oracle.com/doc/oracle8i_816/server.816/index.htm
the backup and recovery section for details.  Doing a hot backup
is not any more complex or involved then a cold backup.  The
RMAN utility can be used to automate all of the backup as well
(or you can just use TAR or DD as many -- self included -- still
do after placing the tablespace in backup mode)
August 25, 2000 Satish -- Thanks for the question regarding "REGARDING CHANGE OF PASSWORD", version 8.0.5
You Asked
Somebody has changed the password of SYS. How do i reset it
since nobody knows the existing password ? How do we change the
password of SYS without knowing the existing password.
and we said...
o if you can "connect internal", you can change it via "alter
user sys identified by newpw".  If you get prompted for the
internal password -- well that'll basically be the sys password
so that won't work

o log in as any DBA.  They have the ALTER ANY USER priv and can
alter user sys identified by newpw.
August 25, 2000 Rupali -- Thanks for the question regarding "Creating Table same as existing table.", version Oracle 8.1.5
You Asked
If you create table with the following command

Create Table emp1 as select * from emp where 1 = 2;

It creates a table emp1 same as emp with no rows in it.  But in
this way

1.  emp1 doesnt have the primary key which is there in emp.
2.  if there are some not null constraints in emp, other
    than primary key in emp, then they get created same as emp
    in emp1.

Kindly tell me why so..

And can we avoid this and get Primary Key also generated at the
same time.
and we said...
There is no command "create table like...".

One method that work if you like:

o exp userid=u/p tables=emp rows=n
o SQL> rename emp to emp_hold
o imp userid=u/p full=yes
o SQL> rename emp to emp1
o SQL> rename emp_hold to emp

EXP will get all indexes, constraints, triggers, etc, etc,
etc...  Beware however if you used NAMED constraints

For example, if you:

  1* create table t ( x int, constraint t_pk primary key(x) )
ops$tkyte@8i> /

When you goto import you'll get:

....
. . importing table                            "T"          0
rows imported

IMP-00017: following statement failed with ORACLE error 2264:
 "ALTER TABLE "T" ADD  CONSTRAINT "T_PK" PRIMARY KEY ("X") USING
INDEX PCTFRE"
 "E 10 INITRANS 2 MAXTRANS 255 STORAGE(INITIAL 524288)
TABLESPACE "UTILS" ENA"
 "BLE NOVALIDATE"
IMP-00003: ORACLE error 2264 encountered
ORA-02264: name already used by an existing constraint

About to enable constraints...
IMP-00015: following statement failed because the object already
exists:
 "ALTER TABLE "T" ENABLE CONSTRAINT "T_PK""
Import terminated successfully with warnings.

So, in the same schema there is no "perfect" way to do it as it
involves renaming lots of other things (thats why we have no
"create table like...." -- there are lots of things that would
have to be renamed and we don't do that)...

If you let constraints name themselves (eg: if you had used

create table t ( x int primary key )

) you will not hit the above issue.
August 25, 2000 Reji -- Thanks for the question regarding ""Random Sample"", version 8.1.6
You Asked
Tom:
    I saw your explanation about how to get random set of
    data.  Would you please explain how this "Sample()"
    function works?

-Thx
-Reji
and we said...
Sure, in Oracle8i (8.1 and up) you can place SAMPLE onto some
queries.

SAMPLE ( n )       -- samples N% of the rows
SAMPLE BLOCK ( n ) -- samples data from N% of the blocks of the
                      table
You can specify SAMPLE only in a query that selects from a
single
table.

Useful to see the cardinality of a column of a big table or just
to get a random sample of the data from a table.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76989/ch4l2.htm#13327
for more info.
August 25, 2000 Daljeet -- Thanks for the question regarding "Function Index not being used", version 8.1.5
You Asked
Hello,
I have the following query:
    SELECT /*+ INDEX(ALBUMCONFIGHEADER ) */
    ALB.PRODUCTCODE "pid", ALB.TITLE "name",
    TRUNC(ALB.OURPRICE + (ALB.OURPRICE *
(MNET_OLS_CART.getVATPercent/100)), 2) "price",
    TRUNC(ALB.LISTPRICE, 2) "listPrice", ALB.ARTISTBANDNAME
"artistName",
    MNET_OLS_CAT.getGenre(ALB.GENRE) "genre", ALB.STYLE
    "style", ALB.LANGUAGE "language", TO_CHAR(ALB.RELEASEDATE,
'mm/dd/yyyy') "releaseDate",
    ALB.DESCRIPTION "description", ALB.ARTISTBANDCODE
"artistBandCode",
    ALB.DISCOUNTPC "discountPC", ALB.MUSICCOMPOSER
"musicComposer", ALB.LYRICIST "lyricist",
    ALB.SINGERNAME "singerName", ALB.RATING "rating",
MNET_OLS_CAT.getMediaType(ALB.MEDIATYPE) "mediaType",
    ALB.MEDIATYPE "mediaTypeCode", ALB.MEDIASETCOUNT
"mediaSetCount", MNET_OLS_CAT.getTimeDuration(ALB.DURATION)
"duration",
    ALB.IMAGE1 "image1", ALB.IMAGE2 "image2", ALB.COMMENTS
"comments", CURRENCY "currency"
    FROM
    ALBUMCONFIGHEADER ALB
    where
    Upper(ALB.ARTISTBANDNAME) like Upper('nomen%') or
    Upper(ALB.ARTISTBANDNAME) like Upper('% nomen%')
    ORDER BY ALB.TITLE||'-'||ALB.ARTISTBANDNAME
/

and the following index:
create index ach_upper_abn_idx on
albumconfigheader(upper(artistbandname));

The execution plan shows that the index is not being used for
the query:
Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=26590
Card=50388 Byt
          es=36329748)

   1    0   SORT (ORDER BY) (Cost=26590 Card=50388
Bytes=36329748)
   2    1     TABLE ACCESS (FULL) OF 'ALBUMCONFIGHEADER'
(Cost=961 Car
          d=50388 Bytes=36329748)

Thanx
Daljeet
and we said...
Your hint is wrong in the above case (AND you do not want to use
the index anyway on that one...)

Consider:

ops$tkyte@8i> alter session set QUERY_REWRITE_ENABLED=TRUE;
Session altered.

ops$tkyte@8i> alter session set QUERY_REWRITE_INTEGRITY=TRUSTED;
Session altered.

the above must be set at either the SESSION or init.ora level,
it not, this won't work

ops$tkyte@8i> create table ALBUMCONFIGHEADER
  2  ( artistbandname varchar2(25),
  3    x date, y number, z char(200) );

Table created.

ops$tkyte@8i>
ops$tkyte@8i> create index ach_upper_abn_idx
  2  on ALBUMCONFIGHEADER(upper(artistbandname));

Index created.

ops$tkyte@8i> set autotrace on explain

ops$tkyte@8i> select /*+ index(ALBUMCONFIGHEADER) */ *
  2  from ALBUMCONFIGHEADER ALB
  3  where upper(alb.artistbandname) like upper( '% blah%' )
  4  /

no rows selected

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=5
   1    0   TABLE ACCESS (FULL) OF 'ALBUMCONFIGHEADER' (Cost=1

That hint is wrong -- you renamed the table to be ALB --
therefore the hint was ignored (the table name should have been
ALB in the hint), lets just use CBO and see what it does:

ops$tkyte@8i> select /*+ FIRST_ROWS */ *
  2  from ALBUMCONFIGHEADER ALB
  3  where upper(alb.artistbandname) like upper( '% blah%' )
  4  /

no rows selected

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=HINT: FIRST_ROWS (Cost=1
   1    0   TABLE ACCESS (FULL) OF 'ALBUMCONFIGHEADER' (Cost=1

Still full scans -- why -- it saw the leading %.  The index
will have to have each and every entry inspected to answer this
-- the index is not very useful here -- much better to full
scan.  Remove the leading % and watch:

ops$tkyte@8i> select /*+ FIRST_ROWS */ *
  2  from ALBUMCONFIGHEADER ALB
  3  where upper(alb.artistbandname) like upper( 'blah%' )
  4  /

no rows selected

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=HINT: FIRST_ROWS (Cost=1
   1    0   TABLE ACCESS (BY INDEX ROWID) OF 'ALBUMCONFIGHEADER'

   2    1     INDEX (RANGE SCAN) OF 'ACH_UPPER_ABN_IDX' (NON-

Now it says "index will be useful, lets use it.  You can also
hint it to use your index with the leading percent via:

ops$tkyte@8i> select /*+ index(ALB) */ *
  2  from ALBUMCONFIGHEADER ALB
  3  where upper(alb.artistbandname) like upper( '% blah%' )
  4  /

no rows selected

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=5
   1    0   TABLE ACCESS (BY INDEX ROWID) OF 'ALBUMCONFIGHEADER'

   2    1     INDEX (RANGE SCAN) OF 'ACH_UPPER_ABN_IDX' (NON-

which is what you were attempting anyway...
August 25, 2000 -- Thanks for the question regarding "performance en OPS", version 8i
You Asked
Tom ... estoy usando la version 8i 8.1 y he leido que tiene un
modo especial de two-node-cluster.  La pregunta es OPS me reduce
el preformance en la base de datos?.  Es recomendable utilizar
esta opcion(two-node-cluster)?
and we said...
I think you are referring to the High Availability configuration
of OPS available in 8.1.6, see:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:262615352849
for info on that and pointers to more documentation.  If you are
interested primarily in high availability and have not designed
to take advantage of OPS (eg: partitioned the application in
some fashion across the nodes), this is a feature that would be
of interest to you -- yes.
August 25, 2000 Sudha -- Thanks for the question regarding "Returning a table from a procedure.", version 7.3
You Asked
Hi Tom,

Thanks for all your previous help. I have another question to
ask you. I need to create a procedure and show the display on
an ASP.

In the procedure I'm creating a cursor and selecting a few
records from a table according to a certain criteria.

Declare
  c1 cursor is select unit from case where unit like '2%';
  c1_rec varchar2(05);
Begin
  open c1;
  loop
  fetch c1 into c1_rec;
  exit when c1%notfound;
  dbms_output.put_line(c1_rec);
  end loop;
  close ci;
End;

This works fine on the SQL prompt, but I need to display the
output as a table. How do I create a table to store these values
and return this table as the out parameter in a procedure ?

I'm new to PL/SQL tables and somebody suggested to use that. How
do I go about it ? I need to use %columntype instead of
varchar2, number, etc. This is urgent !

Thanks is advance
Sudha
and we said...
see
http://osi.oracle.com/~tkyte/ResultSets/index.html
for the answer -- it is called a REF CURSOR in Oracle -- i have
an ASP example there.
August 25, 2000 Shruti -- Thanks for the question regarding "Shell scritps from OAS.", version 4.0.8.1
You Asked
Hi Tom,

I have shell script which I execute using URL format

rduxsl.micro.lucent.com/cgi-bin/printped.sh?100

Now I want add one more variable to the script. How do I pass it
in the URL?

Shruti

Shell script looks like as follows:

!/bin/ksh -f
/bin/echo Content-Type: text/plain
/bin/echo

#
#/home/modis/cgi-bin/dbup.sh
#

#
-----------------------------------------------------------------
------
# Filename:   printped.sh
# Purpose:
export LPDEST=lasereng;

# Set up the search paths:
        PATH=$PATH:/usr/local/bin
# Setup Oracle environment
        ORACLE_SID=slmod;            export ORACLE_SID
        ORAENV_ASK=NO
        . oraenv
        ORAENV_ASK=YES;             export ORAENV_ASK
#
sqlplus slmod/s1m0d @/oracle/cgi-bin/module.sql $1

/oracle/usr/run_rev120.cmd  /oracle/cgi-bin/module.tmp
/oracle/usr/noise4.cmd /oracle/cgi-bin/module.tmp
and we said...
If I have a shell script such as:

-----------------------------------------------
#!/bin/csh

/bin/echo Content-Type: text/plain
/bin/echo

/bin/echo $*
/bin/echo  ----------------------------
/bin/echo $1
/bin/echo $2
/bin/echo  ----------------------------
/bin/echo $QUERY_STRING
------------------- eof -------------------------

and run it with:
http://aria.us.oracle.com/cgi-bin/test.sh?100
I get:
100
----------------------------
100

----------------------------
100

as the output.  If I run it with:
http://aria.us.oracle.com/cgi-bin/test.sh?100+200
I get:
100 200
----------------------------
100
200
----------------------------
100+200

Just use the + to separate them..
August 25, 2000 Shahriyar -- Thanks for the question regarding "Data Import.", version 8i
You Asked
How can I populate a BLOB field in a table?
and we said...
Many ways.

SQLLDR can do it. see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:627223659651
and
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:392618837633
PLSQL can do it, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:482221538758
The above has a link to show how to do it in java as well using
streams...

In general, see:
http://technet.oracle.com/doc/oracle8i_816/appdev.816/index.htm
for lots of ways to do it in various languages...
August 25, 2000 Bala -- Thanks for the question regarding "Instance ", version 8.0.5
You Asked
What do you mean by Oracle Instance ? How will you differentiate
an Instance and a Database, can we have multiple instances up
and running at the same time.

Thanks
and we said...
To see what is meant by an instance vs database, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:533422350794
You can have >1 instance up and running at a time, yes (they'll
each have exactly 1 database mounted at any time)
August 25, 2000 Jane -- Thanks for the question regarding "alert file", version 7.3.4
You Asked
Tom:

I just checked the alert file of our database. I found we never
cleaned it since the startup of our database. The first record
was written in Jun. 1997. The file is 1.3mg now. Before I raise
this issue to my boss I need to know how often I should check
the alter file and how many days of records should be kept in
alert file.

I appreciate you help.

Jane
and we said...
Wow, only 1.3 meg?  Thats a pretty small alert log for that
long.  Mine is >10meg after 6 months...

You should check the alert log fairly regularly (every day
perhaps or more) to see if anything is wrong.  You should keep
as much as you want to keep.  At 10meg, I'm thinking about
"rolling" mine (rename it, we'll create a new one for you) and
compressing it.  I like to keep them around.

Unless you are really tight on space, I'd let it be for another
3 years...
August 25, 2000 wallacel -- Thanks for the question regarding "disk i/o", version 8.1.6
You Asked
Tom:

when I read tuning i/o part of oracle8i designing and tuning for
performance, it say that I need to analyze disk i/o,
such as reads/second, and writes/second,
my question is how do i know the value for those? by disk
vendor's document or by some kind of test?

Regards,
and we said...
Depends on your OS.  on Unix for example, sar, iostat, vmstat,
top, glance, and so on are tools we typically use to monitor
this.  On NT, its perfmon.

Before you analyze IO, I would start with analyzing my
applications -- see how they are doing (sql_trace, tkprof).
Work up to IO after everything else is tuned up.  No good to
optimize IO if they way you apps will access it is going to
change over time (cause you eventually must tune them if you
want to get the biggest bang for the buck)...
August 25, 2000 subhakar -- Thanks for the question regarding "pl/sql", version 8.1.6
You Asked
Hi Tom,

I have a table "t" containing the following data:
c
--
xx
xx
xx
yy
yy
zz
aa
bb

I was trying to modify the duplicate rows in the table by adding
a suffix, like in this ex. xx_1 xx_2 so the col values would be
xx, xx_1, xx_2
Well, I have written the code for this, but the problem Iam
facing is .... it's updating all the duplicate records including
xx. so, my out put is xx_1, xx_2, xx_3. Please advise....

Thanks in advance
Subhakar
and we said...
Well, in Oracle8i we can put a subquery anywhere a constant or
identifier would have gone, so we can do this in a simple
update:

SQL> select * from t;

C
------------------------------
xx
xx
xx
yy
yy
zz
aa
bb

8 rows selected.

SQL>
SQL> update (select c, (select count(*)
  2                       from t t2
  3                      where t2.rowid < t.rowid
  4                        and t2.c = t.c ) AS cnt
  5            from t
  6           where exists ( select null
  7                            from t t2
  8                           where t2.rowid < t.rowid
  9                             and t2.c = t.c )
 10         )
 11  set c = c || '_' || cnt
 12  /

3 rows updated.

SQL>
SQL> select * from t;

C
------------------------------
xx
xx_1
xx_2
yy
yy_1
zz
aa
bb

8 rows selected.

SQL>

works best if C is indexed of course...
August 25, 2000 William -- Thanks for the question regarding "PIM", version any
You Asked
I am looking for an address book/contact manger software that
can be run with oracle. It needs an easy to use interface with
pop-ups. Thank You
and we said...
Have you looked at
http://www.oraclesalesonline.com/ofs313/welcome.html
see also
http://yahoo.cnet.com/news/0-1007-200-2610115.html?pt.yfin.cat_fin.txt.ne
The calendar (has calendar, todo's, memo's, and address book)
that is part of Oracle Sales Online is also available as part of
http://www.oracle.com/fastforward/enterpriseportal/index.html
...


Subject | Article | Last Updated (East coast time)
SQL Loader | article only | Aug 28, 2000 07:23 am
rdbms questions | article only | Aug 28, 2000 09:49 am
Calling an external program from PL/SQL | article only | Aug 28, 2000 10:02 am
How to find whether patches are applied or not | article only | Aug 28, 2000 12:51 pm
select sum of count(*) | article only | Aug 28, 2000 12:59 pm
Transactions -- dirty read | article only | Aug 28, 2000 01:46 pm
raid | article only | Aug 28, 2000 02:32 pm
Advanced Queues | article only | Aug 28, 2000 03:00 pm
About Online DB Backup | article only | Aug 28, 2000 03:04 pm
Query to retrieve the top 50 rows | article only | Aug 28, 2000 04:38 pm
Flat file | article only | Aug 28, 2000 04:43 pm
Calling PL/SQL procedure from Pro*C with a twist | article only | Aug 28, 2000 08:59 pm
Oracle Forms- how to populate a list item | article only | Aug 29, 2000 06:00 am
Getting incremental export of data | article only | Aug 29, 2000 06:04 am
How to get the IP address of a session in Oracle Server | article only | Aug 29, 2000 06:13 am
Unix Kernel Parameters | article only | Aug 29, 2000 06:15 am
performance tuning -- what does a "tuned" system look like. | article only | Aug 29, 2000 06:23 am
Page numbering | article only | Aug 29, 2000 06:25 am
dblinks and rollback segment | article only | Aug 29, 2000 08:56 am
Excel output | article only | Aug 31, 2000 07:50 am
Accessing a SQL server table from an oracle database trigger | article only | Aug 31, 2000 07:55 am
LOBs or Files ? | article only | Aug 31, 2000 08:20 am
OWA_UTIL.ident_arr and max size | article only | Aug 31, 2000 08:23 am
RE: Returning sequence numbers to a third party software tool | article only | Aug 31, 2000 08:30 am
shutdown transactional | article only | Aug 31, 2000 08:37 am
SQL*Loader Problem | article only | Aug 31, 2000 09:56 am
Cursors | article only | Aug 31, 2000 10:21 am
Latches, UTLBSTAT & UTLESTAT | article only | Aug 31, 2000 10:37 am
Can i call a Shell Unix commands from Pl/Sql or Sql Plus | article only | Aug 31, 2000 11:00 am
Getting Files into the Database? | article only | Aug 31, 2000 11:04 am
how to print in unix monitor? -- extprocs, printf and fprintf | article only | Aug 31, 2000 11:24 am
sql loader query | article only | Aug 31, 2000 11:44 am
Migration of 7.3.4 to 8.1.6 | article only | Aug 31, 2000 12:52 pm
Passing OS variables to the database | article only | Aug 31, 2000 01:22 pm
Oracle Database Size and tuning parameters. | article only | Aug 31, 2000 01:36 pm
create user | article only | Aug 31, 2000 01:38 pm
Instance shutdown with dispatcher | article only | Aug 31, 2000 03:54 pm
Migration | article only | Aug 31, 2000 03:59 pm
Problem with Sql Loader | article only | Aug 31, 2000 08:39 pm
Instalando con RAW | article only | Aug 31, 2000 09:06 pm
dbms_shared_pool | article only | Sep 01, 2000 08:12 am
developer -- forms 4.5 on win2k | article only | Sep 01, 2000 08:15 am
pl/sql | article only | Sep 01, 2000 08:20 am
SQLJ, checking oracle.sql.CHAR values | article only | Sep 01, 2000 11:26 am
Exporting to /dev/null | article only | Sep 01, 2000 11:36 am
performance tuning regarding OR | article only | Sep 01, 2000 04:46 pm
LOG MINER | article only | Sep 01, 2000 07:44 pm
IMPORTING THE DUMP INTO DIFFERENT DATABASE HAVING DIFFERENT LOGICAL STRUCTURE | article only | Sep 01, 2000 07:46 pm
exiting triggers and/or procedures | article only | Sep 01, 2000 07:55 pm
row(s) 1 - 49 of 49
August 28, 2000 Ashish -- Thanks for the question regarding "SQL Loader", version 8.1.5
You Asked
I have a ctl file look like this

  OPTIONS(rows=1)
  LOAD DATA
  INFILE *
  INTO TABLE A
  ( a   POSITION(1:10) ,
    b   "DECODE(:a,null,' '','select name from table b where c1
= :a)",
    c   "DECODE(:b,null,'N','Y')
)

I am having a problem when when there is a value in col a which
dosen't exists in table B so b is null , but somehow my c decode
always return be 'Y' it should return me 'N'.

Please advice
and we said...
Well, the problem is that

  c  "decode( :b, null, 'N', 'Y' )"

is applied at the same exact instant

  b  "decode( :a, ..... )"

is.  The :b in the decode for C is set by SQLLDR when it BOUND
the statement -- it is imutable and is not the actual value of B
when the insert is done.

You'll find that since B and C do not have positions, they
default to position(1:1), that is, the above is the same as:

c   position(1:1) "DECODE(:b,null,'N','Y')

hence, upon input -- :b will be whatever the first byte of A
was...  For example, I had:

begindata
1234567890

and :b had the value 1.

So, if you want C to be based on whatever B evaulates to, we
must replace refereces to :b with the function you apply to b.
It could look like this:

options(rows=1)
load data
infile *
replace
into table a
( a position(1:10),
  b "decode( :a, null, ' ', (select name from table_b where c1 =
:a))",
  c "decode( decode( :a, null, ' ', (select name from table_b
where c1 = :a)), null, 'N', 'Y' )"
)
begindata
1234567890

That loads

ops$tkyte@ORA8I.WORLD> select * from a;

A                         B           C
------------------------- ----------- -----------
1234567890                            N

as expected.
August 28, 2000 Fergal -- Thanks for the question regarding "rdbms questions", version Oracle8.1.5
You Asked
I'm an Informix DBA of around ten years and going through the migration period
to Oracle. I've gone through all the rdbms training and even some advanced stuff
in terms of the Oracle instance/recovery. I have a few jibes from a UNIX point
of view only. Perhaps if you get a chance you could you comment on them. I would
very much prefer if you did not comment on them in terms of the general public.
I don't care for the 'out there' feeling.

1. Is there no nice utility to examine your database tables in terms of columns,
number of rows etc. All you get is plsql and you have to take everything out of
the dictionary?

2. How can you tell if your instance is OnLine. You can 'ps -ef | grep pmon*'
but again that's horrible. Any nice status utility?

3. How can you check your chunks from UNIX i.e I've 30 datafiles and they take
up so much space and I have this much left?

4. I've yet to create some datatables using RAW?

5. What was the reasoning behind one instance per database. In informix you can
have multiple databases per instance?

That's it for the moment. Thanks for your help.

Just by the way. Do you regard yourself as a Technologist. Who makes these words
up - technologist isn't even an English word. I refer you to July/August oracle
magazine page 17.

Kind Regards,

Fergal.
and we said...
1) There are a variety of tools that show you the schema from Designer 2000 to
the database tool Oracle Enterprise Manager (OEM).  You should have OEM as part
of the database and it has a schema manager in it.  WebDB does it on the web via
HTML as well.  The SQLPlus describe command will give you a cursory overview as
well.

2) See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:538422444709
for a method.  I recommend using OS Authentication accounts for things like
this.  the PS thing is extremely viable as well, ipcs does the same.  Typically
though, people use OEM which does this monitoring for you -- it monitors
multiple instances on one console.

3) Don't know exactly what you are looking for here.  Do you want to know how
much space your datafiles take up versus the amount of space left in the OS?
The view DBA_DATA_FILES shows you all of the information about the datafiles
associated with the database.

4) Don't think of raw as being special and you'll be OK.  Create tablespace
mytablespace '/dev/rdisk/.....' size ....   Just use the device name.  It is no
different then "cooked".  See your OS admin guide for specifics.  For example,
the Solaris guide states:

<quote>
Raw Device Setup
Keep in mind the following items when creating raw devices:

n When creating the volumes, ensure that the owner and group are oracle and dba,
respectively.

n The size of an Oracle datafile created in a raw partition must be at least two
Oracle block sizes smaller than the size of the raw partition.
</quote>

So, if you have a 10gig device and an 8k blocksize, your size above would be
10485744k (10 * 1024 * 1024 - 16)

5) Actually, you have it backwards.  It is one database per instance.  A
database may have many instances. See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:533422350794
for clarification.

In Oracle, we use a schema much in the way Informix used "database".  In
Informix -- unless you were using "MODE ANSI" databases (which in my experience
very very few people did) you typically never used a schema name in your queries
and such.  Rather, you picked a "database" and would then run queries against
unqualified database objects (eg: select * from T, not select * from OWNER.T).
In Oracle you either:

  o select * from OWNER.t and treat OWNER much like a database
    in Informix

  o alter session set current_schema=OWNER and then you can
    select * from T which will be intrepreted the same as
    select * from OWNER.T (so setting the current_schema is
    much like picking a database).

6) Not that it is relevant, not that it is important, but ... actually, going to
http://www.m-w.com/netdict.htm
and putting in my job title "technologist" I find:

Main Entry: tech·nol·o·gy
Pronunciation: -jE
Function: noun
Inflected Form(s): plural -gies
Etymology: Greek technologia systematic treatment of an art, from technE art,
skill + -o- + -logia -logy
Date: 1859
1 a : the practical application of knowledge especially in a particular area :
ENGINEERING 2 <medical technology> b : a capability given by the practical
application of knowledge <a car's fuel-saving technology>
2 : a manner of accomplishing a task especially using technical processes,
methods, or knowledge <new technologies for information storage>
3 : the specialized aspects of a particular field of endeavor <educational
technology>
- tech·nol·o·gist /-jist/ noun

You can go all of the way back to at least 1913 to find it in the dictionary:
http://machaut.uchicago.edu/cgi-bin/WEBSTER.sh?WORD=technologist
that is Websters unabridged where they define it as:
"... One skilled in technology..."

So, it would appear that technologist is in fact an english word.  Goto
http://www.google.com/
and
search for it.  For a word that is not a word -- it sure is used lots in peoples
job titles.

So, yes, I regard myself as a technologist.
Review & Followup
Rating: 5
Why People become so Agressive..? October 11, 2002
Reviewer: Gururaj Kulkarni from Bangalore, Karnataka India
Tom,

I really..really appreciate the work you are doing now.

I am pointing to your 6th answer, and wondering why people ask/discuss such
things. Why do you take trouble to answer such people?

With Regards

August 28, 2000 Ramesh -- Thanks for the question regarding "Calling an external program from PL/SQL", version 8.1
You Asked
can we call an external program(a new process) from a PL/SQL
procedure. if so, How? are there any limitations in making those
calls ?
and we said...
See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adg11rtn.htm#1656
for all of the details.

There are some limitations with regards to this (eg: the
external process must reside on the same machine with the
database) but not many.  That section outlines the architecture
and the guidelines for building external routines.
August 28, 2000 Ramana -- Thanks for the question regarding "How to find whether patches are applied or not", version 8.1.5
You Asked
Hi,
  My system is running on oracle version 8.1.6 on sun solaris
2.6. How to find which patches are applied?
Thanks
Ramana
and we said...
$ showrev -p

shows the OS patches.  In Oracle -- the "patch" number is the
full version string of the database (eg: you really have 8.1.6.0
or 8.1.6.1 or 8.1.6.2 -- there may even be a fifth digit in some
cases).

The owhat command can be used on various executables and
libraries within Oracle as well for one off patches thay may or
may not have been applied.  for example:

$ owhat bin/oracle
August 28, 2000 Thiruvaiyaru -- Thanks for the question regarding "select sum of count(*)", version 8.1.6
You Asked
Tom,

How do I do a sum of count(*) on a table , for eg :-

I have a table called order and I do the following :-

select oid,count(*) from order
group by oid order by 2;

and the result is :-

oid      count(*)
====     ========
111        7
112        7
113        8
114        8
115        12

What I need here is I want to display the same results
and I want to sum the count(*) for same values , ie.
sum of 7 = 14,sum of 8 = 16 , sum of 12 = 12.
I even tried  :-
break on count(*) on order
compute sum of count(*) on order

Doesn't seem to work. Your help would be greatly
appreciated.

Thanks
Sai
and we said...
Ok, if we start with:

scott@ORA8I.WORLD> select oid, count(*)
  2  from t
  3  group by oid
  4  /

       OID   COUNT(*)
---------- ----------
       111          7
       112          7
       113          8
       114          8
       115         12

we can get the sums of the like counts by doing this:

scott@ORA8I.WORLD> select cnt, sum(cnt)
  2    from ( select count(*) cnt
  3             from t
  4            group by oid )
  5   group by cnt
  6  /

       CNT   SUM(CNT)
---------- ----------
         7         14
         8         16
        12         12

and if they really needed to be merged in with the original
query, we could have this:

scott@ORA8I.WORLD> select oid, cnt1 cnt, sum_cnt
  2    from
  3    ( select oid, count(*) cnt1
  4        from t
  5       group by oid ) A,
  6    ( select cnt cnt2, sum(cnt) sum_cnt
  7        from ( select count(*) cnt
  8                 from t
  9                group by oid )
 10       group by cnt ) B
 11   where cnt1 = cnt2
 12  /

       OID        CNT    SUM_CNT
---------- ---------- ----------
       111          7         14
       112          7         14
       113          8         16
       114          8         16
       115         12         12
Review & Followup
Rating: 5
DBA May 13, 2001
Reviewer: Pauline from U.S.A.
Very good example.

August 28, 2000 Keith -- Thanks for the question regarding "Transactions -- dirty read", version Oracle8i
You Asked
Say you have user A and user B accessing a database at the same
time. User A makes an update to the database but does not
commit. Is there any way to allow user B to see this update
without user A commiting the update to the database? Thanks.
and we said...
No.

That is known as a "dirty" read and we never allow for those.
We support consistent reads only.  Dirty reads are how some
other databases purport to give you "non-blocking reads".

We don't do that.
August 28, 2000 wallacel -- Thanks for the question regarding "raid", version 8.1.6
You Asked
Tom:

I have some question regarding RAID.
first of all, most important question. for simplify,can I
consider RAID device just like normal disk and follow the
oracle's document regarding Normal disk how to put datefile
in multiple disk, how to put multiple member of redo log member
in redo log group , etc.

2.although RAID 0 provide the best read and write performance
but oracle don't recommand it because it is not a true RAID
system. however I think RAID 0 should proveid better performance
than normal disk regarding read and write. so I just consider
RAID 0 device as normal disk and follow oracle's recommand
regard normal disk, is that correct?
and we said...
1) yes.

2) raid 0 is striping and we like that.  It provides no
protection against failure.  We would rather use hash partitions
then raid stripes -- this is true -- but only because of the
reduced downtime in then event of a failure, faster recovery and
the opportunity for partition elimination.  None of which is
possible with just raid 0.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:359617936136
for more info.
August 28, 2000 Kevin -- Thanks for the question regarding "Advanced Queues", version Oracle8i v8.1.6
You Asked
Hello Tom,
Currently I have a set of download, process and storage daemons
written in perl.
The daemons know when to start a download, process daemons start
processing downloaded data when they see a DOWNLOAD_SUCCESS
flag(which is simply a file). If the file exists the process
phase starts. Similarly, the storage phase starts when a
PROCESS_SUCCESS flag (i.e. file) exists.

I am converting all the download, process and storage scripts to
java to be ran as stored procedures within the Oracle server.

I am also looking for a way to use Oracle for the scheduling of
downloads, processing and storing of data.

I have been looking at the DBMS_JOBS and DBMS_AQ packages.

My question is, how can I use queues to start a phase?
It seems to me that a queue message can be used as the flags but
another program would have to be running in the background
similar to the daemons I have now.

Do you have any suggestions on how to go about this conversion?
I have seen in the Oracle documentation a few examples on how to
create queue tables and dequeue and enqueue messages, but I am
uncertain how to use them to start a stored procedure. ???

Any help would be greatly appreciated :)
and we said...
Well, you would not use queues to start a stored procedure to
process the queue.

As you have surmised -- the queues are built so that some
consumer, somewhere is out there running and getting messages
from it.  It is up to you to get that "something" up and running
"somewhere".

What sounds most applicable for you is to use dbms_job to
schedule your procedure to run on a recurring basis.  This
procedure would either look for a queue message OR for the
existence of this file in the OS (up to you -- either works).
It would then do its thing.  You could have your procedure look
every N minutes or so for this file.

Otherwise, you would have to have a session going external from
the database that is blocked on the queue waiting for the
message (as you thought).
August 28, 2000 Sridharan -- Thanks for the question regarding "About Online DB Backup", version version 8.0.1.4
You Asked
Sir,

I am new to the oracle db.  I would to share my thought with
you, could you please help me out.

What online backup does and what are their features.?

What is tablespace and datafile?

Expecting your reply at the earliest.

Thanking you,

V.S.Iyer
and we said...
Online backup means you can backup the database while people are
still reading and writing it -- there is no impact to the end
users.

A tablespace is what holds our objects -- its a container of
sorts.  A table is created in a tablespace.  An index is created
in a tablespace.  A rollback segment is created in a tablespace.
 Every object (segment we call them) belows to a tablespace.

A tablespace on the other hand is physically made up of files.
These are the datafiles.  A tablespace may have 1 or more
datafiles associated with it.  This is where the data is
physically stored.

I will refer you to the server concepts manual now.  I would
strongly urge you to read this one from cover to cover.  If
you do -- you will have a very good broad understanding of
Oracle the database and many of its abilities.
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/toc.htm
...
August 28, 2000 swaroop -- Thanks for the question regarding "Query to retrieve the top 50 rows", version 7.3.4.4
You Asked
Hi,
    Please help me rewrite the query to select only the top 50
rows for each HCO.  Thanks.

swaroop
    set pagesize 15000
    set heading off
    Column TITLE Format A50
    Column HCO Format A50
    Column REQUESTS Format 99999
    BREAK ON HCO SKIP PAGE
    select substr(hco_name,1,50) HCO ,substr(object_title,1,50)
TITLE, count(request_count) REQUESTS
    from dm_request_fact a, dm_date_dim b, dm_visit_dim c,
hco_domain_dim d
    where report_flag = 'Y'
    and c.referring_domain = d.hco_domain
    and     object_title is not null
    and  InitCap(object_title) not in ('Search', 'Error 404',
'Search Result')
    and  a.dm_visit_dim_id = c. dm_visit_dim_id
    and  a.dm_user_dim_id = c. dm_user_dim_id
    and  a.dm_date_dim_id = b.dm_date_dim_id
    and  Month_name = InitCap('&Month')
    and     year = &yr
    group by substr(hco_name,1,50),object_title
    order by 1,3 desc;
    spool off;
and we said...
In 7.x, you'll probably find this easiest via a package, 'temp'
table and a cursor.  For example, I used ALL_OBJECTS and a query
like:

select owner, object_type, count(*) from all_objects
group by owner, object_type
order by 1, 3
/

as my test query.  I want the N top items created for each owner
(just like your query).  In order to do this, i set up a table:

tkyte@ORA734.US.ORACLE.COM> create table temp
  2  as
  3  select owner, object_type, 0 cnt from all_objects where
1=0;

Table created.

That is my result set...  I have a package then to manipulate
it:

tkyte@ORA734.US.ORACLE.COM> create or replace package report_pkg
  2  as
  3      type rc is ref cursor;
  4
  4      procedure do_report( p_cursor in out rc,
                              p_num_to_keep in number );
  5  end;
  6  /

Package created.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> create or replace package body
report_pkg
  2  as
  3
  3  procedure do_report( p_cursor in out rc,
                          p_num_to_keep in number )
  4  as
  5      l_last_owner  temp.owner%type := 'xxxxxx';
  6      l_counter     number;
  7  begin
  8      insert into temp
  9      select owner, object_type, count(*)
 10        from all_objects
 11       group by owner, object_type;
 12
 12      for x in ( select rowid rid, owner
 13                   from temp
 14                  order by owner, cnt DESC )
 15      loop
 16          if ( x.owner <> l_last_owner ) then
 17              l_counter := 1;
 18              l_last_owner := x.owner;
 19          elsif ( l_counter >= p_num_to_keep ) then
 20              delete from temp where rowid = x.rid;
 21          else
 22              l_counter := l_counter+1;
 23          end if;
 24      end loop;
 25
 25      open p_cursor for select * from temp
                           order by owner, cnt;
 26      delete from temp;
 27  end;
 28
 28  end;
 29  /

Package body created.

The interesting thing in that procedure is:

o it fills the temp table with the entire answer
o it removes the rows we are not interested in
o it opens a ref cursor on the remaining rows
o it DELETES all of the rows.

The ref cursor will still have our answer and outside of this
procedure -- the table appears EMPTY always -- no need to manage
it -- no concurrency issues at all.

This works because of our multi-version read consistency model.
The result set of the cursor is pre-ordained at the time it is
opened -- so even though TEMP is empty -- the cursor is full
(and will remain so until you commit at which time it MIGHT get
an ORA-1555 if you fetch from it -- but maybe not, depends on
how big your rollback is)

Now I can use it like this:

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> break on owner skip 1
tkyte@ORA734.US.ORACLE.COM> variable x refcursor
tkyte@ORA734.US.ORACLE.COM> exec report_pkg.do_report( :x, 50 )

PL/SQL procedure successfully completed.

tkyte@ORA734.US.ORACLE.COM> print x

OWNER                          OBJECT_TYPE         CNT
------------------------------ ------------ ----------
PUBLIC                         SYNONYM             332

SCOTT                          TABLE                 2

SYS                            PROCEDURE             3
                               TABLE                 6
                               PACKAGE              24
                               VIEW                178

SYSTEM                         TABLE                 2
                               VIEW                  2

TKYTE                          INDEX                 1
                               PACKAGE               2
                               PACKAGE BODY          2
                               TABLE                 2

12 rows selected.

That would show upto the first 50 by owner -- I don't have 50
so it shows the entire thing, now to limit it to show the code
works --

tkyte@ORA734.US.ORACLE.COM> exec report_pkg.do_report( :x, 2 )

PL/SQL procedure successfully completed.

tkyte@ORA734.US.ORACLE.COM> print x

OWNER                          OBJECT_TYPE         CNT
------------------------------ ------------ ----------
PUBLIC                         SYNONYM             332

SCOTT                          TABLE                 2

SYS                            PACKAGE              24
                               VIEW                178

SYSTEM                         TABLE                 2
                               VIEW                  2

TKYTE                          PACKAGE               2
                               TABLE                 2

8 rows selected.

and I get the top 2 (if you have 2) of each....

You would create the table and package ONCE in your database --
your report would just call the procedure and print the ref
cursor...
August 28, 2000 Kevin -- Thanks for the question regarding "Flat file", version 8.1.5
You Asked
I have to update some rows in TABLE EMP as batch mode.
To provide re-run of this batch process, I have to extract some
rows from EMP table.
I try to use "Select * from emp where emp_no > 3000" to get flat
file. And want to use SQL* loader to reload those rows.
When I issued "Select * ..." to get flat file, some of the
columns not be populated because it has null value.
I do not know how to handle those null valued columns when I get
flat file.
OR ELSE would you give me information "what is the best way to
get some rows from EMP table?"
Thanks. KEV.
and we said...
Easiest method would be to

create table nologging HOLD_MY_EMP_DATA as
select * from emp where emp_no > 3000;

and then you can just:

insert into emp select * from hold_y_emp_data;

to "restore" or "reload" the data.  Short of that, use export
since you have 8.1 and in 8.1 and up, export supports a where
clause.

$ exp .... tables=emp 'query=where emp_no>3000'

and export those rows.  Later, you can

$ imp .... full=y ignore=y

to import the rows again (ignore=y allows imp to continue after
the CREATE TABLE EMP fails since it already exists)....
August 28, 2000 Michael -- Thanks for the question regarding "Calling PL/SQL procedure from Pro*C with a twist", version 8.1.6
You Asked
I'm trying to code a generic Pro*C program that will take as
input a file containing lines that are actually a call to a
stored procedure writen in PL/SQL. The file would look something
like this:

procedure('arg1', 'arg2', ....)
procedure('arg1', 'arg2', ....)
....

I need the program to read in each line of the file and execute
the line in Oracle. Everything is complete except for that part.
I can't seem to find a way to do this. I'm limited by the use of
host variables in this context. Here's the pertinent code block:

while (fgets(fileline,LINE_LEN, fp) != NULL && fileline[0] !=
'\n') {
    /* Register sql_error as the error handler. */
    EXEC SQL WHENEVER SQLERROR DO sql_error("np_loaddemos2
error: \n");

    /* Call the stored procedure. */
    EXEC SQL EXECUTE
      BEGIN
         /* fileline needs to be here */
      END;
    END-EXEC;

    /* Commit the transaction. */
    EXEC SQL COMMIT;
}

The variable fileline contains the procedure call that I want to
execute. How can I do this within the PL/SQL block? or is there
another way?

Michael
and we said...
It can work like this with execute immediate:

main( argc, argv )
int argc;
char *  argv[];
{
char        oracleid[50] = "scott/tiger";

varchar     sql[255];
int         cnt;

    EXEC SQL WHENEVER SQLERROR DO sqlerror_hard();
    EXEC SQL CONNECT :oracleid;

    sprintf( sql.arr, "begin %s; end;",
                      "dbms_output.put_line( 'Hello World' )" );
    sql.len = strlen(sql.arr);

    EXEC SQL EXECUTE IMMEDIATE :sql;

    printf( "Done...\n" );
}

replace my call to dbms_output with your "filename" variable and
away you go....
August 29, 2000 sing -- Thanks for the question regarding "Oracle Forms- how to populate a list item", version 8.0.6
You Asked
Tom,

HOw do I populate a list item in Forms.
I am working with Oracle forms 6i.

Thanks,
sing
and we said...
You can add list elements by adding elements one at a time or by
populating a list item with values contained in a record group.
You can add values to a list item by using these built-in
subprograms:

o ADD_LIST_ELEMENT
o POPULATE_LIST
August 29, 2000 santhosh -- Thanks for the question regarding "Getting incremental export of data", version 8.1.5
You Asked
Hi
Suppose I have a production database. from this database i need
to take data from a tabble x every weekend in a flat file. how
can i do it so that every weekend only fresh rows(those whixh
are inserted betweend prevvious and current week)are taken into
this flat file.
Kindly tell which will be the if that can done with follwing
utlities and if yes then which will be the best utility for this
among
1.exp or
2.sqlldr or
3.writing in a spool through select statment.

Note: this table X does not have a time field.
and we said...
None of the above.

There are no timestamps kept at the row level for any data.  In
order to achieve what you want -- you will have to do something
like on of the following:

o place a timestamp column in the table -- have it maintained by

  a trigger

o create a snapshot log on the table.  This will create another
  table that holds the primary key or rowid and the DML
operation
  (I)nsert (U)pdate or (D)elete that took place on that row.
  You can use this log to identify rows for I and U and select
  them out via (select * from T where pk in ( select pk from
  the_snapshot_log) ).  You can then purge the log.  Do this
  all in a serializable transaction to ensure integrity.

o don't use a flat file format, rather use RMAN to create a
  block level incremental backup of the tablespace.
August 29, 2000 alvaro -- Thanks for the question regarding "How to get the IP address of a session in Oracle Server", version Oracle Server 7.3.4.0.0
You Asked
Hi Tom,
I'm building a trigger for auditing an aplication.
This triggers stores in a table information about the users who
changes the data in some tables.
I've gotten the most information by means of the table V$session
and the function USERENV, but I don´t know How I can get the IP
address of the session who chance the data.
If I can get more information about the user, I wish know it !

Could you help me , please
and we said...
In 7.3 as you have, you may

o enable audit_trail=true in the init.ora
o audit connects

Then, a query such as:

sys@ORA734.US.ORACLE.COM> l
  1  select a.username, b.comment$text
  2  from v$session a, aud$ b
  3  where a.audsid = b.sessionid
  4* and a.username = 'SCOTT'
sys@ORA734.US.ORACLE.COM> /

USERNAME             COMMENT$TEXT
-------------------- ----------------------------------------
SCOTT                Authenticated by: DATABASE; Client
                     address:
                     (ADDRESS=(PROTOCOL=tcp)(HOST=138.2.5.206
                     )(PORT=32889))

will return this additional information.  To get the right row
from aud$ for the current session in a trigger, you would code:

select * from aud$ where sessionid=userenv('sessionid');

Note that you could just enable auditing, save the sessionid
into your own table and join to aud$ when you wanted the data as
well -- you don't need to copy it.

aud$ is owned by SYS.  See the admin guide for more details on
auditing in general.
August 29, 2000 db -- Thanks for the question regarding "Unix Kernel Parameters", version 8.0.6
You Asked
Hi Tom,
We have been running 8.1.5 on Sun Solaris 2.7 for
well four months.
One of our application requires 8.0.6.
I installed 8.0.6 on same server with different oracle home.

When I try to create database on 8.0.6, I got following error.

SVRMGR> startup pfile=initDB1.ora nomount;
ORA-07279: spcre: semget error, unable to get first semaphore
set.
SVR4 Error: 28: No space left on device
Additional information: 1

Is this is related to SYSTEM parameters problem.
If it is then, how come I did not get while I created several
instances on 8.1.5?

Thank you for your time and help.
/db
and we said...
Every instance you add needs more "stuff".  You added the straw
that finally pushed us over the limit.  See the admin and
install guide for Solaris for the settings you want.  They are
at:
http://technet.oracle.com/docs/products/oracle8i/doc_index.htm
also see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:454420165038
for more details.
August 29, 2000 wallacel -- Thanks for the question regarding "performance tuning -- what does a "tuned" system look like.", version 8.1.6
You Asked
Tom:

I have a very stupid question.

I have no idea what a successful tuned system look like,
can you give me a general idea how the configuration can support
what kind of application with what kind of performance.(an
example).

such as a bank system with application deposit and cash back,
with server x hz, with y disk, and can accept z concurrent
people concurrent access the system, or something like that.
so I can get a general idea.

I know every application different from each other a lot,
but I just want to know a very very general idea.

Thanks a lot.
and we said...
There is no general idea.  A successfully tuned system is on
that is supporting the necessary users within the alloted time
frame.

Every system can always be tuned to go a little faster -- there
is no end to that cycle.  You don't tune until you are done,
rather you are given a "finish line" to cross (X people doing Y
things concurrently for Z hours) and tune towards that.  When
you hit it -- you are done (you may never get there if X, Y or Z
are unreasonable of course...)
August 29, 2000 Devin -- Thanks for the question regarding "Page numbering", version 3.3 or 8.0 I have both
You Asked
I want to do a common task for page numbering.  I want it to
print out the total number of pages starting on the first page
in the format 'Page x of y'.  The page x part is no problem
using the built in SQL.PNO variable of the TTITLE or BTITLE.
However the total page count is giving me fits.

Please Help,

Devin M Gale
and we said...
You cannot do that with sqlplus.  It has no idea how many pages
are coming until they are done.  sqlplus works 1 row at a time
-- it does not pre-fetch the entire query and then print -- it
gets row 1, prints, gets row 2, prints and so on.

You cannot get there from here with sqlplus.
August 29, 2000 kasthuri -- Thanks for the question regarding "dblinks and rollback segment", version 8.1.5
You Asked
Hi Tom,

 we have a stored proc as below which uses dblink:

 create or replace procedure sel_usr (p_usr_cur_out out
types.cursorType) as
 begin
 open p_usr_cur_out for
        select  ssn, pin
        from    usr_auth;
        union
        select  email_addr_uid,
                pswd
        from    vstr_auth@SLU1;
 end;

 Case 1: when i execute this procedure in a loop continuously
from with sqlplus, it functions normally

 Case 2: when i execute this procedure from with my java code,
there is a subsequent increase of use in the RBS & eventually it
goes too high to handle. Is there any particular reason for the
Rollback segment to get filled up? There is no major inserts or
updates going on at this time. we just executed the call from
java code in a while(true) loop.

We will be using dblinks extensively and would like to know if
this is a issue.

Thanks & Regards,
J.Kasthuri

Java Code:
class SelUsr
     {
       public static void main (String args [])
                          throws SQLException,
ClassNotFoundException
       {
           String driver_class =
"oracle.jdbc.driver.OracleDriver";
           String connect_string =
"jdbc:oracle:thin:@server:sid1";

           String query = "exec sel_usr_tst(?);";

           Connection conn;
        try {
           Class.forName(driver_class);
           conn = DriverManager.getConnection(connect_string,
"scott",
     "tiger");

          CallableStatement cstmt = conn.prepareCall(query);
          cstmt.registerOutParameter(1,OracleTypes.CURSOR);
          cstmt.execute();
          ResultSet rset = (ResultSet)cstmt.getObject(1);

           while (rset.next ()) {
             System.out.println( rset.getString (1) );
             System.out.println( rset.getString (2) );
        }
           cstmt.close();
        } catch (Exception e)
          {
         String err =e.toString();
            System.out.println(err);
     }

       }
and we said...
I cannot reproduce.  I created a database link -- put the tables
out there -- created the procedure and using the following java
program:

import java.io.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.*;

class SelUsr
{
public static void main (String args [])
throws SQLException, ClassNotFoundException
{
    String driver_class = "oracle.jdbc.driver.OracleDriver";
    String connect_string = "jdbc:oracle:thin:@aria:1521:ora8i";

    String query = "begin sel_usr(?); end;";
    // String query =
    //"begin update usr_auth set ssn=ssn+0; sel_usr(?); end;";

    String query2 = "select to_char( ubafil, '999999' ) || "+
              " to_char( ubablk, '999999' )  ||"+
              " to_char( ubasqn, '999999' )  ||"+
              " to_char( ubarec, '999999' )  ||"+
              " to_char( start_ubafil, '999999' )  ||"+
              " to_char( start_ubablk, '999999' )  ||"+
              " to_char( start_ubasqn, '999999' )  ||"+
              " to_char( start_ubarec, '999999' ) rbs_data "+
              "  from v$transaction "+
              "  where addr in ( select taddr  "+
              "                    from v$session  "+
              "                   where username = USER ) ";
    int recCnt;

    Connection conn;
    Class.forName(driver_class);
    conn = DriverManager.getConnection
                     (connect_string, "scott", "tiger");

    conn.setAutoCommit(false);

    System.out.println("   Curr   Curr   Curr   Curr  Start"+
                       "  Start  Start  Start ROWS" );
    System.out.println("   File  Block    Sqn    Rec   File"+
                       "  Block    Sqn    Rec FETCHED" );
    System.out.println("   ----  -----  -----  -----  -----"+
                       "  -----  -----  ----- ----------" );

    for( int i = 0; i < 100; i++ )
    {
        CallableStatement cstmt = conn.prepareCall(query);
        cstmt.registerOutParameter(1,OracleTypes.CURSOR);
        cstmt.execute();
        ResultSet rset = (ResultSet)cstmt.getObject(1);

        for( recCnt = 0; rset.next (); recCnt++ );
        cstmt.close();
        rset.close();

        Statement stmt = conn.createStatement();
        stmt.execute( query2 );
        rset = stmt.getResultSet();
        while( rset.next() )
            System.out.println( rset.getString(1) + " " +
                                recCnt + " rec" );
        rset.close();
        stmt.close();
    }
}
}

I have 2 "query" strings there.  The one I have uncommented is
yours.  When I run this I get output like:

$ java SelUsr
   Curr   Curr   Curr   Curr  Start  Start  Start  Start ROWS
   File  Block    Sqn    Rec   File  Block    Sqn    Rec FETCHED
   ----  -----  -----  -----  -----  -----  -----  ----- -------
      0      0      0      0     24    889   8526     17 61 rec
      0      0      0      0     24    889   8526     17 61 rec
      0      0      0      0     24    889   8526     17 61 rec
      0      0      0      0     24    889   8526     17 61 rec
      0      0      0      0     24    889   8526     17 61 rec
      0      0      0      0     24    889   8526     17 61 rec
.....

showing a transaction was started but no rollback ever used.
Only if I use the second one (commented above), with the update
in there do I start to generate lots of rollback:

$ java SelUsr
   Curr   Curr   Curr   Curr  Start  Start  Start  Start ROWS
   File  Block    Sqn    Rec   File  Block    Sqn    Rec FETCHED
   ----  -----  -----  -----  -----  -----  -----  ----- ------
     18   1601   8248     54     18   1601   8248     26 61 rec
     18   1601   8248     83     18   1601   8248     26 61 rec
     18   1602   8248     29     18   1601   8248     26 61 rec
     18   1602   8248     58     18   1601   8248     26 61 rec
     18   1603   8248      1     18   1601   8248     26 61 rec
     18   1603   8248     30     18   1601   8248     26 61 rec
     18   1603   8248     59     18   1601   8248     26 61 rec
     18   1604   8248      2     18   1601   8248     26 61 rec
     18   1604   8248     31     18   1601   8248     26 61 rec

You say "There is no major inserts or updates going on at this
time" but it looks like there must be something going on.  Since
the code you have above doesn't really compile (the plsql
doesn't) -- I'm assuming this is an extract from a much larger
test case.  Can you try my java program -- see how it behaves on
your system and add to it until you can reproduce the issue --
then we can track it down.

create or replace package types
as
    type cursorType is ref cursor;
end;
/

drop database link ora816dev.us.oracle.com
/

create database link ora816dev.us.oracle.com
using 'ora816dev.us.oracle.com'
/
REM i have the other table on the other system the dblink
REM points to, it is created in the same fashion as below:

drop table usr_auth;
create table usr_auth ( ssn int, pin varchar2(30) );
insert into usr_auth select user_id, username from all_users
where rownum  < 30;

create or replace procedure sel_usr (p_usr_cur_out out
types.cursorType)
as
begin
 open p_usr_cur_out for
        select  ssn, pin
        from    usr_auth
        union
        select  email_addr_uid,
                pswd
        from    vstr_auth@ora816dev.us.oracle.com;
 end;
/

declare
    rc types.cursorType;
    l_int  number;
    l_str  varchar2(255);
    l_cnt  number;
begin
    for i in 1 .. 100 loop
        sel_usr( rc );
        l_cnt := 0;
        loop
            fetch rc into l_int, l_str;
            exit when rc%notfound;
            l_cnt := l_cnt+1;
        end loop;
        close rc;

        for x in ( select to_char( ubafil, '999999' ) ||
                          to_char( ubablk, '999999' ) ||
                          to_char( ubasqn, '999999' ) ||
                          to_char( ubarec, '999999' ) ||
                          to_char( start_ubafil, '999999' ) ||
                          to_char( start_ubablk, '999999' ) ||
                          to_char( start_ubasqn, '999999' ) ||
                   to_char( start_ubarec, '999999' ) rbs_data
                     from v$transaction
                    where addr in ( select taddr
                                      from v$session
                                     where username = 'SCOTT' )
)
        loop
            dbms_output.put_line( x.rbs_data || to_char( l_cnt,
'9999' ) || ' records');
        end loop;
    end loop;
end;
/
August 31, 2000 Sanjay -- Thanks for the question regarding "Excel output ", version 4.0.8
You Asked
Tom,
We use the SYLK format to output a report as a spreadsheet
(we found this works better than changing the mime to csv).
However, one problem that just will not go away is when the
web server is ready to serve up the spreadsheet. Is there
a way that we can specify a filename (maybe as part of the
SYLK header ?), instead of using the cryptic filename that
the webserver generates.
The only other option that I can think of is writing to disk
and then displaying the spreadsheet. But, you can't do this
in using PL/SQL..
Any suggestions ?
Thanks
Sanjay
and we said...
Well, it is not the webserver generating that "cryptic" filename
-- it is Excel and/or the Browser is naming a temporary file.

So, what can you do to get a more "normal" name associated with
the spreadsheet?  One thing you can do is to use a
package.procedure instead of just a procedure.  Lets say you
have a package called OWA_SYLK with a procedure SHOW that takes
a query and generates a SYLK format file from it (i have one so
I tested with it).  You wrote a procedure:

create or replace procedure emp_ss
as
begin
  owa_sylk.show( 'select * from emp' );
end;
/

and run that with a URL like:

http: //hostname/dcd/owa/emp_ss

Now, Excel or the browser sees that -- sees no extension or
perhaps sees an extension it does not understand (if you used
OWNER.emp_ss or something) and creates a temporary, mangled
name.  We can "fix" this by:

create or replace package data
as
    procedure xls;
end;
/

create or replace package body data
as

procedure xls
is
begin
    emp_ss;
end;

end;
/

and now the URL looks like:

http: //hostname/dcd/owa/data.xls

And both the browser and Excel are "happy", they see data.xls as
a normal file name and do the right thing.
August 31, 2000 Sabitha -- Thanks for the question regarding "Accessing a SQL server table from an oracle database trigger ", version Oracle 7.3.4
You Asked
We have a trigger that checks for a certain status of a field in
one table before allowing the user to rename a package (a field
in another table). The table with the status field currently
exists in a DB2 table and we update an intermediate oracle table
with the status field nightly. This intermediate table is then
used to check the status from the trigger that either allows the
user to rename a package or not.

We are looking to eliminate the intermediate oracle table and
make it more real time. Also the DB2 tables are being replaced
by SQL Server. Can I query the SQL Server table from within an
Oracle trigger using database links? What would I need to do
this?

If database link is not a good idea is there a way to call a
jave program from a trigger and have the jave program pass the
status information to the trigger. Where can I get information
on this? Thanks for your help.
and we said...
Well either DB2 or Sybase (or Informix or ....) can be queried
from Oracle using a transparent gateway.  See
http://www.oracle.com/gateways/
for more info on that.

In 7.x as you have, doing the second option, calling a "java
program" from a trigger is possible but not trivial.  See
http://osi.oracle.com/~tkyte/plex/index.html
for the concept.  You would have a java program that connects to
Oracle and listens for requests on a pipe.  A trigger would use
the dbms_pipe package to write a message onto the pipe, the java
program would get it -- do whatever -- and write a response back
on another pipe, one that the trigger is blocked on waiting...

In 8.0, this would be more easily done via an EXTERNAL PROCEDURE
which allows you to write a DLL or .so file (NT or Unix) in C
(using C calling conventions, doesn't have to be C necessarily).
 The trigger can then call this directly as if it were a stored
procedure.

In Oracle8i release 8.1 and up -- you could write a java stored
procedure as well.
August 31, 2000 Vinh -- Thanks for the question regarding "LOBs or Files ?", version 8.0.4
You Asked
Hi Tom,
I'm developing a application that archive documents on a Oracle8
database. End-users can upload these files on browsers and view
it in native format. But now, I don't know where store these
documents: LOB column in a table or files on file system of Web
server machine, and how to uploading these files from browser
and view it from database. I think, Web mail systems (Hotmail,
Yahoo ...) store attached files on file system of web server
machine, is it true?
Please give me an advice. How do I implement it ? (some basic
steps).
Thanks a lot.
and we said...
I myself always use the database.  That is my approach.  I like
having the recoverability, the guarantee of availability, the
knowledge I know exactly where the data is provided by the
database.

If I stuff the files into the OS, there is nothing preventing
someone from saying "wow, look at all of this junk.  rm *".

So, if you look at alot of the features offered by the database
and think you might like to have them (all in the area of data
integrity and control) -- the database would be the right place
to put them.

As for how to implement -- it'll depend on the software you are
using in the middle (between the browser and the database).
Would need more info to go into details there.
August 31, 2000 Cathy -- Thanks for the question regarding "OWA_UTIL.ident_arr and max size", version 4.0.7.0
You Asked
I'm using the  Web Toolkit OWA_UTIL.ident_arr data type to pass
multivalued parameters to another procedure.

My problem is that the ident_arr is defined as VARCHAR2(30) and
my parameters can be up to VARCHAR2(45), so when I try to pass a
parameter that is more than 30 chars long an error occurs.

Is there any way I can change ident_arr to a VARCHAR2(45)?

Thanks

Cathy
and we said...
Don't use owa_util.ident_arr.  Create your own type.  Simply:

create or replace package my_types
as
   type myArray is table of varchar2(4000)
         index by binary_integer;

   emty myArray;
end;
/

In that way, you can now create a procedure like:

create procedure my_procedure
    ( my_data in MY_TYPES.myArray default MY_TYPES.empty )
as
........

The webserver will use that type -- no problem there.  As well,
since you defined an "empty" one of them you can even default
your tables if you need.

Just only use varchar2 types -- the webserver will not be able
to bind to a table of number or date or anything other then
varchar2(any_length) correctly.
Review & Followup
Rating: 3
March 14, 2001
Reviewer: yu.feng from japan

August 31, 2000 Tad -- Thanks for the question regarding "RE: Returning sequence numbers to a third party software tool", version 8.0.5
You Asked
Tom

I asked you a few weeks ago about this problem and one of your
suggestions sounded like the perfect solution.

You suggested :

"At least three ways to do this:

1) insert into t values ( .... ) RETURN COLUMN_NAME INTO
:bindvar

  That syntax, used with inserts and updates, is useful to
  retrieve the value of any column(s) in one round trip  "

Unfortuantely PRO*C fails to precompile this code as it is not
valid for Embedded SQL, as I am calling it from C code.

Is there another way of doing this through Embedded SQL ?

Thanks,

Tad
and we said...
There are at least 2 ways to do this in pro*c using 8.0...

One is to use a static anonymous block like this:

    EXEC SQL EXECUTE
    begin
    insert into t (x) values ( 0 ) returning x into :x;
    end;

when you precompile you must use sqlcheck=full|semantics and
pass in a userid=u/p as well.  If you don't like to precompile
with those options (takes longer) you can also:

if ( firstTime )
{
    strcpy( sql.arr,
 "begin insert into t(x) values(0) returning x into :x; end;" );
    sql.len = strlen(sql.arr);

    exec sql prepare S from :sql;
    exec sql declare C cursor for S;
    firstTime != firstTime;
}
exec sql open C using :x;

You only need to prepare (parse) once...
August 31, 2000 Kenneth -- Thanks for the question regarding "shutdown transactional", version 8.0.5
You Asked
Dear Tom,

While shutting down there are 3 modes
1. shutdown
will wait for all user to exit
no new users allowed to connect
meaning that all trasactions will get commited

2. shutdowm immediate
will not wait for all user to exit. Kill their sessions
no new users allowed to connect
on going  trasactions will get rollbacked.

3. shutdown abort
will not wait for all user to exit. Kill their sessions
no new users allowed to connect
on going  trasactions will  not be rollbacked.

In oracle8 onwards
shutdown transactional is also available
Documentation says
it will wait for all on going transactions to complete.
my query is  if these transactions get completed then will they
be comitted or rollbacked.
If they get comitted then it is same as a normal shutdown
else if they get rollbacked then it is same as shutdown
immediate. ( only that it will not wait for the transaction to
complete

So what is the thin line betwen shutdown immediate or shutdown
transactional.

Thanks In Advance,
Kenneth
and we said...
They will be committed (if the client commits that is, the
client can still issue rollback itself).

Shutdown immediate does a clean shutdown after killing (all
sessions) and rolling back all in process transactions (things
that are modifying the database).

Shutdown transactional allows the in process transactions to
finish to completion and prevents all existing sessions from
starting any new work.  As the in process transactions complete
-- they too are prevented from starting new transactions.  When
no outstanding transactions remain -- the database is shutdown.

The thin line:  immediate kills everything right away and rolls
them back.  Transactional waits for no work to be in progress
and then shuts down cleanly.

In my opinion, transactional is close to NORMAL then to
immediate....
August 31, 2000 Malcolm -- Thanks for the question regarding "SQL*Loader Problem", version 7.3.4
You Asked
Problem with SQL*Loader.
A cut down example of the problem is enclosed:

I have the following control file:

UNRECOVERABLE
LOAD DATA
APPEND
INTO TABLE mal
WHEN (1:3) = "010"
(
empno position(6)  CHAR             terminated by "|!",
ename              CHAR             terminated by "|!",
job                CHAR             terminated by "|!"
)

Inserting to a basic table

 Name                            Null?    Type
 ------------------------------- -------- ----
 EMPNO                                    VARCHAR2(3)
 ENAME                                    VARCHAR2(10)
 JOB                                      VARCHAR2(10)

And my datafile is:

010|!21|!MAL|!MAL|!
010|!22|!DEWI|!DEWI|!

Anyhow, when calling SQL*Loader I get the following error:

SQL*Loader: Release 7.3.4.0.0 - Production on Thu Aug 31
09:27:32 2000

Copyright (c) Oracle Corporation 1979, 1996.  All rights
reserved.

SQL*Loader-350: Syntax error at line 7.
Expecting single char, found "|!".
empno position(6)               CHAR             terminated by
"|!",
                                          ^

Can you shred any light on this?

Regards

malcolm
and we said...
A terminator can only be 1 character long.  Your control file
can look like this:

LOAD DATA
INFILE *
APPEND
INTO TABLE mal
WHEN (1:3) = "010"
fields terminated by '!'
(
empno position(6) "rtrim(:empno,'|')",
ename "rtrim(:ename,'|')",
job   "rtrim(:job,'|')"
)
begindata
010|!21|!MAL|!MAL|!
010|!22|!DEWI|!DEWI|!

to load your data.
August 31, 2000 Audrey -- Thanks for the question regarding "Cursors", version Java 1.2 JRun 2.3 Oracle 8i
You Asked
Hi I have a few question on SQL statements and cursors
My application is written in Java and connects to the database
using JDBC.

1. When an SQL statement is been executed I read in some
documentation that 5 default cursors are created. Are 5 default
cursors created per SQL statement executed or 5 in total?

2.  When I create  prepared statements, are active cursors
created for these and how do I close them? Is it stm.close
where PreaparedStatement stm;

3.  How many cursors would be open for this example select
statement

select terms.t_termId, terms.t_target, terms.t_engterm  from
terms,termsproperties where ( terms.t_hashtargetmatchcase = ?
and termsproperties.tp_termid = terms.t_termid and tp_linux = ?
and tp_unix = ? and tp_windows = ? and tp_mac = ?)order by
terms.t_engterm

? = some paramter read from application inputted by user.
and we said...
1) In Oracle, the total number of cursors that may be opened
simultaneously by your program is controled by the init.ora
paraemeter OPEN_CURSORS.  This parameter fixes an array if you
will at some maximum length.  When you open a cursor -- we look
for an empty slot.  If we find no empty, allocated slot (the
array starts out filled with "nulls") we will allocate stored
for 12 slots -- point to them with the array and give you one of
them.  So, when you ask for the first cursor -- 12 of them are
allocated and you get one back.  The next 11 requests (if you do
not close some of your cursors) will get the next 11 allocated,
empty slots and then the 13'th one will cause 12 more to be
allocated.  So, the number of cursor "spaces" grows by 12's.
The number of cursors actually allocated and in use -- you
control how that grows and it grows by 1's.

2) They create a cursor (and maybe more then one if the
prepared/callable statement is to a plsql routine that returns
ref cursors).  stmt.close and rset.close are what close them.
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:553222846752
for an example java program that shows how to track this
information.

3) One cursor.
August 31, 2000 Bala -- Thanks for the question regarding "Latches, UTLBSTAT & UTLESTAT", version 8.0.5
You Asked
1.  What are latches ? How are they used ?
2.  I wanted to run utlbstat, estat and generate a report, is it
advisable to run in System default tablespace or is it advisable
to run in a new tablespace, if so how do i accomplish this.

Regards

Bala
and we said...
1) a latch is a lightweight serialization mechanism.  We use
them to protect data structures from concurrent updates.

2) It is OK to run in system.  You do not have to -- alter user
sys default tablespace XXXXX -- when executed before running
utlbstat as the SYS user, will have the objects created in
tablespace XXXXX/
August 31, 2000 Pedro -- Thanks for the question regarding "Can i call a Shell Unix commands from Pl/Sql or Sql Plus", version 8
You Asked
Can i call a Shell Unix commands from Pl/Sql or Sql Plus

thanks a lot,
PP
and we said...
From SQLPlus you can use the SQLPlus command "host" to execute
any command.

ops$tkyte@DEV816> host date
Thu Aug 31 10:59:45 EDT 2000

In PLSQL -- you can use external procedures to create a C
routine that can fork/exec some scripts (see
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adg11rtn.htm#1656
for info on that)  or you can use Java in 8i to run programs or
you can use dbms_pipes to "talk" to an existing process.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:16212348050
for a quick and dirty example but make sure you fully
understand the security implications of such an implementation!
all commands would be executed under the uid of the person
running the pipe program -- could be dangerous.
August 31, 2000 Petra -- Thanks for the question regarding "Getting Files into the Database?", version 8.1.6
You Asked
Dear Tom!

After you helped me with WebDB I'm now optimistic you can do it
with the database again...
I'd like to store several multimedia files (.gif, .O2C, .SWF,
...) into the databse for publishing it later on our homepage.
So I created for example a table 'bilder' like
Create table bilder(
 bild_id   number(6) primary key,
 beschreibung   varchar2(80),
 bild  BLOB);

Table was created. Then I tried to insert data into this table,
but how do I get the picture-files, audio-files etc. in it?

I tried INSERT INTO bilder (1, 'Wasserfall', EMPTY_BLOB());
It worked. But now I didn't understand to use DBMS_LOB package
to get the data into the table/tablespace. What is the thing
with the locator?

The files are not big - mostly 30-80 KByte. Is there another
solution?

Thanks for all!
Petra
and we said...
In 8.1 as you have, sqlldr can be used, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:624423639385
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:392618837633
for examples.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:482221538758
for how to do this in plsql using dbms_lob.loadfromfile...
And in Java using streams if that interests you.

August 31, 2000 minnie -- Thanks for the question regarding "how
      to print in unix monitor? -- extprocs, printf and fprintf", version
      oracle8i 8.1.5

      You Asked
Hi,Tom:
   when i call OCI external procedure by pl/sql, i want to
display something out by "printf()" in oci program. But there
are some trouble to display it in out unix monitor(SUN solaris),
Sometimes the unix monitor can display them out, but now it
cann't , and nobody modify the configure. I tried to use
"fprintf" to a file, it seemed that OCI doesn't support it when
it is called by pl/sql(if only in OCI, it can). We contact your
company the day before yesterday, but don't get any answer yet.
Do you know how to configure something to make the unix display?

thanks.

minnie

      and we said...
By display I'll have to assume you mean on the unix "console"
since there is no such thing as a "display"...

Extproc processes are started by the listener.  A printf issued
by the extproc will goto the console that the listener is
currently attached to.

If you start the listener as part of the startup process on your
machine -- it will be attached to the system "console".
Otherwise -- the listener will be attached to whatever pty
(psuedo tty) that happens to start it.  If you start the listner
in some telnet session -- LEAVE that session open and run your
extproc -- you should see your printfs goto that window.  They
will no longer goto the system console.

So, in your case, what probably happened is you restarted the
machine at some point and the messages were going to the
console.  Later, someone stopped and restarted the listner --
changing the "monitor" it would display to.  When that person
exited their telnet/xterm session -- their pty went away and the
printf now just go into a big bit bucket.  When they restarted
the listener -- they stopped the messages getting to the
console.  When they exited their session -- they stopped the
messages from being display anywhere.

OCI fully supports the ability to fprintf to a file in an
extproc -- I do it all of the time myself.  All of my
extprocs, and I've written quite a few, use fprintf heavily to
generate trace files.

You can also use the functions:

OCIFileOpen
OCIFileWrite
OCIFileClose

as well.  I use both successfully (and easily).  Your problem
with fprintf is undoubtably a permissions problem ( don't forget
-- the extproc runs as the user the listener is, not as "you".
If you try to open a file in "your" home directory or something,
the extproc probably will not be able to do that. )

Here is a snippet of code you might find useful.  I use it all
of the time -- it works great (given the above).

It implements a simple debugf routine that works like printf but
writes to a trace file suitable to be "tail -f /tracefile" in
another window (so your extproc output can be viewed in "real
time" as it happens).

Give this a try.

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>

#ifndef OCI_ORACLE
# include <oci.h>
#endif

static int currLineNo;
static char * currFileName;

void _debugf( char * fmt, ... );

#define debugf \
currFileName=__FILE__, \
currLineNo=__LINE__, \
_debugf

/* PUT YOUR CODE HERE!!!!! */

/* ------------------------------------- */
#undef debugf

void _debugf( char * fmt, ... )
{
va_list ap;
FILE    * fp;
char    * debug_modules = "all";
char    * debug_file    = "/tmp/tkyte.dbg";
time_t    theTime = time(NULL);
char    buffer[25];

    if ( !debug_modules ) return;

    if ( (fp = fopen( debug_file, "at" )) == NULL )
        fp = stderr;

    strftime( buffer, sizeof(buffer),
             "%y%m%d %H%M%S GMT", gmtime(&theTime) );

    fprintf( fp, "%s (%13s,%3d) ",
             buffer, currFileName, currLineNo );
    va_start(ap,fmt);
    vfprintf( fp, fmt, ap );
    va_end(ap);
    fprintf( fp, "\n" );

    if ( fp != stderr ) fclose(fp);
}
August 31, 2000 Vaishakhi -- Thanks for the question regarding
      "sql loader query", version ver 8.0.5

      You Asked
The data to be loaded from a flat file has positional fields not
separated by any delimiters. The database table into which the
flat file data is to be loaded has 10 fields and the flat file
has 30 fields. Now, the question i have is, Can the flat fields
which are not contiguous be concatenated and mapped to a single
field in the db table i.e. the flat file has

field1 position 6:10
field2 position 20:25
field3 position 45:55

field1 ||'-'||field2 ||'-|| field3 is to be mapped to a single
field "prodid" in the db table.

Can this be done directly through the control file
specifications or the flat file will have to be modified to
comply the db table definition.

Thank you.
Vaishakhi

      and we said...
You would have to have 1 field defined in the ctl file with a
postition specification that overlapped all three of your
logical fields and use a SQL function to get what you want.

For example, instead of field1 .. field3 as you have, you would
have 1 field:

....
thefield position(1:55)
"substr(:thefield,6,5)||'-'||substr(:thefield,20,6)||'-'||substr(
:thefield,45,11)"
.....

August 31, 2000 -- Thanks for the question regarding "Migration
      of 7.3.4 to 8.1.6", version 8.1.6

      You Asked
Dear Tom,
My company is planning to migrate the database from 7.3.4 to
8.1.6.The size of the database is 25GB.I just want ur
suggestions before going to do that.I want to know which will be
the best method and efficient one for migrating?(in terms of
fastness and less error prone)
1)Using mig utility
2)Using export utility.
At the same time can u pls tell me what are the real problems
which will occur while doing that.Are there any books or
material related to migration other than the one from oracle
corporation.
Thanks for ur help
Geeta

      and we said...
See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:444419950548
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:294416170927
for some of my previous comments on that.

If you are happy with your current blocksize, I would use the
mig utility.  It'll take less time then a full export/import.

If you are unhappy with your current blocksize or would like to
"clean up" some objects (reassign to another tablespace, rebuild
things with different storage parameters, take full advantage of
new features like locally managed tablespaces and such) -- this
would be the perfect opportunity.

So, in the end, it will be a matter of choice.  Both will get
you there -- one is faster but you end up with what you started
with.  The other allows you to make big changes...

I am not personnaly aware of any books related to just
"migration".
August 31, 2000 subhakar -- Thanks for the question regarding
      "Passing OS variables to the database", version 8.1.6

      You Asked
Hi Tom,

Is there any way I can use any package to query the OS and
obtain the value in a variable to Oracle???????

I have to write an After STARTUP database trigger to update one
of my table with the IP address of the host system each time it
reboots..

Thanx for u'r help...

      and we said...
In 8.1.6 as you have, with java it is pretty easy:

ops$tkyte@DEV816> create or replace and compile java source
  2  named "InternetStuff"
  3  as
  4  import java.lang.String;
  5  import java.net.InetAddress;
  6  import java.net.UnknownHostException;
  7
  8  public class InternetStuff {
  9    public static String returnHostByIP()
 10    {
 11      try
 12      {
 13          return InetAddress.getLocalHost().getHostAddress();
 14      }
 15      catch (UnknownHostException e)
 16      {
 17            return null;
 18      }
 19    }
 20  }
 21  /

Java created.

ops$tkyte@DEV816> create or replace function my_ip return
varchar2
  2  as
  3  language java
  4  name 'InternetStuff.returnHostByIP() return
           java.lang.String';
  5  /

Function created.

ops$tkyte@DEV816> select my_ip() from dual
  2  /

MY_IP()
------------
138.2.5.52

If you have the jserver option, plsql can do it as well with
utl_inaddr.get_host_address.

ops$tkyte@DEV816> select utl_inaddr.get_host_address from dual;

GET_HOST_ADDRESS
-------------------
138.2.5.52

An alternate method would be use to a C extproc to grab this
information.  See

http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adg11rtn.htm#1656
for more info on that method.

Review &
      Followup

      Rating: 4
Liked the
      solution with utl_inaddr.  April 11, 2001

Reviewer:  Bijay  from Hayward, CA
Thank you Tom!

August 31, 2000 John D -- Thanks for the question regarding
      "Oracle Database Size and tuning parameters.", version Oracle 8.0.5 /
      Oracle 8.1.6

      You Asked
Hi Tom,

   I am new to Oracle Admin.

   1. How to find a database size?

   2. How should I tune INITRANS, MAXTRANS parameters?

   3. Why does oracle keep deleted records in index with
      deleted marks, instead of removing it from index?

   Thanks in advance,

with regards,

d. john britto.

      and we said...
1) I use a script like the following.  It shows lots of
information by tablespace and then total.

--------------------------------------------------------
-- free.sql
--
-- This SQL Plus script lists freespace by tablespace
--------------------------------------------------------

column dummy noprint
column  pct_used format 999.9       heading "%|Used"
column  name    format a16      heading "Tablespace Name"
column  Kbytes   format 999,999,999    heading "KBytes"
column  used    format 999,999,999   heading "Used"
column  free    format 999,999,999  heading "Free"
column  largest    format 999,999,999  heading "Largest"
column  max_size format 999,999,999 heading "MaxPoss|Kbytes"
column  pct_max_used format 999.9       heading "%|Max|Used"
break   on report
compute sum of kbytes on report
compute sum of free on report
compute sum of used on report

select nvl(b.tablespace_name,
             nvl(a.tablespace_name,'UNKOWN')) name,
       kbytes_alloc kbytes,
       kbytes_alloc-nvl(kbytes_free,0) used,
       nvl(kbytes_free,0) free,
       ((kbytes_alloc-nvl(kbytes_free,0))/
                          kbytes_alloc)*100 pct_used,
       nvl(largest,0) largest
from ( select sum(bytes)/1024 Kbytes_free,
              max(bytes)/1024 largest,
              tablespace_name
       from  sys.dba_free_space
       group by tablespace_name ) a,
     ( select sum(bytes)/1024 Kbytes_alloc,
              tablespace_name
       from sys.dba_data_files
       group by tablespace_name )b
where a.tablespace_name (+) = b.tablespace_name
order by &1
/

The most interesting column perhaps is "LARGEST" which shows the
largest free contigous chunk of space in that tablespace --
thats the largest NEXT extent you can have...

2) In most systems, you would leave them be.  It is special
cases where you need them (where you expect lots of people to be
modifying the same exact block simultaneously for example).  It
is something you would tune because you have to -- but later,
when you discover the need for it.

3) It is not that it keeps the deleted records in the index so
much as it does not immediately reclaim the space.  Lets say you
have a table T ( x int, y char(2000), primary key(x,y) ).  You
insert into that table the values (1,'a'), (2,'a'), and
(9999999999999999999999999999,'a').

Now, you go into a loop:

ops$tkyte@DEV816> begin
  2    for i in 2 .. 1000 loop
  3         delete from t where x = i;
  4         commit;
  5         insert into t values ( i+1, 'a' );
  6     end loop;
  7  end;
  8  /

If we left the deleted entries in there (eg: if when we deleted
2 we left it there) you would expect this index on T for the
primary key to grow and grow and grow (especially since each
index entry is over 2000 bytes in length -- by using the CHAR we
assured that).  In fact, it does not.

What happens is that when we deleted 2 from the index initially
-- we did not reorganize the entire index structure to
accomidate that.  Rather, we deleted 2 on that block but left
its slot there.  Now, any value that fell between 1 and that
really big number can reuse that slot but that slot would remain
there until we reused it OR every slot on that index block was
empty.

Here is a small test you can run to see this yourself:

ops$tkyte@DEV816> create table t ( x int, y char(2000),
constraint t_pk primary key(x,y) )
  2  tablespace system
  3  storage ( initial 1k next 1k pctincrease 0 )
  4  /

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t values ( 1, rpad('a',2000,'a')
);

1 row created.

ops$tkyte@DEV816> insert into t values ( 2, rpad('a',2000,'a')
);

1 row created.

ops$tkyte@DEV816> insert into t values (
9999999999999999999999999999, rpad('a',2000,'a') );

1 row created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> analyze index t_pk validate structure;

Index analyzed.

ops$tkyte@DEV816> exec print_table( 'select
blocks,lf_blks,del_lf_rows from index_stats' );
BLOCKS                        : 2
LF_BLKS                       : 1
DEL_LF_ROWS                   : 0
-----------------

PL/SQL procedure successfully completed.

ops$tkyte@DEV816>
ops$tkyte@DEV816> begin
  2    for i in 2 .. 1000 loop
  3         delete from t where x = i;
  4         commit;
  5         insert into t values ( i+1, rpad('a',2000,'a') );
  6     end loop;
  7  end;
  8  /

PL/SQL procedure successfully completed.

ops$tkyte@DEV816>
ops$tkyte@DEV816> analyze index t_pk validate structure;

Index analyzed.

ops$tkyte@DEV816> exec print_table( 'select
blocks,lf_blks,del_lf_rows from index_stats' );
BLOCKS                        : 2
LF_BLKS                       : 1
DEL_LF_ROWS                   : 0
-----------------

PL/SQL procedure successfully completed.

You see -- the index never grows, even though we put 2000*1000
bytes in and out of it.  It remains the same size.
August 31, 2000 GAURANG -- Thanks for the question regarding
      "create user", version 8.1.5

      You Asked
hi tom.

when we create user in oracle database.how much space it occupies.
(no object is in user's schema,just user defination.)

      and we said...
It takes the little amount of space it will take in the various data dictionary
tables to store the definition of the user. A row in user$ and rows in the
various auth tables for roles and privileges granted.

Very very little space overall.

August 31, 2000 Shawn -- Thanks for the question regarding
      "Instance shutdown with dispatcher", version 8.1.6

      You Asked
When doing an immediate shutdown of the instance, I get the
following message:

   ORA-00106: cannot startup/shutdown database when connected to
a dispatcher

I am aware that I created the database as SHARED.  However, I am
not familiar with the proper procedure for management of the
dispatcher(s).  I have read the error message, but do not quite
understand their explanation. Any advice would be greatly
appreciated.

      and we said...
There are many adminstrative functions that you cannot perform
when connected to the database using MTS (multi-threaded
server).  Instance startup and shutdown are one of them.

You should either:

o connect directly, without Net8, on the machine with the
database.  Do not use an "@tnsname", do not have  TWO_TASK
environment variable.  Simply "connect sys/manager" or "connect
internal" and do the operation.

o use a TNSNAME entry that has a SRVR=DEDICATED in it, for
example:

MYDATABASE.WORLD =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = foobar)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = MYSERVICENAME)
    )
  )

In that fashion, you will use a dedicated, not shared, server --
will not be connected via a dispatcher and will be able to use
these commands.
August 31, 2000
      Mike -- Thanks for the question regarding
      "Migration", version 7.3.3.6.0

      You Asked
Tom,
Our company is planning to move from Oracle 7.3.3.6.0 to Oracle
8.0.x(?) (8.0, not 8i).  I saw in the ORACLE magazine where you
stated that "Hopefully you are moving to Oracle8i Release 8.1,
not 8.0." in response to another migration issue.  What are the
cons of not going to 8i immediately?

Thanks in advance.

Mike

      and we said...
Oracle8.0 is already "old software".  Why move to a release of
the database that is nearing end of life?  If you are upgrading
-- and going to all the effort that entails, why would you not
go to the latest, most current release?

I just cannot imagine going to all of the work to upgrade and
not getting the lastest software releases.  That is why I said
what I said.

To see what features you might be missing out on by going to the
release of Oracle that was current over 2 years ago -- see

http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
I can't tell you exactly which ones might interest you in your
environment (not knowing anything about it) but I can assure you
that 8i has many improvements over 8.0 and many new features
over 8.0.  Not all of them are "internet" related (most aren't
or aren't specifically internet oriented).

August 31, 2000 Jahanzeb -- Thanks for the question regarding
      "Problem with Sql Loader", version Oracle 8.0.5

      You Asked
I have been trying to load data from a text file into a database
table through Sql Loader since last week, but I am not getting
the required results.

The sample data of the text file (data.txt) is as follows,

3205679761 - Detailed Report

  July 01, 2000 21:24
    Location : djdjffsdfsfjsdjf
    Status   : jksddfkllfsfdsdffk

  July 01, 2000 22:18
    Location : ksjflsdfjdjgfggjgr
    Status   : jkfdgjfkldgjklfdgjdfklgjldfkgjldfkjgkldfgjf

  July 01, 2000 23:20
    Location : jkfghgfjghdfg
    Status   : jksfgdskgjkgjkdfgdfkgjkdfglfgg

  July 01, 2000 23:28
    Location : jkfgjkfgdfgjdfgjjkdfgjk
    Status   : uierteirtguertgreuvhghhghighighg

  July 03, 2000 08:05
    Location : jklsfjkdldkdjg
    Status   : ertjioejnferionvre

  July 03, 2000 09:54
    Location : lkfjgiesfghoeisghirhg
    Status   : fgegfiegfgwugvwoerhg

3205679783 - Detailed Report

  July 01, 2000 21:24
    Location : dfjgdfklgdlfkfjglfij
    Status   : jkdfgilfdshgilhgiorwtg

  July 01, 2000 22:14
    Location : iodfigvjdosfjgfiogjg
    Status   : dgkjdfgjrtivjrjrjvjrjtvbjrtjrj

  July 01, 2000 23:11
    Location : ierwegweruigiwerg
    Status   : igjtirtirtvbjhrtjbhrtjbhrjhb

  July 01, 2000 23:32
    Location : uiergiehuiegerg
    Status   : figooejgejvervjerjvvjrejv

Now , I want to load this data into a table , named sample with
structure as ,

 Name                            Null?    Type
 ------------------------------- -------- ----
 sno                                      VARCHAR2(20)
 date-time                                varchar(50)
 LOCATION                                 VARCHAR2(100)
 STATUS                                   VARCHAR2(100)

As you can see that data consists of two detailed reports.One
for sno .3205679761 and other for sno. 3205679783.
There are several steps in each detailed report.Each step
contains date-time , location and status.

I want to load each step for that particualr sno. in the
appropriate coulumns of table 'sample'. i.e the first row of
table should contain first sno of detailed report and
date-time,location,status of first step.Like this the second row
should contain first sno of detailed report and
date-time,location,status of second step..and so on.

Please tell me what should be the correct fromat of control
file.

Thanks.

      and we said...
Well, you could do this with SQLLDR and some really tricky
triggers on the table and such but... in the interest of time --
straightforwardness and ease of maintenance -- what I'm going to
suggest is

o load the file "as is" into an ordered temp table.
o run a procedure against the data.

For example, I used this control file:

LOAD DATA
INFILE *
INTO TABLE TEMP
( seqno RECNUM,
  text Position(1:1024))
BEGINDATA
3205679761 - Detailed Report
........

to load into a table TEMP ( seqno int primary key, text
varchar2(1024) );

Then, I created your table:

create table t
( sno varchar2(20),
  date_time varchar2(50),
  location varchar2(50),
  status   varchar2(50) );

And a very simple small stored procedure:

create or replace procedure reformat
as
    l_sno       t.sno%type;
    l_date_time t.date_time%type;
    l_location  t.location%type;
    l_status    t.status%type;
    l_temp_date date;
begin
    for x in ( select * from temp order by seqno )
    loop
        if ( x.text like '%Detailed Report%' ) then
            l_sno := substr( x.text, 1, instr(x.text,'-')-1 );
        elsif ( x.text like '%Location : %' ) then
            l_location := substr( x.text, instr(x.text,':')+2 );
        elsif ( x.text like '%Status %:%' ) then
            l_status := substr( x.text, instr(x.text,':')+2 );
            insert into t ( sno, date_time, location, status )
            values ( l_sno, l_date_time, l_location, l_status );
        else
            begin
                l_temp_date := to_date( ltrim(rtrim(x.text)),
                                      'Month dd, yyyy hh24:mi');
                l_date_time := x.text;
            exception
                when others then null;
            end;
        end if;
    end loop;
end;
/

That fixes all of the data right up.  I think that is the best
approach.  sqlldr and then run a procedure.
August 31, 2000 Fernando -- Thanks for the question regarding
      "Instalando con RAW", version 8.1.5.0.0

      You Asked
   Tom estoy tratando de instalar una base de datos en
plataforma HP-UX 11 con raw (no con filesystem) pero tengo dudas
al respecto:
 Como le indico el lugar en donde quedaran los archivos de
control, datafiles,redo,etc?.

  Yo le estoy indicando por ejemplo:
    /dev/vg02/rctrl01
   pero me envia un error:
    este archivo ya esta creado

      and we said...
   When using a raw device you need to specify the full pathname
in single quotes, and use the REUSE parameter.  e.g. if there
are two raw devices, each 30Mb in size, and the database has a
4K block size, the relevant command would look like this:

   create tablespace raw_tabspace datafile '/dev/raw1'
                                  size 30712K REUSE
                                  datafile '/dev/raw2' size
                                  30712K REUSE

Do not forget to read you OS admin guide!  You typically have to
leave some space for overhead off of the size of a raw
partition.  For example, on Solaris the size of an Oracle
datafile created in a raw partition must be at least two
Oracle block sizes smaller than the size of the raw partition
itself.  This is important -- I don't know about HP/UX myself
(work on solaris predominantly) but make sure to check the
Administrators reference for your platform...

September 01, 2000 wallacel -- Thanks for the question regarding
      "dbms_shared_pool", version 8.1.6

      You Asked
Tom:

you don't need to answer my previous question regarding
oem, I found the answer in your archive.
it is a bug, and i kill the process and restart oem
everything goes fine.

my new question is
i run dbmspool.sql under system account by accident,
and then i run it again under sys account.
then i go back to system account and drop package
dbms_shared_pool. and then try to use dbms_shared_pool under
system account, it don't work.
since the inside dbmspool.sql it grant execute on
dbms_shared_pool to execute_catelog_role, system should
have no problem to run it, can you tell me what's the problem?

Regards,

      and we said...
Without an actual error message -- I'm going to have to guess.

I did what you did above and had no problems.  What might be
tripping you up however is the fact that dbmspool.sql does
not create a public synonym for dbms_shared_pool.  So, when
system wants to describe it or run it, it must:

SQL> desc sys.dbms_shared_pool
SQL> exec sys.dbms_shared_pool.sizes(0)

It must qualify the reference with SYS.  Perhaps that is your
issue.  If not, repost the question - with a cut and paste of
the exact error you are receiving.

September 01, 2000 t.siva rama -- Thanks for the question regarding
      "developer -- forms 4.5 on win2k", version 7.2.2

      You Asked
is d2k 1.3.5 (forms 4.5) compatible with windows 2000?

      and we said...
That configuration is not supported.  That does not mean it will
not work however, I would not suggest using such a configuration
in a production environment as forms 4.5 is no
supported/supportable on that platform.
September 01, 2000 greeshma -- Thanks for the question regarding
      "pl/sql", version 8.0.6

      You Asked
hi!tom
thankx for ur help on previous occassion.
i have a sequence generator starting with 1 and goes upto
999999.
is there any way that the database can reinitialise the
 same sequence to 1 after reaching the maximum number.
thankx for ur help.

      and we said...
Sure, use the CYCLE keyword:

 1* create sequence my_seq start with 1 maxvalue 3 cycle
cache 2
ops$tkyte@8.0> /

Sequence created.

ops$tkyte@8.0> select my_seq.nextval from dual;

   NEXTVAL
----------
         1

ops$tkyte@8.0> /

   NEXTVAL
----------
         2

ops$tkyte@8.0> /

   NEXTVAL
----------
         3

ops$tkyte@8.0> /

   NEXTVAL
----------
         1

ops$tkyte@8.0> /

   NEXTVAL
----------
         2

ops$tkyte@8.0> /

   NEXTVAL
----------
         3

ops$tkyte@8.0>
September 01,
      2000 steve -- Thanks for the question
      regarding "SQLJ, checking oracle.sql.CHAR values", version jdeveloper 3.1
      + 8.1.6.0.0

      You Asked
Hi Tom,

I'm looking for a neater way to check that a SQLJ variable
of type oracle.sql.CHAR is equal to "Y".

It doesn't sound hard and probably isn't but this is the
method I currently use, is there a better way?

oracle.sql.CHAR p_replace;

       if (p_replace.equals(new
oracle.sql.CHAR("Y",CharacterSet.make(CharacterSet.WE8ISO8859P1_C
HARSET))))

Thanks
Steve

      and we said...
How about:

if (p_replace.stringValue().equalsIgnoreCase("Y"))
{
  // Do something....
}

Unless you really truely need the character set support provided
by oracle.sql.CHAR, you might consider just using unicode
Strings in java -- change the datatype of p_replace from
oracle.sql.CHAR to String....

September 01, 2000 -- Thanks for the question regarding "Exporting
      to /dev/null", version 7.3.3

      You Asked
I tried to use export with file=/etc/dev/ to find the row counts
for all tables without creating a dump file.
But Export expects the Return key or Volume size before it can
proceed as show below.
How do I provide the Return key response in a parm. file when I
do

 nohup exp parfile=exp01.prm &         ?
What is the volums size it asked for ?  What are the valid
values ?
It doesn't look like it  is in the documentation.

Connected to: Oracle7 Server Release 7.3.3.0.0 - Production
Release
With the distributed and parallel query options

PL/SQL Release 2.3.3.0.0 - Production

Volume size (<ret> for no restriction) >

Thanks.

      and we said...
Well, that would be the undocumented volsize parameter to exp:

exp userid=scott/tiger file=/dev/null owner=scott volsize=1000m

exp thinks /dev/null is a tape device for some reason...

Article-ID:         <Note:90620.1>
Circulation:        PUBLISHED (EXTERNAL)
Folder:             server.Utilities.ExportImport
Topic:              3.3 --- Exporting to Tape / Large Exports
Title:              Export Using the Parameter VOLSIZE
Document-Type:      BULLETIN
Impact:             LOW
Skill-Level:        NOVICE
Server-Version:     07 to 08
Updated-Date:       05-MAY-2000 15:24:52
References:
Attachments:        NONE
Content-Type:       TEXT/PLAIN
Keywords:           EXPORTINFO;
Products:           5/RDBMS;
Platforms:          GENERIC;

PURPOSE

This article provides a brief explanation on how to export a
file that is greater than 2Gig using the "volsize" parameter.

SCOPE & APPLICATION

                       Export VOLSIZE

This bulletin provides a brief explanation on the use of
the export parameter "volsize" for exporting a file to tape that
is greater than 2Gig.

Once you have decided that you need to perform the export with a
file greater than 2Gig it is recommended to export directly to
tape.

You will need to change the syntax of your export statement so
that export knows the name of the tape device and how much data
can be written to that tape device.

There are only 2 parameters that you need to change to do this :

1. FILE - The name of the tape device you are exporting to:
           e.g. /dev/rmt/0 .

2. VOLSIZE - The amount of data that can be written to one tape.

If the entire export file will fit onto a single tape, then a
volsize of 0 (variable length) can be used i.e. exp <other
options> volsize=0.

If the resultant export file is larger than a single tape, then
volsize needs to be set accordingly e.g. exp <other options>
volsize=<size>M.

Please note, there is a 4 Gigabyte limit to the volsize
parameter.

EXAMPLE OF EXPORTING DIRECTLY TO TAPE

A full database export to a QIC 150 (150 Megabytes capacity) to
a
tape device "/dev/rmt/0m",where the resultant file is 200M would
be exported using the following syntax:

  os> exp userid=system/manager full=y file=/dev/rmt/0M
volsize=145M

The volsize is set to 145M, even though the tape is a QIC 150
because there may not be exactly 150M of tape on the volume.

Once the export utility has written <volsize> to the tape, it
will prompt for the next tape:

"Please mount the next volume and hit <ret> when you are done."

To import from the resultant export on tape, the following
commands would be used :

  os> imp userid=system/manager full=y file=/dev/rmt/0M
volsize=145M

September 01, 2000 wallacel -- Thanks for the question regarding
      "performance tuning regarding OR", version 8.1.6

      You Asked
Tom:

I read a topic regarding performance tuning of OR.

it says:

correctly indexing on statements having an or clause and
multiple where conditions can be difficult.
while in previous versions it was essential to index at
least one column in each clause ORed together,the merging of
indexes in indexes in Oracle8 becomes potentially hazardous
to the performance.the solution is often to supress all indexes
except the most LIMITING for each table in the query.
Consider the following examples:
Given indexes on empno,ename, and deptno:

select ename,deptno,city,division from emp1
where empno=1 or ename='loney' or deptno=10;

Execution time:4400 seconds

execution plan
table access emp1 full

The solution:
Select /*+index(emp emp11) */ ename,deptno,city,division
form emp1 where empno=1 or ename='loney' or deptno=10;

Execution Time:280 seconds

Execution plan:
Table access emp1 rowid
   Table access emp11 index RS

=========================================================
My question is I don't understand why the solution is
better than the original. although execution time is much
shorter, but it don't make any sense to me.
since the condition is ORed together, I think full table
scan is better, even you use index for empno column,
you still need to access other row because ename and deptno
condition also need to be checked.

BUT,if they use index which is least(instead of most)
LIMITING,IT make a little bit sense to me, because we can first
get all rows from the index and check all other rows by other
condition.

Regards,

      and we said...
doesn't make sense to me either -- not enough information is
supplied.

The above query "select * from emp1 where empno=1 or
ename='loney' or deptno = 10" could not be answered via an index
range scan on any one of the three indexes above.  It could
be done via an index FULL SCAN.

My experience is the opposite of his above however.  That and
the text just doesn't correspond to the example.  The first plan
is using FULL, not the three indexes -- the second plan is
impossible for the query.  So either, there is a mistake in
the book or you've taken it out of context.

I created a table like this to demonstrate with:

create table emp
as
select object_id empno, owner||'.'||object_name ename,
       object_type city, mod(object_id,100) deptno,
       status division
  from all_objects
/

create unique index emp1 on emp(empno);
create index emp2 on emp(ename);
create index emp3 on emp(deptno);

Now, I'll run a test against it:

ops$tkyte@DEV816> set termout off
ops$tkyte@DEV816> set autotrace on explain
ops$tkyte@DEV816> set timing on
ops$tkyte@DEV816>
ops$tkyte@DEV816> select ename,deptno,city,division
  2    from emp
  3   where empno=1 or ename='loney' or deptno=10;

...
217 rows selected.

Elapsed: 00:00:00.05

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   CONCATENATION
   2    1     TABLE ACCESS (BY INDEX ROWID) OF 'EMP'
   3    2       INDEX (RANGE SCAN) OF 'EMP3' (NON-UNIQUE)
   4    1     TABLE ACCESS (BY INDEX ROWID) OF 'EMP'
   5    4       INDEX (RANGE SCAN) OF 'EMP2' (NON-UNIQUE)
   6    1     TABLE ACCESS (BY INDEX ROWID) OF 'EMP'
   7    6       INDEX (UNIQUE SCAN) OF 'EMP1' (UNIQUE)

ops$tkyte@DEV816>
ops$tkyte@DEV816> Select /*+index(emp emp1) */
ename,deptno,city,division
  2   from emp where empno=1 or ename='loney' or deptno=10;

...
217 rows selected.

Elapsed: 00:00:00.55

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=826 Card=415
Bytes=3
          0710)

   1    0   TABLE ACCESS (BY INDEX ROWID) OF 'EMP' (Cost=826
Card=415
          Bytes=30710)

   2    1     INDEX (FULL SCAN) OF 'EMP1' (UNIQUE) (Cost=26
Card=415)

ops$tkyte@DEV816>
ops$tkyte@DEV816> Select /*+full(emp ) */
ename,deptno,city,division
  2   from emp where empno=1 or ename='loney' or deptno=10;

....
217 rows selected.

Elapsed: 00:00:00.13

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=5 Card=415
Bytes=307
          10)

   1    0   TABLE ACCESS (FULL) OF 'EMP' (Cost=5 Card=415
Bytes=30710)

ops$tkyte@DEV816>
ops$tkyte@DEV816> set autotrace off
ops$tkyte@DEV816> spool off

As you can see -- totally the opposite of what was purported
above.  Maybe you can go to his website and ask for a further
explaination.

http://www.kevinloney.com/
September 01, 2000 VENKATARAMAN -- Thanks for the question regarding
      "LOG MINER", version 8.1.5

      You Asked
Hi,

Can I extract data from log files of one database through
logminer and apply those data to another database ?

regards

venkat

      and we said...
Not really.

Logminer will create sql inserts and deletes that in most cases
will replay a transaction for you.  It does however have some
limits and only can be used on the originating source datatbase.

Some of the limits are

o it does not handle all datatypes and data structures.  There
are some constructs you may use that it will not generate the
SQL for.

o it does not handle chained blocks and migrated blocks as yet.
It cannot generate the sql for that.

o since it operates on rowids -- the SQL it generates is only
useful in the database whence the logs came from.

We have a facility called a standby database if you wish to have
the logs shipped to another instance and applied their.  Its
purpose is to maintain a failover site in the event of a total
loss of the primary site.
September
      01, 2000 VENKATARAMAN -- Thanks for the
      question regarding "IMPORTING THE DUMP INTO DIFFERENT DATABASE HAVING
      DIFFERENT LOGICAL STRUCTURE", version 8.1.5

      You Asked
Hi,

Can I import a dump of one database into another database where
username and tablespace names are not matching with the source
database.  Ifso, how can I do ?

regards

venkat

      and we said...
Sure, you would use:

imp .... fromuser=OLD_USERNAME touser=NEW_USERNAME

imp will attempt to create the objects in the tablespace named
after the tablespace in the originating database and in the
event it cannot (due to a quota or the fact the tablespace does
not exist) it will create the object in the NEW_USERNAME's
default tablespace.
September 01,
      2000 Angela -- Thanks for the question
      regarding "exiting triggers and/or procedures", version 8.1.6

      You Asked
would like to know if there is anyway to exit out of a row level
trigger without letting record insert, without rolling back
entire transaction and without returning an error message.

      and we said...
Not directly.

There are ways to accomplish this.  One of the easiest is via a
VIEW.  Instead of exposing a real table to the applications --
you would expose a view.  For example, lets say you have a table
T.  You could:

rename t to t_table;
create view t as select * from t_table;
(revoke all on t_table from everyone)
(grant whatever on t_table to everyone that needs it)

Now, you can:

create or replace trigger T_trigger
instead of INSERT on T
begin
  if ( some_conditions_are_met ) then
       insert into t_table ( .... ) values
       ( :new.c1, :new.c2, ...... );
  end if;
end;
/

That trigger, on the view, will either insert the row into
T_table (and hence into the view on T_table) or not.  If it does
not insert into T_table -- the row just "disappears".

A more complex method can work on the real table with

o a package to maintain a state
o a before trigger
o an after for each row trigger
o an after trigger

The before trigger would simply reset the package state to
"empty".  The row level trigger would put into an array in the
package the primary key(s) of any row(s) that should not be
allowed to be inserted.  The after trigger would delete all of
those rows -- un-inserting them.

See

http://osi.oracle.com/~tkyte/Mutate/index.html
for more info on this concept.  It is very much like the
mutating table issue and the work around is identical.


Subject | Article | Last Updated (East coast time)
DIPLAY DATE BY DEFAULT | article only | Sep 02, 2000 08:49 am
Java with Oracle | article only | Sep 02, 2000 10:53 am
import problem.! | article only | Sep 02, 2000 01:03 pm
How to Scripts for oracle version 8.1.6 | article only | Sep 02, 2000 01:07 pm
Locking a row for writing lob data | article only | Sep 03, 2000 10:53 am
Long Raw Data (Urgent) | article only | Sep 03, 2000 11:00 am
Oracle 8.0 installation on Solaris x86 | article only | Sep 03, 2000 11:16 am
Should I repin an object kept in the shared pool after an instance restart? | article only | Sep 03, 2000 11:56 am
Check Tablespace | article only | Sep 04, 2000 10:13 am
A couple of questions | article only | Sep 04, 2000 10:21 am
Compare the Feature of Oracle 8i Standard and Oracle 8i Enterprice | article only | Sep 04, 2000 10:27 am
Refresh snapshot from none snapshot owner | article only | Sep 04, 2000 10:51 am
performance -- how many tps/tpm's | article only | Sep 04, 2000 11:45 am
The use of the host built-in in FORMS' DEVELOPER 6.0 | article only | Sep 04, 2000 03:51 pm
Snapshots from 2 different Databases into one instance/Schema | article only | Sep 04, 2000 03:53 pm
how to send email -- from forms | article only | Sep 05, 2000 06:51 am
setting at runtime Query_Data_Source_Name | article only | Sep 05, 2000 07:07 am
Question about database engine | article only | Sep 05, 2000 07:15 am
SQLJ directory listing | article only | Sep 05, 2000 08:36 am
Last friday of a month | article only | Sep 05, 2000 08:45 am
Conditions in a SQL select | article only | Sep 05, 2000 12:48 pm
Java options | article only | Sep 05, 2000 12:50 pm
Ora-error 14101 | article only | Sep 05, 2000 01:01 pm
Using Not Equal to Condition in the SQL Select Statement | article only | Sep 05, 2000 05:22 pm
Space Utilization within a block | article only | Sep 05, 2000 06:01 pm
Ordering a CONNECT BY | article only | Sep 05, 2000 06:25 pm
database trigger -- same type triggers fire in random order | article only | Sep 06, 2000 11:03 am
tablespace | article only | Sep 06, 2000 11:30 am
A few Queries | article only | Sep 06, 2000 12:44 pm
Data Compression during RMAN backup | article only | Sep 06, 2000 12:53 pm
bmp | article only | Sep 06, 2000 12:57 pm
Change management | article only | Sep 06, 2000 12:59 pm
DISPAY DATE IN FORM 'DD-MM-YYYY' | article only | Sep 06, 2000 01:11 pm
create table as select | article only | Sep 06, 2000 01:14 pm
Make an .exe of Oracle Project | article only | Sep 06, 2000 01:34 pm
db tuning | article only | Sep 06, 2000 02:58 pm
Time Comparison | article only | Sep 06, 2000 03:19 pm
SQL -- comparing a time STRING to sysdate | article only | Sep 07, 2000 08:52 am
Create a View Dynamically using PL/SQL stored procedure | article only | Sep 07, 2000 08:56 am
Few tables in SYSTEM schema are not exported | article only | Sep 07, 2000 09:07 am
.dmp file -- whats FORMAT71 | article only | Sep 07, 2000 09:22 am
Exhausted rollback segments -- v7.1 | article only | Sep 07, 2000 09:45 am
Transferring data via database link fails when the table has a LONG datatype | article only | Sep 07, 2000 01:50 pm
Retreiving object column from a table. | article only | Sep 07, 2000 02:20 pm
addredss | article only | Sep 07, 2000 02:30 pm
Does the number of tablespace effact performance? | article only | Sep 07, 2000 02:37 pm
Resizing Tables Smaller | article only | Sep 07, 2000 02:43 pm
Standby Init.ora file | article only | Sep 07, 2000 03:01 pm
Oracle ProC/C++ CGI | article only | Sep 07, 2000 03:48 pm
Invalid objects - ORA 2311 | article only | Sep 07, 2000 03:55 pm
Database creation - instance - RMAN use - | article only | Sep 08, 2000 11:16 am
Encrpt fields on table | article only | Sep 08, 2000 12:44 pm
hash_value | article only | Sep 08, 2000 12:45 pm
Password Encryption while connecting to sql*plus | article only | Sep 08, 2000 12:48 pm
Avoiding fragmentation | article only | Sep 08, 2000 12:55 pm
row(s) 1 - 55 of 55
September 02, 2000 ATHER -- Thanks for the question regarding "DIPLAY DATE BY DEFAULT ", version 7
You Asked
I WANT TO DISPALY DATE DD-MM-YYYY
ONLY USING THIS COMMAND SELECT SYSDATE FROM DUAL BECAUSE I DONT WANT TO USE THE
FOMATE MASK IN FORM .
and we said...
SQL> alter session set nls_date_format='dd-mm-yyyy';

you could put that into you login.sql (a startup script run by sqlplus) if you
like as well.
September 02, 2000 Sankalp -- Thanks for the question regarding "Java with Oracle", version 2.1
You Asked
Dear Tom,

Take for example I have to build an application which caters to
one of the following:

a) an Insurance application which will be used in one company
(one building) and only some part of it will be on internet
(Agent information system in case of insurance)

b) an Insurance  application which will be used in one company
as well as its branches(same building or diff city) and it has
some parts which will be on internet (Agent information system
in case of insurance)

c) an Insurance application which will be completely on net.

Please go through each of these cases carefully.

QUESTIONS:

i) For each of these cases which of the java technology
combinations will be used and why? Kindly be specific ?

ii)For each of these cases how will handle security issues?

iii)If I need to use only oracle tools to make each of these
applications ,which oracle tools will be used if the database is
Oracle.Kindly be specific ?

Thanks a lot in advance.

SANKALP
and we said...
1) for all three, depending on the needs of the user interface,
I would tend to go towards HTML as the "presentation" layer and
some combination of java/plsql to generate the HTML.  None of
the three cases above is different from the other cases as far
as I am concerned.  Whether the application is used in a
building, on the internet, or in a couple of buildings hooked
together via the internet -- they are all the same.

I want a UI that is easy to use and that I can upgrade from my
server.  The rules out installing anything on the client.
Everyone has a browser and that supports HTML and for most UI's,
simple HTML is more then sufficient (add a little tiny bit of
javascript here and there).

I myself tend to do things mostly in PLSQL since I build
database applications and PLSQL interfaces with "data" in SQL
databases much better Java does (in my opinion).  I can do the
same exact thing in Java as I do in PLSQL however.  The relevant
java technologies would be servlets, java server pages (JSP's)
and perhaps java stored procedures in the database (if you
wanted to do all java).

2) Security -- depends.  I would probably use SSL to obfusicate
the traffic between the client and server.  I would use the
database to secure the data.  Either via fine grained access
control (see
http://osi.oracle.com/~tkyte/article2/index.html
for details) or by encapsulating all access to data by stored
procedures which limit the access to only relevant information.
FGAC is alot more powerful as it allows us to use SQL from ANY
application against the data and still have security enforced.

In as much as the term security can mean many things to many
people -- thats about as far as I can go...  Don't know what
exactly your requirements are at this point...

3) Oracle JDeveloper is one tool that would be of use.  Oracle
Developer Server -- if you found that HTML was not sufficient --
would be a great way to deliver what looks like a client server
application to the client browsers as well.
September 02, 2000 -- Thanks for the question regarding "import problem.!", version 8.0
You Asked
hello sir,

I have following doubts/problems can u please help me..

(1) I took export from oracle 8.0.5 on linux then while trying
to import in oracle 8.0.4 on NT it is not importing. It is
displaying followin errors.

IMP-00010: not a valid export file, header failed verification
IMP-00021: operating system error - error code (dec 2, hex 0x2)
IMP-00000: Import terminated unsuccessfully

(2) when I use substr function in where clause of a query will
the query bipass index and lead to full table scan ?

(3) I want to restrict forms runtime session to one...ie when a
user click on short cut icon of my module/project only one
session should run on that client machine.  for more than one
session I want to display a message " Application already
running".  I didnot succeed with win_api_session.one_session,
can u please tell me other possible way..

thanks a lot for ur help to oracle community...

regs
mubeen
and we said...
1) you probably ftp'ed the file correct?  If so, it sounds like
you forget to set "bin" to true in the transfer and it
transferred in ascii mode -- corrupting the file.  Please verify
the file size on NT is the same as on Unix.

2) maybe -- depends on how you use it.
  select * from emp where ename = substr(:hostvar,1,20)

  will use an index on ename.

  select * from emp where substr(ename,1,20) = :hostvar

  will not.

  See
http://osi.oracle.com/~tkyte/article1/index.html
for how this is solved in Oracle8i release 8.1

3) verify you are using one_session correctly.  Refer to this
support note below:

Notes
=====
-- If you have other sessions opened, use the code shown in the
form from which you want to quit the current session.

-- Pass the following constants as a parameter for the
appropriate  version for which you are trying to detect if a
session is being  used:

   Version 4.5 -> 'ui23MDIroot_W32'
   Version 5.0 -> 'ui25MDIroot_W32'
   Version 6.0 -> 'ui60MDIroot_W32'

-- For the third parameter to WIN_API_SESSION.One_Session,
called (MATCHTYPE), you have a choice of Window, Module, or
Both. In order to work correctly with NT OS, you must pass
WINDOW.

Code
====

BASED ON A FORM CREATED IN FORMS 5.0.6.16.0

FORM 1
--IN WHEN NEW FORM INSTANCE TRIGGER--

DECLARE
REG BOOLEAN;

BEGIN
set_window_property(FORMS_MDI_WINDOW, TITLE, 'Session0');
reg := WIN_API_SESSION.One_Session('Session0', 'F50RUN32.EXE',
'WINDOW', FALSE, 'ui25MDIroot_W32', FALSE);
if reg then
  message('session exists');
  exit_form;
else
  message('session doesn''t exist');
end if;
END;

FORM 2
--IN WHEN NEW FORM INSTANCE TRIGGER--
set_window_property(FORMS_MDI_WINDOW, TITLE, 'Session0');
September 02, 2000 Atul -- Thanks for the question regarding "How to Scripts for oracle version 8.1.6", version Oracle 8.1.7
You Asked
Hi  Tom,

I would like to ask you (HOW-TO)

1. Scripts to Tune SQL statements (Various Methods ) .

2. Cold & Hot Backup  of Database

2. Online & Offline Restore of Database

3. General purpose scripts to monitors Database for proper
   functionality .
and we said...
1) There really aren't scripts for this but processes.  I use
autotrace -- see
http://osi.oracle.com/~tkyte/article1/autotrace.html
and tkprof/timed_statistics myself, see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76992/ch14_str.htm#1018
for that.  As well, OEM (Oracle Enterprise Manager) in the
performance pack has "query tuning helpers" that will look at
the sql you execute and suggest alternate ways to write it.

2 & 2) RMAN is the answer -- see
http://technet.oracle.com/doc/oracle8i_816/server.816/index.htm
for the docs on backup and recovery.

3) OEM is the answer for that.  OEM is the tool to do this. See
http://www.oracle.com/ip/deploy/database/system_mgmt/index.html?content.html
for more info.
September 03, 2000 justin -- Thanks for the question regarding "Locking a row for writing lob data", version 8.0.6
You Asked
I wrote a java servlet which should populate a Blob value into
the database,  but I am getting the following error:

java.io.IOExeception Error while doing write LobByteValue
java.sql.SQLException row containing the LOB value is not locked

I am using the follwing code for my insert
Connection dbcon = null;
ResultSet rs = null;
Statement stmt = null;
Blob myBlob = null;
InputStream inStream = null;

try{
    Properties props = new Properties();
    props.put("user","etscdvl");
    props.put("password","dvlp");
    props.put("server","dccts1001.cscoe.ac.com");
    props.put("database","enowotds");
    Class.forName("weblogic.jdbc20.oci.Driver");
    dbcon = DriverManager.getConnection
("jdbc20:weblogic:oracle", props);

String qry = "insert into mailbox
values(9,9,9,empty_blob(),'t',1,'2000-01-01','s')";
stmt = dbcon.createStatement();
stmt.executeUpdate(qry);

String qry2 = "select PDF from mailbox where id_internal=9";
stmt = dbcon.createStatement();
rs = stmt.executeQuery(qry2);

while(rs.next()){
    myBlob = rs.getBlob("PDF");
}

File binaryfile = new
File("/opt/WebLogicCommerce/server/public_html/keith/mmexs.pdf");

System.out.println("length of test file is " +
binaryfile.length());
inStream = new FileInputStream(binaryfile);
OutputStream os = null;

long size = myBlob.length();
byte[] buffer = new byte[65534];
int numBytes = inStream.read(buffer);
    while (numBytes > 0) {
    os.write(buffer, 0, numBytes);
    numBytes = inStream.read(buffer)
    }

    os.flush();
    os.close();

PreparedStatement pstmt = null;
String qry3 = "Update mailbox set PDF = ? where id_internal=9";
pstmt = dbcon.prepareStatement(qry3);
    pstmt.setBlob(1,myBlob);
    pstmt.executeUpdate(qry3);
}
catch(ClassNotFoundException cnfe){
}
catch(SQLException sqle){

}

My question is Do I need to lock the row previous to writing the
blob into the record? If so, how do I do that? I think the two
errors may be related to one another.  thanks
and we said...
JDBC, what whatever lame reason, has "auto commit" turned on
(which sort of defeats the whole point of a transactional
database).  Almost every Java/JDBC program should have:

  conn.setAutoCommit (false);

immediately after a connect.  That'll fix your issue above (with
regards to the row locking issue).

Here is a quick and dirty example for your reference:

import java.io.*;
import java.lang.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.*;

public class pdf
{
public static void main(String[] args) throws Exception
{
    int    length;

    DriverManager.registerDriver (new OracleDriver());

    Connection conn = DriverManager.getConnection
    // ("jdbc:oracle:oci8:@ora8i.us.oracle.com",
    ("jdbc:oracle:thin:@aria:1521:ora8i",
     "scott","tiger");

    conn.setAutoCommit (false);
    System.out.println( "connected..." );

    PreparedStatement insertStmt = conn.prepareStatement
           ("insert into t ( id, pdf ) " +
            "values ( 9, empty_blob() )");

    System.out.println
       ( "prepared statement for v8.x BLOB insert..." );

    PreparedStatement getStmt = conn.prepareStatement
         ("select pdf from t where id = 9 for update");

    System.out.println
       ( "prepared statement for v8.x BLOB select..." );

    insertStmt.executeUpdate();

    OracleResultSet rset81 =
         (OracleResultSet) getStmt.executeQuery();

    if ( rset81.next() )
    {
        OutputStream os =
            rset81.getBLOB(1).getBinaryOutputStream();
        System.out.println( "Got v8.x BLOB stream..." );

        File binaryfile = new File( "/tmp/zzzz" );
        System.out.println("length of test file is " +
                             binaryfile.length());
        InputStream is = new FileInputStream(binaryfile);

        System.out.println( "Moving data from IS to OS..." );
        byte buffer[] = new byte[32765];
        while ((length = is.read (buffer,0,32765)) != -1)
        {
            os.write( buffer, 0, length );
            System.out.println( "Wrote 32k..." );
        }

        is.close();
        os.close();
        rset81.close();
    }
    insertStmt.close();
    getStmt.close();
    conn.commit();
    conn.close();
}
}
Review & Followup
Rating: 4
WebLogic pooled connections and read/write Oracle LOB's March 23, 2001
Reviewer: Eric Ma (eric.ma@home.com) from Berkeley Heights, NJ USA
Justin:  You did everything right except for missing the "for update" part in
qry2.  This is a pure Oracle LOB issue - you NEED to lock a row any time you
want to insert/update value of a LOB field.

Tom:  The code you provided will not work from a WebLogic connection pool.  A
connection from a WebLogic connection pool cannot be casted to an
OracleConnection - therefore you will not be getting an OracleResultSet.  As
matter of fact, if you want to read/write Oracle LOB's using a WebLogic
connection pool, you cannot use Oracle's JDBC OCI nor thin driver for creating
the pool.  The only choice is to use WebLogic's jDriver/Oracle that comes with
Weblogic 5.1 and up, which is a Type 2 JDBC driver.

September 03, 2000 Lynn -- Thanks for the question regarding "Long Raw Data (Urgent)", version 8.1.5
You Asked
I have 2 tables with 2 columns each; first column is VARCHAR2 &
the second is LONG RAW - to store images - for both tables.

I have to insert records into the second table say 'NEW' based
on the first table say 'OLD' as per the following :
 - if the record already exists in NEW then update it with the
record in OLD
 - if the record is not there in NEW then insert it from OLD

We've been trying to do this thru VB. It allows us to update but
does not allow us to insert a new row. We can't figure out what
the problem is.

Could you please suggest a way to tackle this?

Thanks in advance,
Lynn
and we said...
Well, without an error message or any other information -- I
cannot even guess what the issue might be.  Dealing with long
raws is pretty difficult (in 8.1.5, you really should be using a
BLOB, not a LONG RAW).

If someone asked me to do this -- my steps might be (just to get
it done right now)...  Say the tables columns are NAME varchar2
and data long raw:

o delete from NEW
   where exists ( select NULL
                    from OLD
                   where old.name = new.name )

o use the command line tool EXP and export the OLD table

o rename OLD to OLD_HOLD
o rename NEW to OLD
o use the command line tool IMP with ignore=y and import OLD
(which is really NEW for now)

o rename OLD to NEW
o rename OLD_HOLD to OLD

If you had used blobs -- we could have simply run 2 sql
statements to update the existing rows and insert the new rows
from sqlplus.
September 03, 2000 Basid -- Thanks for the question regarding "Oracle 8.0 installation on Solaris x86", version 8.0.5
You Asked
Tom Hi,
I have Solaris 2.7(x86) for intel running on a server and I have Oracle Database
8.0.5 for Sun Sparc. My doubt is that can I install this database on the above
o/s. If not then is oracle database for Solaris x86 avialable, I browsed Oracle
site on the web but could not find Oracle Database versions available for
Solaris x86 platform. Thanks for your help.

Regards,
Basid.
and we said...
No, you cannot install the SPARC binaries on the x86 CISC hardware.

You can order the media from
http://store.oracle.com/
(trial licenses there as well).  We do not have every platform on technet for
download.
September 03, 2000 Ravi -- Thanks for the question regarding "Should I repin an object kept in the shared pool after an instance restart?", version 8.0.4.4
You Asked
Tom,

Let us assume that I pinned an object and hence it is kept in
the shared pool. If I restart the instance and called the
particular object, will it pinned on its own and kept in the
shared pool?

My questions is, Is the pinning in shared pool effective only
for the duration of the instance or for ever (until next unkeep
is issued). Should I repin the object every time I restart the
instance.

Thanks in adv.

Regards
Ravi
and we said...
You need to repin upon restart if you really truely want it
pinned.  Pinning is something that a restart will "lose".
September 04, 2000 shah -- Thanks for the question regarding "Check Tablespace", version 7.3.3.6
You Asked
Hi Tom,

I'd like to check the tablespace information that similar to OEM
display, because I'dont have OEM installed at console terminal.

I've the script that will show the file name, file id,
tablespace name, total bytes, free bytes and used bytes but the
problem with my sql statement is it will show the file name that
reside in dba_free_space only.

The script that I used as below :

compute sum of used on tbs
break on tbs
select a.file_name,b.file_id,b.tablespace_name tbs,a.bytes
total,sum(b.bytes) free,a.bytes - sum(b.bytes) used
from dba_data_files a,dba_free_space b
where a.file_id = b.file_id
and a.tablespace_name = b.tablespace_name
group by a.file_name,b.file_id,b.tablespace_name,a.bytes

I hope that you can modify my script to be shown as OEM display.
and we said...
The query you seem to be after would be:

select a.file_name,
       a.file_id,
       a.tablespace_name,
       a.bytes allocated,
       nvl(b.free,0) free,
       a.bytes-nvl(b.free,0) used
  from dba_data_files a,
       ( select file_id, sum(bytes) free
           from dba_free_space
          group by file_id ) b
 where a.file_id = b.file_id (+)
/

Using an inline view like that -- especially when one table
needs to be aggregated and the other does not, it extremely
powerful and greatly simplfies the query.

The use of the outer join (+) causes the query to "make up" a
NULL row for B when there is no match for a row in A.  In effect
-- that query returns all rows from A and IF there is a match in
B for that row, will join it, else it will supply all NULLS for
it.
September 04, 2000 Raja -- Thanks for the question regarding "A couple of questions ", version 8.1.5
You Asked
Dear Tom ,
I submit below a couple of questions :

1.NLS Character Set for Malay Language .
-----------------------------------------
Please let me know the NLS Character Set for Malay Language .
Please note that the Malay Language uses English Alphabets as
their language Script .

Also is the Translation of the Oracle Error Messages in Malay
Language available now ?

2.SQL Loader and NOLOGGING
--------------------------
We were doing a large data load using SQL Loader ( conventional
mathod ) and it was generating a very high amount of  redo .
We made the Tablespace into which the Data Comes in as NOLOGGING
and also the respective tables as NOLOGGING .
But it sems to have no effect and continues to generate the redo
as before .
Why is it so ?

3.Oracle Designer and Application System Back up :
------------------------------------------------
While doing logical backup of the Application system , Oracle e
Desginer first extracts to a to set of Archive tables  ( around
15 tables whose name starts with XT_ ) and then only Exports it
.
Here also there is a large redo gets generated  eventhough we
have made all these XT_ Tables as NOLOGGING .
Here again NOLOGGING does not seem to have any effect .
Is there a way for stopping the redo geneation ?

Why does Oracle generates lot of redo during Export ?

Thanks and Regards .

Raja
and we said...
1) You should be able to use WE8ISO8859P1 or UTF-8 (utf-8 should
be able to handle anything).

I do not believe the messages are translated into Malay at this
point in time.  The list I have says "no".  the list is:

Languages
==========
* New translation.
† Translated software messages available.

American English
Arabic †
Bengali
Brazilian Portuguese †
Bulgarian
Canadian French
Catalan †
Croatian
Czech †
Danish †
Dutch †
Egyptian
English
Estonian
Finnish †
French †
German †
German Din
Greek †
Hebrew †*
Hungarian †
Icelandic
Indonesian
Italian †
Japanese †
Korean †
Latin American Spanish †
Latvian
Lithuanian
Malay
Mexican Spanish
Norwegian †
Polish †
Portuguese †
Romanian †
Russian †
Simplified Chinese †
Slovak †
Slovenian
Spanish †
Swedish †
Thai
Traditional Chinese †
Turkish †
Ukrainian
Vietnamese

2)  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:485221567528
You want to use direct path loads if you are wanting to bypass
redo generation.  ANYTHING that does inserts (insert /*+ Append
*/ being the exception) will generate redo and undo.  direct
path and unrecoverable operations avoid redo/undo.

3) same reason as above.  They are doing an insert into
operation and this must be logged (it is our whole purpose of
being)...
September 04, 2000 Thang -- Thanks for the question regarding "Compare the Feature of Oracle 8i Standard and Oracle 8i Enterprice", version Oracle 8i
You Asked
Hi Tom,
Could you tell me the difference (about feature) of Oracle 8i
Standard and Oracle 8i Enterprise ?
Thanks
and we said...
The getting to know Oracle8i guide breaks this out nicely.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/ch4.htm#73594
for the details.
September 04, 2000 Eli -- Thanks for the question regarding "Refresh snapshot from none snapshot owner", version 8.0.6
You Asked
Hi
Our database is divide to 4 areas APPLICATION, REF_MASTER,
REF_READ,(snapshot of REF_MASTER) and CONNECT ,our batch process
are connect to the CONNECT user.the CONNECT user have privilege
to select from all snapshot and update all application tables
.Some of our batch process are need to refresh some snapshot
during the process.
We try to create the following stored function located in
REF_READ and execute it from the CONNECT and we failed to do
this by getting ORA-23401
.There was a very queer think if we add to the function the
following line "SELECT USERNAME INTO USERNAME1 FROM USER_USERS"
the value puts in USERNAME1  is REF_READ .so way the function
failed ?
We don't  want to add system privilege to our CONNECT account
(we know about alter any snapshot ) Can you help us to implement
this by the stored function ?

CREATE OR REPLACE FUNCTION refresh_tab
 ( p_tb_name VARCHAR2)
RETURN NUMBER
IS
BEGIN
      DBMS_SNAPSHOT.REFRESH(p_tb_name,'C');
    RETURN 0;
 EXCEPTION
    WHEN OTHERS THEN
        RETURN sqlcode;
END;
/

Tnx
and we said...
I don't think this is a privileges problem but rather a name
resolution issue.  The ability to run dbms_snaphost has been
conveyed to connect -- what connect is probably doing is not
passing a fully qualified object name to refresh_tab -- hence
dbms_snapshot.refresh is attempting to refresh
CONNECT.snapshot_name -- which does not exist.  This example
shows how this works.  P1 is unqualifed -- P2 has the correct
schema name attached.  See what happens in each case:

SQL> create snapshot foo as select * from dual;
Materialized view created.

SQL> create or replace procedure p1
  2  as
  3  begin
  4          dbms_snapshot.refresh( 'FOO', 'C' );
  5  end;
  6  /

Procedure created.

SQL> create or replace procedure p2
  2  as
  3  begin
  4          dbms_snapshot.refresh( 'OPS$TKYTE.FOO', 'C' );
  5  end;
  6  /

Procedure created.

SQL>
SQL> grant execute on p1 to public;

Grant succeeded.

SQL> grant execute on p2 to public;

Grant succeeded.

SQL> drop user a cascade;

User dropped.

SQL> grant create session to a identified by a;

Grant succeeded.

SQL>
SQL> connect a/a
Connected.
SQL>
SQL> exec ops$tkyte.p1
BEGIN ops$tkyte.p1; END;

*
ERROR at line 1:
ORA-23401: snapshot "A"."FOO" does not exist
ORA-06512: at "SYS.DBMS_SNAPSHOT", line 604
ORA-06512: at "SYS.DBMS_SNAPSHOT", line 661
ORA-06512: at "SYS.DBMS_SNAPSHOT", line 641
ORA-06512: at "OPS$TKYTE.P1", line 4
ORA-06512: at line 1

SQL> exec ops$tkyte.p2

PL/SQL procedure successfully completed.

SQL>
SQL> connect /
Connected.
September 04, 2000 -- Thanks for the question regarding "performance -- how many tps/tpm's ", version 8.1.6
You Asked
how many "transactions per second" or "transactions per minute"
can oracle achieve ?
and we said...
See
http://www.tpc.org/
for standard benchmark results.  This is a truely impossible
question to answer fully as your definition of transaction will
differ from mine will differ from someone else.  As will your
concept of how big "big" is and how small "small" is and so one.
September 04, 2000 felix -- Thanks for the question regarding "The use of the host built-in in FORMS' DEVELOPER 6.0", version 6.0
You Asked
Tom:
When i use the HOST built-in in a FORM'S DEVELOPER 6.0
program(PL/SQL unit program), the execution control don't return
to the program until the HOST finishes.
Is there any way to use this built-in or another with
asyncronous execution?
thanks, for your attention.
Felix.
and we said...
It might vary by version (win95, win98, winNT, win2k) but
something similar to:

host( 'cmd /c "start PROGRAM"' );

should work.  On Win2k -- the above works if PROGRAM is is
either in the PATH or referred to with a fully qualified path
that does not have any spaces....

On Win95/98, it might be a little different.  You'll have to
consult the OS documentation for those to see how to make the OS
do this.
September 04, 2000 ajeet -- Thanks for the question regarding "Snapshots from 2 different Databases into one instance/Schema", version 8.0.5
You Asked
Hi Tom ,

I have been getting snapshots(updatable or Fast) of one Database
into my database..I want to take snapshot of 2 Tables of another
database into the same instance(where I am getting snapshot from
one database ).Is it possible to do ? Please note that all the
databases are oracle having same version.But
the the two source instances are on two  different unix machine
and the target (where I am getting snapshot ) is a diiferent
instance..If yes please suggest what are the different steps I
need to follow.

Thanks
Ajeet.
and we said...
Yes, you can do this.  All you need do is setup another database
link.  Once you have the dblinks setup, so you can "select *
from dual@the_other_site", you can just create your snapshot
just like you did for the first site.  It'll be no different
then just using 1 site was.
September 05, 2000 John -- Thanks for the question regarding "how to send email -- from forms", version forms4.5
You Asked
Hi:
   Here is my question : How to send email with forms4.5? Where
can I find the document about that?

   I am a Chinese,and I cannot read English very well.So please
tell(or send) me with details.   Thank you.
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:319216860351
for how to get started.  See the documentation for your
EMAIL package for info on how to OLE automate it.
September 05, 2000 Petr -- Thanks for the question regarding "setting at runtime Query_Data_Source_Name ", version 6.0.8.10.3
You Asked
Hello Tom,

I have three complex views that display data for three different
regions. ('Crosstab' views using 'Sum', 'Decode' and 'Group by'
syntax). The views are recreated at different frequencies using
native dynamic SQL. While the structure of the views is
identical the source columns aren't.
The views are querying multiple tables including a main table
with about 500k records. Performance is therefore an issue.

I would like to use only one form and change dynamically the
data source at runtime depending on the users' choices. So, the
questions are:

a) Can I use as Query_data_source_type 'table' (which would be
appropiate for a view) and still change the
Query_Data_Source_Name dynamically?
The docs do not mention any restrictions, but I get frm-413810
'Cannot set the blocks query data source'.

b) Do I have to expect a significant performance degradation if
I use a 'FROM clause query' as data source (which should be
dynamically changeable)?

c) Do I have to expect problems if at runtime one user sets the
data source to view1 and another at the same time to view2?

Many thanks in advance!
Petr
and we said...
The way I used to do it in Forms was to

o build the block on an unqualified tablename (by that I mean
the block would be built on "SELECT * FROM EMP" not "SELECT *
FROM SCOTT.EMP".  EMP is unqualified

o at run time, the user would pick what "emp" really was and
create a private synonym EMP for thatowner.thattable.

o forms would issue "select * from EMP" and the database would
figure out what emp meant at that point in time.

Another option in Oracle8i would be to build the form on a
procedure instead of a table/view.  This procedure can return a
dynamically opened ref cursor.  so the procedure could look
like:

...
  begin
     open p_cursor for 'select * from ' || p_tname;
  ......

where p_cursor was a ref cursor type.  In this fashion, you
procedurally decide what to query at runtime using whatever
logic you want.

The FROM clause query will work as well.

None of the above will materially affect the performance of the
query.  The query itself will execute as rapidly as before --
regardless of the approach (given the above 3 approaches).

As for (c) above -- it would only be an issue if you use private
synonyms and more then one user used the same login id.
Otherwise -- no, it will not be a problem.
September 05, 2000 -- Thanks for the question regarding "Question about database engine", version 8.0.5
You Asked
First of all, excuse my english .

Some one told me that , when the database engine analizes the
"where" clause of a sql sentence , if you put an alias to then
names of tables ,  it evaluates the conditions from bottom to
top  . And if you don´t put aliases , evaluates the conditions
in the "where" clause from top to bottom.

Is it true? , an if it is , what´s the reason?

Coold you tell me if there is any documentation about how works
the optimizier to analize a sql sentence ?

Thank you.
and we said...
See
http://technet.oracle.com/doc/server.804/a58246/toc.htm
for many of the details but...

There are 2 modes of optimization -- Rule Based Optimization
(RBO) and Cost Based (CBO)..

The RBO processes queries according to rules.  In general the
rules are "process the FROM list right to left using the right
most table as the 'driving' table", "process the where clause
from the bottom up".  Of course, the existence (or lack thereof)
of indexes and such will change the order of these rules but in
general -- right to left, bottom up.  Aliases do not come into
the picture.

The CBO on the other hand uses statistics to figure out the join
order and the best way to apply the predicate.  There is no
right to left or bottom up rules of thumb -- it figures out how
it wants to do it at runtime.
September 05, 2000 steve -- Thanks for the question regarding "SQLJ directory listing", version 8.1.6
You Asked
Hi Tom,

I'm looking at using SQLJ to return an array of filenames
in a directory for subsequent loading via utl_file.

I've seen the array example in your archive but it doesn't
quite fit with what I'm trying to do:

I don't think I need or want a connection context (other
than perhaps to look at the TYPE defined?).

    // create a new ARRAY object
    int elements[] = { 300, 400, 500, 600 };
    ArrayDescriptor desc =
ArrayDescriptor.createDescriptor("NUM_VARRAY", conn);
    ARRAY newArray = new ARRAY(desc, conn, elements);

So if anything I just want to use the connection of the
calling PL/SQL procedure and not have to reconnect.
(I've never quite understood this bit, PL/SQL just uses
current connection...)

Is there a way I can return an array without creating a
new connection?

Thanks

Steve
and we said...
Have you looked at
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:439619916584
a temporary table might be more "natural" for all involved...

If you want to do this with an ARRAY, you'll be using jdbc --
not SQLJ.  I could look like this:

ops$tkyte@DEV816> grant javasyspriv to ops$tkyte
  2  /
Grant succeeded.

That is needed to read directories.  Beware -- it is an
extremely powerful grant.

ops$tkyte@DEV816> create or replace type fileList as table of
                             varchar2(255)
  2  /

Type created.

ops$tkyte@DEV816> create or replace
  2     and compile java source named "DirList"
  3  as
  4  import java.io.*;
  5  import java.sql.*;
  6  import oracle.sql.*;
  7  import oracle.jdbc.driver.*;
  8
  9  public class DirList
 10  {
 11  public static ARRAY getList(String directory)
 12                               throws SQLException
 13  {
 14      File path = new File( directory );
 15
 16      Connection conn =
 17            new OracleDriver().defaultConnection();
 18      ArrayDescriptor descriptor =
 19        ArrayDescriptor.createDescriptor( "FILELIST", conn );
 20      return new ARRAY( descriptor, conn, path.list() );
 21  }
 22
 23  }
 24  /

Java created.

ops$tkyte@DEV816> create or replace
  2  function get_dir_list( p_directory in varchar2 )
  3    return fileList
  4  as language java
  5  name 'DirList.getList( java.lang.String )
  6        return oracle.sql.ARRAY.ARRAY';
  7  /

Function created.

ops$tkyte@DEV816> declare
  2      l_files  fileList;
  3  begin
  4      l_files := get_dir_list( '/tmp' );
  5
  6      for i in 1 .. l_files.count
  7      loop
  8          dbms_output.put_line( l_files(i) );
  9      end loop;
 10  end;
 11  /
lost+found
.rpc_door
ps_data
.pcmcia
.X11-unix
.X11-pipe
page.html
owinst.log
wwvcb.log
mpAwaWAs
mp3saOFs
wwvcbus.log
sbddl.log
help.log
helpctxs.log
helprela.log
ups_data
helpindx.log
wwvsbus.ctl
tkyte.dbg
exec29047
mpljaa3p
mpwUaGCo
mpUQaq6l
mpYxaizE
mpNcaGOW
mpzqayTW
mp1ra4wY
mp77aqXl
.removable

PL/SQL procedure successfully completed.

ops$tkyte@DEV816>
September 05, 2000 aparna -- Thanks for the question regarding "Last friday of a month", version oracle 7.3
You Asked
Hello Tom

I want to get the last friday of a month using sqlplus
or pl/sql ?
How can I do this ?
Thanks.

aparna.
and we said...
We can do this with:

  2         decode( to_char(last_day( dt ),'d'),
  3                      6, last_day( dt ) ,
  4                      next_day(last_day( dt ) ,'fri')-7 )

that takes the date field DT and finds the last day in that
month.  It looks at the day of the week (6 = friday in my
calendar -- verify with yours) and says if the last day is
friday -- return last_day, else return the next friday from the
last day minus 1 week....

Here is an example:

ops$tkyte@DEV816> create table t ( dt date );

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> begin
  2      for i in 1 .. 12 loop
  3          insert into t values
  4          ( to_date('2000'||to_char(i,'fm00'), 'yyyymm') );
  5      end loop;
  6  end;
  7  /

PL/SQL procedure successfully completed.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> select dt,
  2         decode( to_char(last_day( dt ),'d'),
  3                      6, last_day( dt ) ,
  4                      next_day(last_day( dt ) ,'fri')-7 )
  5    from t
  6  /

DT        DECODE(TO
--------- ---------
01-JAN-00 28-JAN-00
01-FEB-00 25-FEB-00
01-MAR-00 31-MAR-00
01-APR-00 28-APR-00
01-MAY-00 26-MAY-00
01-JUN-00 30-JUN-00
01-JUL-00 28-JUL-00
01-AUG-00 25-AUG-00
01-SEP-00 29-SEP-00
01-OCT-00 27-OCT-00
01-NOV-00 24-NOV-00
01-DEC-00 29-DEC-00

12 rows selected.
Review & Followup
Rating: 2
Simpler Way December 03, 2001
Reviewer: Jason Bucata from Ft Worth, TX USA
This:

next_day(last_day(dptr_date) - 7, 'FRI')

is simpler.

September 05, 2000 -- Thanks for the question regarding "Conditions in a SQL select", version 7.3
You Asked
Hi Tom,

The problem I am facing is as follows :
I need to select the values depending on conditions, I have an
example that can help explain.

IF acc = 'Y' AND (l_type = 'CONVERSION' OR (l_type in ('LEASE',
'RENT') AND rev_type = 'BASE')) THEN
   base_adj = adj_amt
END IF

This condition needs to be used for the base_adj only, and not
for the other columns that are being selected in the same
select,
hence I cannot put this as a part of the WHERE clause.
I tried using decode, but it does not allow conditions like OR
and AND.

Please let me know how this can be done.
thanks in advance
Vivek
and we said...
Decode can do that.... consider:

ops$tkyte@ORA8I.WORLD> create table t
  2  ( acc char(1),
  3    l_type varchar2(20),
  4    rev_type varchar2(20),
  5    base_adj int,
  6    adj_amt int );

Table created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> insert into t values
  2  ( 'Y', 'CONVERSION', 'BASE', 1, 0 );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into t values
  2  ( 'Y', 'LEASE', 'BASE', 1, 0 );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into t values
  2  ( 'Y', 'RENT', 'BASE', 1, 0 );

1 row created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> insert into t values
  2  ( 'N', 'CONVERSION', 'BASE', 1, 0 );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into t values
  2  ( 'Y', 'LEASE', 'XXXX', 1, 0 );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into t values
  2  ( 'Y', 'YYYYY', 'BASE', 1, 0 );

1 row created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select acc, l_type, rev_type,
  2         decode( acc,
  3          'Y', decode( l_type,
  4                       'CONVERSION', adj_amt,
  5                       decode( l_type||'/'||rev_type,
  6                               'LEASE/BASE', adj_amt,
  7                               'RENT/BASE',  adj_amt,
  8                                base_adj )
  9                     ),
 10          base_adj ) real_value
 11  from t;

A L_TYPE               REV_TYPE             REAL_VALUE
- -------------------- -------------------- ----------
Y CONVERSION           BASE                          0
Y LEASE                BASE                          0
Y RENT                 BASE                          0
N CONVERSION           BASE                          1
Y LEASE                XXXX                          1
Y YYYYY                BASE                          1

6 rows selected.

ops$tkyte@ORA8I.WORLD>
September 05, 2000 Rajeev -- Thanks for the question regarding "Java options", version 8i
You Asked
Tom,

I am trying to find online documentation regarding
Java options on oracle 8.1.5.0.0  running on solaris.
I am trying to learn what java options are available
with Oracle 8i and if we have them.
I am new to Java but am very familiar with SQL and PL/SQL.

I just want to know what java options are available
and hopefully some examples explaining them.

I have been trying to run some of the java code that
you have provided in answering some of the queries.
I keep getting errors such as java system class not loaded.

Hence I am trying to find whether our DBA has installed
all of the java options.

Thanks for your help.
Rajeev
and we said...
The easiest way to see if you have the jserver option is:

$ sqlplus

SQL*Plus: Release 8.1.5.0.0 - Production on Tue Sep 5 12:50:50
2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to:
Oracle8i Enterprise Edition Release 8.1.5.0.0 - Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

ops$tkyte@ORA8I.WORLD>

The banner tells you right off.  See the getting to know
Oracle8i guide for a list of available options and what comes
with what...
http://technet.oracle.com/doc/server.815/a68020/toc.htm
....
September 05, 2000 Vinnie -- Thanks for the question regarding "Ora-error 14101", version 8.1.5
You Asked
Tom

I am getting the following error:

ORA-14101 partition extended table name cannot refer to a
synonym

     Cause: An attempt was made to use partition-extended table
name syntax in conjunction with synonym name which is illegal.

     Action: Correct the statement and re-enter it.

What could the cause of this be?

My Code;

( "SELECT e.serseq, hi.hostname, el.eventname, e.eventid,
e.eventtime,....
 FROM connections partition($t_day) c,
.....

where t_day is:

    # Create t_day
    #
    $sth = $dbh1->prepare( "SELECT TO_CHAR( 'MONDDYYYY' ) FROM
dual" )
        or die "Couldn't prepare statement: " . $dbh1->errstr;

    $sth->execute()
        or die "Couldn't execute statement: " . $sth->errstr;

    while ( @data = $sth->fetchrow_array() )
    {
        $t_day = $data[ 0 ];
    }
and we said...
It means that connections is a synonym and we don't allow for
the partitioned extended name to be used after a synonym:

tkyte@TKYTE816> create synonym foo for partitioned;
Synonym created.

tkyte@TKYTE816> select * from foo;

         X          Y Z
---------- ---------- ---------
         2          1 01-JAN-94
         1          1 01-MAR-95

tkyte@TKYTE816> select * from foo partition(part_1);
select * from foo partition(part_1)
              *
ERROR at line 1:
ORA-14101: partition extended table name cannot refer to a
synonym

Use the real tablename.
September 05, 2000 -- Thanks for the question regarding "Using Not Equal to Condition in the SQL Select Statement", version 7.3
You Asked
Hi Tom,
  I am facing a problem - using not equal to condition in the SQL Select
statement. Let me explain it in more details with the following example-

if acc_type = 'Y' then
    IF l_type in ('LEASE','RENT') then
        IF rev_type = 'BASE' then
             IF line_amt <> 0 then
                 billed_days = line_quantity
             END IF
        END IF
    END IF
END IF

Decode can be used for the above condition but how to implement the ' NOT EQUAL
TO' condition in Decode statement.

Please let me know how to resolve this problem.
Thanks in advance
Vidya
and we said...
That is easy:

decode( line_amt, 0, 'what it should be when line_amt=0',
                     'what it should be when line_amt<>0' );

I believe:

decode( acc_type, 'Y',
          decode( rev_type, 'BASE',
              decode( line_amt, 0, NULL,
                      decode( l_type, 'LEASE', line_quantity,
                                      'RENT',  line_quantity,
                                       NULL
                            )
                    ),
                   NULL ),
           NULL )

will do it -- returns NULL is the predicate is not satisfied.  It says:

  if ( acc_type = 'y' )
  then
      if ( rev_type = 'base' )
      then
          if ( line_amt = 0 )
          then
               return null;
          else
               if ( l_type = 'lease' ) or ( l_type = 'rent' )
               then
                   return line_quantity;
               else
                   return null;
               end if;
          end if;
      else
          return null;
      end if;
  else
     return null;
  end if;
September 05, 2000 Dan -- Thanks for the question regarding "Space Utilization within a block", version 8.0.5
You Asked
I have a database that contains several multiple gig tables that
are cleaned up periodically by the archiving of old data.  I
need to find a way of telling how much actual free space is
available within the blocks of the table after the archiving
process deletes a number of records. After a certain point we
need to reclaim the free space to keep the database below 1T.
and we said...
If you analyze the table, then

select avg_space*num_blocks
  from user_tables
 where table_name = 'XXXXX'

should give you that.

...
AVG_SPACE NUMBER

Average amount of free space, in bytes, in a data block
allocated to the table
.....

see also
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
If possible, you might want to look at partitioning for these
large tables and partition by the value you "archive" by.  In
that fashion -- you can implement rolling windows of data that
do not have to ever be deleted from -- you'll just take "old"
stuff and age it off the end of the partition.  Much more
efficient in the long run.
September 05, 2000 Roberto -- Thanks for the question regarding "Ordering a CONNECT BY ", version 8.05
You Asked
Hi Tom,

I am using INDEX and HINT to order a connect by. The problem is
that the first hiararchical level is NOT order, but all the
other levels are! How is that possible?

Thanks

Roberto.

Here is my index, and the query:

create index ACCOUNT_name_idx on account(cd_own_acc, nm_acc);
(there are also indexes on the primary key!)

select  /*+ INDEX(account ACCOUNT_code_owner_idx ) */
LPAD(' ',2*(LEVEL-1))||nm_acc as nm_acc
from Account
where cd_cpy = 1
start with cd_cpy = 1 and cd_own_acc is null
connect by prior cd_acc = cd_own_acc ;
and we said...
It is using the index in the connect by component since that is
"connect by prior cd_acc = cd_own_acc" and cd_own_acc is
indexed.

It cannot use that index to "start" the query though -- that
predicate is

  "cd_cpy = 1 and cd_own_acc is NULL"

but since totally null index entries are never made in a btree
index -- and nm_acc is probably allowed to be NULL -- that
predicate simply cannot be processed via a btree INDEX -- it
would miss rows such that cd_own_acc is null and nm_acc is null.
 Even if nm_acc is not null -- the cd_own_acc would tend to full
scan.

Consider this example, note the difference in the two plans:

ops$tkyte@ORA8I.WORLD> create table account
  2  ( cd_own_acc number,
  3    nm_acc number,
  4    cd_cpy number,
  5    cd_acc number
  6  );

Table created.

ops$tkyte@ORA8I.WORLD> create index ACCOUNT_name_idx
  2  on account(cd_own_acc, nm_acc);

Index created.

ops$tkyte@ORA8I.WORLD> set autotrace on explain

ops$tkyte@ORA8I.WORLD> select   /*+ INDEX(account
ACCOUNT_code_owner_idx ) */
  2  LPAD(' ',2*(LEVEL-1))||nm_acc as nm_acc
  3  from Account
  4  where cd_cpy = 1
  5  start with cd_cpy = 1 and cd_own_acc is null
  6  connect by prior cd_acc = cd_own_acc ;

no rows selected

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1
   1    0   FILTER
   2    1     CONNECT BY
   3    2       TABLE ACCESS (FULL) OF 'ACCOUNT' (Cost=1 Card=1
   4    2       TABLE ACCESS (BY USER ROWID) OF 'ACCOUNT'
   5    2       TABLE ACCESS (BY INDEX ROWID) OF 'ACCOUNT'
   6    5         INDEX (RANGE SCAN) OF 'ACCOUNT_NAME_IDX' (NON-

That begins with a FULL scan as the index *cannot* be used --
it would miss data... Now, let's try it with a different table

ops$tkyte@ORA8I.WORLD> drop table account;

Table dropped.

ops$tkyte@ORA8I.WORLD> create table account
  2  ( cd_own_acc number,
  3    nm_acc number NOT NULL,
  4    cd_cpy number,
  5    cd_acc number
  6  );

Table created.

ops$tkyte@ORA8I.WORLD> create index ACCOUNT_name_idx
  2  on account(cd_own_acc, nm_acc);

Index created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select   /*+ INDEX(account
ACCOUNT_code_owner_idx ) */
  2  LPAD(' ',2*(LEVEL-1))||nm_acc as nm_acc
  3  from Account
  4  where cd_cpy = 1
  5  start with cd_cpy = 1 and cd_own_acc is null
  6  connect by prior cd_acc = cd_own_acc ;

no rows selected

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1
   1    0   FILTER
   2    1     CONNECT BY
   3    2       TABLE ACCESS (BY INDEX ROWID) OF 'ACCOUNT'
   4    3         INDEX (RANGE SCAN) OF 'ACCOUNT_NAME_IDX' (NON-
   5    2       TABLE ACCESS (BY USER ROWID) OF 'ACCOUNT'
   6    2       TABLE ACCESS (BY INDEX ROWID) OF 'ACCOUNT'
   7    6         INDEX (RANGE SCAN) OF 'ACCOUNT_NAME_IDX' (NON-

ops$tkyte@ORA8I.WORLD> set autotrace off

There it used the index to "start with" as well as "connect
by".

Can you make that modification?
September 06, 2000 greeshma -- Thanks for the question regarding "database trigger -- same type triggers fire in random order", version oracle 8.0.5
You Asked
hi!tom
i have two t1,t2 row type triggers  after insert
or delete or update firing on a
single table parent table simelteneously.trigger t1 pops up data
into a parent
temp table and t2 when fired goes to the child table
and selects more than one child rec.corresponding
with a common column from the parent and dumps data into
another temp table.
iam passing a sequence number into both the tables.where
parent temp table takes the nextval and child temp table
takes the corrval of the sequence.
but when the triggers are fired i am getting an error saying
ERROR at line 1:
ORA-08002: sequence t_SEQ.CURRVAL is not yet defined in this
session
ORA-06512: at "GL.t2", line 66
ORA-04088: error during execution of trigger 'GL.t2'
kindly help me.

thankx
and we said...
sounds like you are counting on the triggers to fire in some
order but -- they do not.  All same type triggers fire in some
undefined order.  You cannot rely on T1 to fire before T2.  You
should instead write a procedure P1 and a procedure P2 and one
trigger T that calls P1 and then P2 in order if they must be
ordered.

Here is an example showing I can make it work (or not) simply by
dropping and recreating the triggers. Do not count on the
"apparent" order of last created trigger fires first -- it is a
fluke -- it is not guaranteed -- you must procedurally order the
triggers as I described above to make this work correctly.

ops$tkyte@DEV816> create table t ( x int );
Table created.

ops$tkyte@DEV816> create sequence my_seq;
Sequence created.

ops$tkyte@DEV816> create trigger t1
  2  after insert or update or delete on T
  3  for each row
  4  begin
  5          for x in ( select my_seq.nextval from  dual )
  6          loop
  7                  null;
  8          end loop;
  9  end;
 10  /

Trigger created.

ops$tkyte@DEV816> create trigger t2
  2  after insert or update or delete on T
  3  for each row
  4  begin
  5          for x in ( select my_seq.CURRVAL from  dual )
  6          loop
  7                  null;
  8          end loop;
  9  end;
 10  /
Trigger created.

ops$tkyte@DEV816> insert into t values ( 1 );
insert into t values ( 1 )
            *
ERROR at line 1:
ORA-08002: sequence MY_SEQ.CURRVAL is not yet defined in this
session
ORA-06512: at "OPS$TKYTE.T2", line 2
ORA-04088: error during execution of trigger 'OPS$TKYTE.T2'

Here, t2 happened to fire before t1.  dropping and recreating
the triggers will change this behavior (MAYBE, MAYBE NOT -- it
is quite simply "not defined")

ops$tkyte@DEV816> drop trigger t1;
Trigger dropped.

ops$tkyte@DEV816> drop trigger t2;
Trigger dropped.

ops$tkyte@DEV816> create trigger t2
  2  after insert or update or delete on T
  3  for each row
  4  begin
  5          for x in ( select my_seq.CURRVAL from  dual )
  6          loop
  7                  null;
  8          end loop;
  9  end;
 10  /

Trigger created.

ops$tkyte@DEV816> create trigger t1
  2  after insert or update or delete on T
  3  for each row
  4  begin
  5          for x in ( select my_seq.nextval from  dual )
  6          loop
  7                  null;
  8          end loop;
  9  end;
 10  /

Trigger created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t values ( 1 );

1 row created.

ops$tkyte@DEV816>
September 06, 2000 T.S.R. -- Thanks for the question regarding "tablespace", version 7.3
You Asked
How can i get tablespace information report in the below format

TablespaceName   UsedSpace  AvailableSpace  FreeSpace(%)
System              xxx       xxxx               xxx
Rollback            xxx       xxxx               xxx
Tempoary            xxx       xxxx               xxx
Index               xxx       xxxx               xxx

could you help me?
and we said...
Use the following script in SQLPlus.  It shows you this sort of
stuff.  You can order by any column -- to order by tablespace
you would run:

SQL> @free 1

--------------------------------------------------------
-- free.sql
--
-- This SQL Plus script lists freespace by tablespace
--------------------------------------------------------

column dummy noprint
column  pct_used format 999.9       heading "%|Used"
column  name    format a16      heading "Tablespace Name"
column  Kbytes   format 999,999,999    heading "KBytes"
column  used    format 999,999,999   heading "Used"
column  free    format 999,999,999  heading "Free"
column  largest    format 999,999,999  heading "Largest"
column  max_size format 999,999,999 heading "MaxPoss|Kbytes"
column  pct_max_used format 999.9       heading "%|Max|Used"
break   on report
compute sum of kbytes on report
compute sum of free on report
compute sum of used on report

select nvl(b.tablespace_name,
             nvl(a.tablespace_name,'UNKOWN')) name,
       kbytes_alloc kbytes,
       kbytes_alloc-nvl(kbytes_free,0) used,
       nvl(kbytes_free,0) free,
       ((kbytes_alloc-nvl(kbytes_free,0))/
                          kbytes_alloc)*100 pct_used,
       nvl(largest,0) largest
from ( select sum(bytes)/1024 Kbytes_free,
              max(bytes)/1024 largest,
              tablespace_name
       from  sys.dba_free_space
       group by tablespace_name ) a,
     ( select sum(bytes)/1024 Kbytes_alloc,
              tablespace_name
       from sys.dba_data_files
       group by tablespace_name )b
where a.tablespace_name (+) = b.tablespace_name
order by &1
/
September 06, 2000 Sanjeev -- Thanks for the question regarding "A few Queries", version 8.1.5
You Asked
Hi Tom,
I have some questions:
1. Can you explain (in short), what is cron job and how it works
also if you can provide any small example.
2. How to use ORAINST utility for the creation of Oracle
Database.
3. There was a documentation for Database Security, Where it's
located.

Regards,
Sanjeev
and we said...
A cron job is a unix facility to run recurring Unix processes.
You can use cron for example to schedule a script to run every
night at midnight -- or every 5 minutes during the day -- or
whenever.  Cron is to Unix what DBMS_JOB is to the database...

You say you have 8.1.5 -- Orainst would not be used to create a
databas in 8.1.5, you would use the Java GUI application
"dbassist" to do that.  It is fairly straightforward.

Orainst, the Oracle Installer for 8.0 and before, could be used
as well to generate and then run "create database" scripts for
you.  Just follow the prompts on the installer if you are using
that.

Database security is a broad topic -- you'd have to be more
specific.  A good start might be
http://www.oracle.com/pls/oracle8i/O8i.Search?string=security
...
September 06, 2000 sasi -- Thanks for the question regarding "Data Compression during RMAN backup", version 8.1.6
You Asked
hello tom

i wanted to know if we can compress a datafile while performing
a backup using the oracle backup utility RMAN.
we have 2G datafiles on our system, and we are interested in
knowing methods for data compression while backing up to a disk.

is data compression possible during backup or is it dependent on
th operating system ??

any information in this matter will be helpful

thanks in advance
sasi
and we said...
In general, it is dependent on the device.  If you backup to a
tape device for example, depending on what device name you use
-- differing levels of compression would be employed.  That uses
hardware (the tape drive) to compress.

If you backup to a compressed disk device, it will work as well.

The compression RMAN has is only the ability to backup blocks
that have been written to -- so a 2 gig file with lots of never
before used space will backup to a much smaller file.
Additionally, incremental backups can cut way down on the size
of intervening backups (those between your full backups)
September 06, 2000 wallacel -- Thanks for the question regarding "bmp", version 8.1.6
You Asked
Tom:

I have a question regarding lob.
what i want to do is have a table which stored lots of
bmp file(around 1000 now), and each time user select one of
those by id,and then clinet software display that bitmap to
user.
my question is which one is better, bfile or lob?
how to store and display it?
and we said...
What are your requirements?  It is not that one is better then
the other -- they are different and serve different purposes.
If the bmp files must be accessible to a non-database
application -- bfiles make more sense.  On the other hand, there
is nothing to keep the file system in sync with the database -
the bfiles are not protected by transactional consistency,
locking, backup, recovery and so on.

I myself like LOBS in the database, I tend to keep everything in
the database.  Others would not.  So, it really depends on your
individual needs.  both are viable.

One drawback to a bfile is that you cannot write them via the
database, you must write them in some other way.  So, you could
not upload the bmp files through the database into the
filesystem for example -- you would have to get them into the
files system and then you would be able to read them from the
database.

As to "how to store" and "how to display" -- one would need to
know the client software in order to answer that.  Each will be
dfferent.  What works on the web isn't what will work with
forms, what works with forms won't work for a Java program, and
so on...
September 06, 2000 Jagan -- Thanks for the question regarding "Change management", version 8.1.6
You Asked
Hi Tom,
I am using oracle change manager for version control i.e., to
track the changes made to data base object definitions. But how
to track the changes made to data?. Is there any tool for
managing the changes made to data?

thanks,
-Jagan
and we said...
You would have to roll your own via triggers -- to maintain a
history of changes.  There is nothing builtin that does that.

See:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:671424467534
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:59412348055
for some approaches.
Review & Followup

      Rating: 5
what about
      8.1.7  March 03, 2003
Reviewer:  umesh
       from bangalore India
I know that change manager pack has fully been implemented in 9i , but is
anything available as  builtin in oracle 8.1.7. This will help me a lot in one
of the implementation, if not I can suggest the customer to go for 9i

      Rating: 5
ignore my
      previous question  March 03, 2003
Reviewer:
      umesh  from bangalore India
Forgive me for my hasty previous question , I have a enterprise manager console
and a repository with version 2.2 but when i login to console I cannot see any
thing related to change manager , i got licence to the whole package

September 06, 2000 ATHER NADEEM -- Thanks for the question regarding
      "DISPAY DATE IN FORM 'DD-MM-YYYY'", version VERSION 7

      You Asked
I want t dispaly a date format 'dd-mm-yyyy' i dont want to use
the format mask in form . By default  date is dd-mm-yyyy

      and we said...
Create a WHEN-NEW-FORM-INSTANCE trigger with:

forms_ddl( 'alter session set nls_date_format=''dd-mon-yyyy''
');

in it.  See

http://osi.oracle.com/~tkyte/Misc/NLSDateFormat.html
for why the database init.ora doesn't do it for you.
September 06, 2000 gabby -- Thanks for the question regarding
      "create table as select", version 8.0.6

      You Asked
Hi
when i do create table as select i know that only the table
created and all the indexes and pK will not be created.

there is any easy way to create also the indexes pk etc
because we need to do it in some of our jobs.

thanks
gabby

      and we said...
If you need to copy the table into another SCHEMA (a different
userid) or a different database, then yes, we can do this:

exp userid=old_owner tables=that_table
imp userid=new_owner fromuser=old_owner touser=new_owner full=y

will copy the table from old_owner into new_owner.  If you just
need the skeleton of the table (no data) add rows=n to the
export.

If you are moving this to another database, the exp would stay
the same, the imp would become:

imp userid=new_owner@another_db full=y

September 06, 2000 Rupali -- Thanks for the question regarding "Make
      an .exe of Oracle Project", version 8.1.5

      You Asked
Dear Mr. Tom,

I have seen VB, PB etc. front ends making their .exe files and
installing them directly on clients machine without installing
the software.

Can u tell me in which way can we make an .exe file of an
project developed with Oracle - D2k.

If not possible then what is the other way of not showing our
source code to the user same as the .exe ones.

Rupali

      and we said...
A forms/report will be delivered to your end users in a compiled
binary format.  For example -- your end users do not get the
.fmb file from forms -- they get a .fmx file.  The .fmx file
cannot be reversed into a .fmb.

So, if just preventing access to your code is the issue, the
.fmx file will cover that.

September 06, 2000 t.siva rama -- Thanks for the question regarding
      "db tuning", version 7.2.2

      You Asked
when i executed one procedure the output is like as below

Buffer Cache Hit Ratio         is     72%
Library Cache Hit Ratio     is     93%
Dictionary Cache Hit Ratio     is     81%
Rollback Segment Wait Ratio     is     0%
Sorts to Disk Ratio         is     0%
Cursor Usage Ratio         is     22%
Transaction Usage Ratio     is     2%
File I/O Rate             is     2 per second
Number of users awaiting lock     is     0
Number of unarchived logs     is     0
Redo Log Space Requests     is     0

current info about
Shared Pool Size = 100000000 Bytes
DB Block Buffer = 300 Blocks
Log Buffer  = 32768 Bytes

Logical Reads ... 4515353
physical reads .. 1291198
physical writes . 617

Total Gets  .. 57665
Total Misses .  2863

Pins     .. 39469
Reloads    .. 9
Lib Cache Miss Ratio  ..0

can you give some comments on the above result. how can i get
the actual table size or tablespae size information. can you
guide me please?

      and we said...
the comments I would have is -- taken out of context, without a
greater understanding of everything about your system -- the
above is not very useful.  Tuning is a "large" thing.  A couple
of numbers taken out of context won't tell us very much.

For example -- someone might say "72% Buffer cache hit" -- thats
too low (and it may very well might be).  Cannot really tell
though.  did you just cold start the database?  if so, thats
really good.  If not, did you just run this application for the
first time since you started it?  Has it been a long time since
the data it touches was touched?  are you expecting it to hit
data that reasonably should be cached?  There are many cases
where the answer is NO (eg: I have a 1 billion row table and my
process looks at a couple of rows -- there is no reason to
believe my data would be cached).

People might say "Library cache hit of 93%" -- thats too low. In
a production environment maybe, in a test/development -- maybe
not (i recompile lots of code and add new stuff all of the
time).  Same with dictionary cache hits.

For actual table size/utilization, see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
for tablespace utilization see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:285415955510
...
September 06, 2000 Eurof -- Thanks for the question regarding "Time
      Comparison", version 8.0.5

      You Asked
I have a field called production_date on a table. Currently the
production date is always the current date. However, in the
future we will be manufacturing until 07:00 am an in which case
I want the production date to be the date at which the shift
started. In other words, the shift starts at 21:00 and finishes
at 07:00, and all production down within this time, must bve
allocated to the date at which the shift started. In the case
where production is done at any time from 09:00 to 24:00 then
the production date will be the system date, but when it goes
over midnight the production date must be the day before.

I think that this is a fairly common scenario, but I need some
tips/advice on how the best way of doing this is.

Help,

Eurof Davies

      and we said...
Well, I guess I would put an INSERT or UPDATE trigger on each
table that touches a date column.  Assuming the applications
insert SYSDATE into the tables -- I would have them "adjust"
sysdate so that it might be something like:

  if ( to_char(:new.date_fld,'hh24') between 0 and 6 )
  then
     :new.date_fld := trunc(:new.date_fld-1);
  else
     :new.date_fld := trunc(:new.date_fld);
  end if;

Or something similar.  That sets the date_fld to be either today
at midnight (if we are in an hour from 7am on) or YESTERDAY at
midnight if we are in an hour from 12:00am to 6:59am.

Since you are playing around with the time field -- You'll
probably need to STRIP off the time field (hence my use of
trunc) -- that will be up to you to decide.

It might be advisiable to store 2 fields actually -- the actual
date/time inserted by the application and a NEW derived field
maintained by the trigger that is the "business day" of the
transaction.
September 07, 2000
      Miriam -- Thanks for the question regarding
      "SQL -- comparing a time STRING to sysdate", version version 8

      You Asked
I have a field called attribute8 on a table.  Currently the
attribute8 has a value from a list box, with the following mask
Example:
   8:00AM  - 'HH12:MIAM'

I need to compare this field with a sysdate in this way

SELECT DISTINCT(C.segment5) categoria
FROM
pcinv_categories_v C,
pcPO_LINES_all_v B,
pcpo_headers_all_v A
WHERE
b.po_header_id = a.po_header_id
AND b.category_id = c.category_id
AND A.reply_date >= SYSDATE
AND COMPARE ATTRIBUTE8????? >= TO_DATE(TO_CHAR(SYSDATE, 'HH12:MI
AM'), 'HH12:MI AM')
AND A.attribute3 NOT IN ('ADM CONTRATOS 2','ADM CONTRATOS
I','INS/ADM OBRAS CIVILES')
ORDER BY 1;

I don't want to use decode , because the performance is low.

  I try to use substr and instr ?  What you recommended me?

      and we said...
Well, in my experience DECODE is amazingly, blindingly fast...
So, I don't understand why decode would be slow for you unless
you are relying on an index on attribute8 to be used (in which
case -- using any function on attribute8 would be "slow").  See

http://osi.oracle.com/~tkyte/article1/index.html
for how this would be solved in Oracle8i if that is the case.

You can compare:

to_date( attribute8, 'hh:miam' ) >=
       to_date(to_char(sysdate,'hh:miam'),'hh:miam')

That will do the comparision without a decode -- but I believe
you'll find that is performs just the same as a decode would
(however you were using the decode..).

It works by converting the ascii string with a time in it, into
a date/timestamp -- the date component will be the first day of
the current month.  In order to compare to SYSDATE, we need to
turn sysdate into just a time as well and then covert back into
a date to get it to be the current time on the first day of the
month.

September 07, 2000 Manoj -- Thanks for the question regarding
      "Create a View Dynamically using PL/SQL stored procedure", version
      8.1.5.0.0

      You Asked
Hi Tom

Is it possible to create a view dynamically thru PL/SQL stored
procedure. Is there any sample code available.

Thanks
Manoj

      and we said...
In Oracle8i -- using EXECUTE IMMEDIATE makes this trivial.  In
Oracle8.0 and before, you would use DBMS_SQL which is only
marginally more difficult.  Here is an example using execute
immediate:

ops$tkyte@ORA8I.WORLD> begin
  2          execute immediate
  3          'create or replace view V as select * from dual';
  4  end;
  5  /

PL/SQL procedure successfully completed.

Now, if you put it into a procedure and receive the following
error message:

ops$tkyte@ORA8I.WORLD> create or replace procedure p1
  2  as
  3  begin
  4          execute immediate
  5          'create or replace view V as select * from dual';
  6  end;
  7  /

Procedure created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> exec p1
BEGIN p1; END;

*
ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "OPS$TKYTE.P1", line 4
ORA-06512: at line 1

You'll want to read

http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
to find out why and how to solve it.  In Oracle8i, one method to
"get around" this is:

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> create or replace procedure p1
  2  AUTHID CURRENT_USER
  3  as
  4  begin
  5          execute immediate
  6          'create or replace view V as select * from dual';
  7  end;
  8  /

Procedure created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> exec p1

PL/SQL procedure successfully completed.

But make sure you understand FULLY what is implied by invokers
rights (authid current_user) before doing so.  It totally and
completely changes the privilege model of stored procedures.
See the concepts manual for more info.
September 07, 2000 balasubramanian -- Thanks for the question
      regarding "Few tables in SYSTEM schema are not exported", version
      8.0.6/8.1.5

      You Asked
Dear Tom,

While exporting full database, the following tables (SYSTEM
schema) are not exported.

AQ$_QUEUES
AQ$_QUEUE_TABLES
AQ$_SCHEDULES

 But all other tables (except SYS tables) are exported properly.
But when I am checking with the query --SELECT TABLE_NAME FROM
DBA_TABLES WHERE OWNER = 'SYSTEM'-- it displays the above 3
table names. What may be the reason ?

      and we said...
Because QUEUES are exported procedurally.  The queues must be
recreated upon import via a stored procedure call so they get
registered correctly.  Many objects are not exported "as is" but
rather "procedurally" so that stored procedures on the other end
(the import side) can be invoked with the correct parameters to
recreate them.

Export does a logical export -- not a table by table export.  It
is doing the "right" thing.  When you see the posttables action
-- it is running DBMS_AQ_EXP_QUEUES (among other things) to
export the queues properly.
September
      07, 2000 Keith -- Thanks for the
      question regarding ".dmp file -- whats FORMAT71", version 7.3.4

      You Asked
Contains statements like:
CREATE FORMAT71TRIG
CREATE FORMAT71 PACKAGE...
CREATE FORMAT71 FUNCTION...
What is the relevance of the FORMAT71 clause?
N.B. The compatability mode of the database from which the
export was taken is 7.3.4

      and we said...
format71 is a keyword to the IMP utility (not passed to the SQL
engine) generated by EXP versions 7.1 and up.

If you dumped the dmp file around the FORMAT71, you would see
something like:

CREATE FORMAT71 PROCEDURE "DUMP_TABLE"
\375\377^GCREATE ,procedure dump_table( p_tname in varchar2 )
^Cis
:    l_theCursor     integer default dbms_sql.open_cursor;
$    l_columnValue   varchar2(4000);

the format71 is a keyword to import to tell it "hey, the thing
that follows is a CREATE statement stored in a 7.1 and up export
format -- it is not a SQL create statement yet".  Imp will see
that and procedurally rebuild the actual SQL create statement.
The special characters you see are leading integer byte counts
that imp uses to read and rebuild the original SQL with.
September 07, 2000 Robert -- Thanks for the question regarding
      "Exhausted rollback segments -- v7.1", version 7.1.5.2.4

      You Asked
Dear Tom,

Free space in rollback segments, both in system and rollback
tablespaces, is at a premium following an attempted update that
neither committed nor rolled back because the VMS process that
it was running under crashed.

The data in the database are still valid, so we do not have to
retain the information contained in rollback.  We would prefer
not to--and really don't see the need to--create additional
rollback segments.

What procedure would you follow in attempting to free the space?

Many thanks.

  --Bob Nelson

      and we said...
If the "session" is still alive -- then you do in fact need that
rollback.  Once the session is "officially killed" (either via
the alter system kill session or by a restart) Oracle will need
that rollback to undo the work done by that transaction.

In the "session" is really gone and has been rolled back (eg:
the rows it updated have been unlocked and you can update them
yourself or if you have restarted -- thus definitely killing the
session), then the space is in fact free.  It is just
dedicated to that rollback segment.  Rollback segment space is
allocated and kept -- we use it and reuse it in a circular
buffer fashion.

You can shrink it (give back unused extents) in later releases
of Oracle via an ALTER ROLLBACK SEGMENT command.  In 7.1, you
would manually shrink it via a DROP and CREATE.  If the rollback
segment is truely not needed, the alter rollback OFFLINE,
followed by drop rollback will succeed (if not -- that means we
do in fact need it -- you might bounce the instance to really
get rid of that session) and then you can recreate it.  In later
releases (beyond 7.1) you can specify an "optimal" size on
rollback segments such that after they extend to be large --
they will automatically "shrink" back (release extents) to an
optimal size.
September 07, 2000
      sateesh kumar -- Thanks for the question
      regarding "Transferring data via database link fails when the table has a
      LONG datatype", version 8.1.5

      You Asked
Hi,
  I was trying to transfer data for a table from one database to
another database. It comes out giving an error ora 0997. Tables
are of same structure on both databases .
The insert statement is

insert into tbl_name
select * from tbl_name@dblnk

Can we not transfer data when a table has a long datatype.

Thanks
Sateesh

      and we said...
No, you cannot use longs in that way.  In Oracle8i, (8.0 and up
actually) the appropriate type to use would be a CLOB -- Lobs do
not suffer the limitations of a LONG or LONG RAW.

To move the long, you can either use EXP/IMP (export from
source, import into target) or you can use the sqlplus copy
command -- see

http://osi.oracle.com/~tkyte/Misc/MoveLongs.html
for the howto on that.

September 07, 2000 Farhad -- Thanks for the question regarding
      "Retreiving object column from a table.", version 8.1.5

      You Asked
Hi Tom,
  Thanx for the last reply which you gave me on password
decryption. Well this time, I am facing the difficulty of
retreiving the attribute of the object which is embedded in the
table. Well, here is my script:

create type temp as object
(eno number(3),
 name varchar2(20),
 addr varchar2(30));

Now, I am creating the table in which I am embedding this object
type. The script for this is:
create table v_temp (sal number(7,2),
                     emp temp);

Table Created.

Now, if I want to retreive the eno or name or addr attribute of
the temp object type from the SQL script, how will I do it?
I don't want to display all the attributes of temp object
type,but only one of the attributes of it.
How will I do it through the SQL query?

Hoping for your mail a.s.a.p.

Regards,
Farhad.

      and we said...
It'll look like this:

ops$tkyte@DEV816> create or replace type temp as object
  2  (eno number(3),
  3   name varchar2(20),
  4   addr varchar2(30));
  5  /

Type created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create table v_temp
  2  (sal number(7,2),
  3   emp temp);

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into v_temp
  2  values
  3  ( 100, temp(1,'tom','1122....') );

1 row created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> select sal, a.emp.name, a.emp.addr
  2    from v_temp A
  3  /

       SAL EMP.NAME             EMP.ADDR
---------- -------------------- ------------------------------
       100 tom                  1122....

The correlation name "A" is important (doesn't have to be A but
it must be there!)

Without it you get:

  1  select sal, v_temp.emp.name, v_temp.emp.addr
  2*   from v_temp
ops$tkyte@DEV816> /
select sal, v_temp.emp.name, v_temp.emp.addr
                                        *
ERROR at line 1:
ORA-00904: invalid column name

September 07, 2000 GAURANG -- Thanks for the question regarding
      "addredss", version 8.1.5

      You Asked
hi tom.

1)There are lots of address column in
v$session(saddr,addr,SQL_ADDRESS,PREV_SQL_ADDR),in v$sqltext(address) etc
i am confused with this .could you explian me in detail about this.

2)could you explian me about in v$session(SQL_HASH_VALUE) and
in v$sqltext(HASH_VALUE).and what is this HASH

      and we said...
the are the addresses in memory on the server of various objects.  They can be
used as keys into other tables.  For example you can join v$session to
v$sql_area by SQL_ADDRESS to ADDRESS to see what SQL someone is executing right
now.

 SADDR                                  RAW(4)
 PADDR                                  RAW(4)
 TADDR                                  VARCHAR2(8)
 SQL_ADDRESS                            RAW(4)
 PREV_SQL_ADDR                          RAW(4)

SADDR is the sessions address (like primary key of v$session)

PADDR is the process address - foreign key to v$process

TADDR is the transaction object address -- foreign key to v$transactions

the SQL_ADDRESSES are foreign keys to v$sql_area

September 07, 2000 Amy -- Thanks for the question regarding "Does
      the number of tablespace effact performance?", version 8.1.6

      You Asked
Dear Tom,

One of our application has about 30 tables and table sizes are
very different. Considering performance, some one suggests
create tablespace for each table. Do you think if it helps or
not?

Thanks. Amy

      and we said...
Using multiple tablespaces will allow you to more closely
control where objects are physically.  If right now you have 1
big tablespace with files on one disk only -- you can definitely
use >1 tablespace to help spread out the load over more then 1
disk.  You would create your new tablespaces with files on
different devices and move your objects into them.

Using more then 1 tablespace will allow you to tune -- having >1
tablespace does not mean you are tuned.  It'll let you place
objects where they should be on the disks -- but it won't do it
for you.  You will use tablespaces to put things where they
belong.

So, yes, i would agree you need more then 1 tablespace but
consider a means to the end, not the final answer.  You'll need
to place things correctly (eg: keep data that is frequently
accessed together -- like a table and its indexes -- on
different devices).

since you'll be rebuilding your objects - suggest you read
through:

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:240014552942
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:407619241062
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:652224147530
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:228413960506
and seriously consider using locally managed tablespaces with
either uniform or system managed exent sizes.

Also, see the "ALTER TABLE T MOVE TABLESPACE ..." command and
"ALTER INDEX REBUILD ..." command.  They will let you put the
existing things into the new places easily (remember to rebuild
indexes AFTER moving a table!!)

September 07, 2000 Rob -- Thanks for the question regarding
      "Resizing Tables Smaller", version 8.1.5

      You Asked
Does anyone have some sort of reasonably general procedure for
resizing a table smaller?  For example someone cleans out a
history table and 90% of the space is now unused.  But maybe
every block has at least one record and the table covers
multiple
extents.

The problem is dealing with constraints, triggers and indexes.
There are special cases where shrinking a table can be done
without a lot of pain.  But there doesn't seem to be any easy
way
to deal with the general case.

My preference would be a PL/SQL procedure which outputs the SQL
commands to do all the necessary work.  I could then review the
script, maybe make some manual changes, and then run it.

Any thoughts or suggestions?

      and we said...
In Oracle8i as you have, it is very simple:

Alter Table T move tablespace Y storage (....);

and then online rebuild the indexes on T.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:47812348053
there i show how to move objects into different tablespaces --
but the concept is identical for you, it'll just move into the
"same" tablespace.

No worry about constraints, triggers, etc.  Exp is no longer
needed for this.
September 07,
      2000 Bala -- Thanks for the question
      regarding "Standby Init.ora file", version 8.0.5

      You Asked
Tom,

Can i get the sample Init.ora file for primary database and
standby database, I just need to compare the parameters and I
also wanted to know what are the parameters I need to add in the
standby init file.  Instead of Primary db control file I should
be using the control file created in primary db by specify ALTER
DATABASE CREATE STANDBY CONTROLFILE AS 'filename';
Can I have a different db name for standby db or it should be
one and the same. If so, How do I mount 2 instance with the same
db name.

Thanks

      and we said...
See

http://technet.oracle.com/doc/server.804/a58396/ch12.htm#2429
for the 8.0 documentation.  I personally feel the 8.1 docs are
infinitely better -- and they directly answer your questions
above.

See

http://technet.oracle.com/doc/oracle8i_816/server.816/a76995/toc.htm
but read the preface so you know what features don't apply to
you in 8.0...

Also, you can see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:199412348073
which is a 7.3 howto.

As for the dbname -- they will always be the same.  Since the
standby database will never (should never) be on the same
machine as primary -- there are no clashes.  You can TEST
(stress TEST) on the same machine (it just makes zero sense to
have a standby on the same machine as primary) . See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:427019560395
for how.

September 07, 2000 Michael -- Thanks for the question regarding
      "Oracle ProC/C++ CGI", version Pro*C/C++: Release 8.1.5.0.0

      You Asked
Hi !
 I wrote simple ProC/C++ CGI program, which is running
 from command line just fine.
 When I try to execute that from cgi-bin directory
 it doesn't run.
 There is no error in Web Server error log file &
 status "200" ok in access log, but 0 bytes served.

 Any clues ?

 Thanks.

      and we said...
cgi-bins run in a clean environment.  Your ORACLE_HOME,
ORACLE_SID, LD_LIBRARY_PATH PATH and so on are not set at
all.

Your program is probably getting killed before it starts with a
"ld.so.1 failed to load libclntsh.so" or something like that
(lack of LD_LIBRARY_PATH).

You need to setup a shell script that is really run by the
webserver -- this shell script will run your C code AFTER
setting the ORACLE_HOME, PATH, LD_LIBRARY_PATH and so on.

For now, to test, set up a shell script that is:

#!/bin/sh

/bin/echo Content-Type: text/plain
/bin/echo
printenv

put that script in your cgi-bin directory and run it from the
web to see what "missing" in your environment.

September 07, 2000 subhakar -- Thanks for the question regarding
      "Invalid objects - ORA 2311", version 8.1.6

      You Asked
Hi Tom,

Can a table be "INVALID" ? If so, can U give me an example...
ORA-2311 says: "cannot alter with COMPILE option a valid type
with type or table"

Thankx

      and we said...
No, what that is saying is that if a TYPE has been used in a
CREATE TABLE or another CREATE TYPE command -- it cannot be
recompiled.  here is an example:

ps$tkyte@ORA8I.WORLD> create type t_type as object ( x int, y
int );
  2  /

Type created.

ops$tkyte@ORA8I.WORLD> alter type t_type compile;
Type altered.

so, I can compile that type right now

ops$tkyte@ORA8I.WORLD> create table t ( x t_type );
Table created.

ops$tkyte@ORA8I.WORLD> alter type t_type compile;
alter type t_type compile
*
ERROR at line 1:
ORA-02311: cannot alter with COMPILE option a valid type with
type or table dependents

but once I create a table with that type -- I cannot
September 08, 2000 Tomas -- Thanks for the question regarding
      "Database creation - instance - RMAN use - ", version 8i 8.1.5.0.0

      You Asked
Hey Tom

Nice to know, where I can send my "easy2 questions, that I ca't
find out in the Oracle books.

I got 4 "easy" questions for you!

1. Creation of database, ORA-12203 error

It succeded for me to make a copy of the kontrolfile used by
"Oracle"-database (the default one from Oracle).

I've changed the ini.ora file with different paths and
filenames,
and the executed it, so I shuld have 2 databases on same
machine.
The installation is done by using SVRMGRL.

But when I am trying to mount (by force) the new database
('toatest') then I got first "Total global area..,,,..Redo
buffers..." and then the ORA-2231 error.

I don't call any fancy script from inside the kontorlfile.
but the specified paths af files are created without probælems.

Whats the problem then ???

2. I am often working on databases, that are running on
customors
servers,which I have often only very restricted access to or
none at all except via SQLPlus mounted on 3. machine.
How can I be able to make an backup copy of the databases
controlfile to my own PC or let the information spool over my
screen???

3. Instance - what is it really - on "hardware-level"
I  understand, that an instance is running af copy of ceartain
processes. But - what can I use it for - isn't the copy run
(almost) for every user in an multiuser enviroment???

4. RMAN
Creation of instance (again!!) what schould i be good for??

That's all and thanks in advance!

Tomas

      and we said...
for #1, its a little hard to diagnose as you didn't supply very
much information.  What error are you getting:

$ oerr ora 2231
02231, 00000, "missing or invalid option to ALTER DATABASE"
// *Cause:  An option other than ADD, DROP, RENAME, ARCHIVELOG,
NOARCHIVELOG, MOUNT, DISMOUNT, OPEN, or CLOSE is specified in
the statement.
// *Action:  Specify only legal options.

$ oerr ora 12203
12203, 00000, "TNS:unable to connect to destination"
// *Cause: Invalid TNS address supplied or destination is not
listening. This error can also occur because of underlying
network transport problems.
// *Action: Verify that the service name you entered on the
command line was correct. Ensure that the listener is running at
the remote node and that the ADDRESS parameters specified in
TNSNAMES.ORA are correct. Finally, check that all Interchanges
needed to make the connection are up and running.

You did not really follow correct procedures for cloning a
database instance on the same machine, see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:575623107841
for how to.

#2, That is available from the v$views...

select * from v$log/v$logfile will get you the  LOGFILE part of
the control file.

select * from v$dbfile will get you the datafile section...

select * from nls_database_parameters will get you the character
set information.

select * from v$controlfile_record_section will gets you the
other scalar bits of data.  EG: MAXDATAFILES is

select records_total from v$controlfile_record_section where
type = 'DATAFILE';

and so on...

#3, An instance is a set of OS processes or threads (DBWR, LGWR,
PMON, SMON, and so on) and a shared memory segment. An instance
can mount an open a single database (set of datafiles, redo
logfiles, control files, init files).  A database interestingly
can be mounted and opened by many instances simultaneously (this
is Oracle Parallel Server).

I believe what you are refering to above is the shared or
dedicated servers that respond to user requests to do things in
the database.  In many cases there is a one to one
correspondence between a user session and a dedicated server.
The dedicated server is part of an instance -- not the instance.
 It is just the process that does your select and such.

#4 -- rman is recovery manager.  It is a backup and restore
tool.  See

http://technet.oracle.com/doc/server.815/a67773/toc.htm
for more info.

September 08, 2000 Liming -- Thanks for the question regarding
      "Encrpt fields on table", version 8.0.5 on NT

      You Asked
Hi Tom,

Is there any way to encrypt a field like employee salary field
by using Oracle build-in package or procedure?

If I use application to encrypt the field. I have problem to
sort it from Oracle.

Thank you in advance!

      and we said...
see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:577023128061
for an answer.
September 08,
      2000 GAURANG -- Thanks for the question
      regarding "hash_value", version 8.1.5

      You Asked
hi tom .

in some of v$views i found column name like (sql_hash_value)in v$session, in
v$sqlarea(hash_value).could you explain me that.

      and we said...
It is the internal hash value of the SQL statement.  When we recieve a SQL
statement, we compute a hash based on it (based on the string itself) -- find
the matching statements in the shared pool, see if they are the same and if so
-- just reuse the existing plan (thats a soft parse).  If no true matches are
found, we create a new plan and store it in the shared pool (hard parse).

September 08, 2000 Thiruvaiyaru -- Thanks for the question regarding
      "Password Encryption while connecting to sql*plus", version 8.1.6

      You Asked
Tom,

I have a shell script that kicks off a sql*plus
session. In the shell I have to specify the username
and password for  sql*plus, which I didn't want to
as a security issue. Is there a way where I could encrypt
the password or do something so that the password doesn't
show up on the shell? I tried creating a file that holds
just the password in a directory that has restricted
permissions for the user that runs the shell and pass
the value from the file into a variable in the shell
and use it in the password for sql*plus, but I feel even
this is not enough. Is there a way where  I could directly
encrypt or hide the password when I run the shell ?

Thanks
Sai

      and we said...
see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:142212348066
...
September 08, 2000 Randy -- Thanks for the question regarding
      "Avoiding fragmentation", version 8.1.5

      You Asked
This is related to response to an object sizing question of 9/7
(and the referenced articles):

1)Is the newest viewpoint on object sizing to be less concerned
with the number of extents, and more concerned with the equal
sizing of extents within a tablespace?

2)All this time I though multiple extents were evil, but now it
sounds like fragmentation is actually what's evil.  I guess you
get fragmentation from bad extent allocation, right?

3)How do locally managed tablespaces affect normal admin. tasks
like backups, etc?  Any gotchas?

4)You wrote that you like to put similar types of tables in the
same TS (like lookups), but wouldn't that cause contention since
these are accessed frequently?  I suppose the way around this
would be the KEEP buffer pool.  Correct?

Thanks.

      and we said...
1) i don't know how "new" it is as many of us have felt that way
for many many years now.  I would definitely say "Yes, I feel
that way".

2) correct.  yes.

3) none that I have found to date.  You must be careful to add
64k to each datafile if using UNIFORM extent allocation (see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:652224147530
for why)

4) things that are frequently used will be cached (lookups in
general).  Buffer pools help you control this even more.  With
most people using some sort of striping and volumne management -
and the advent of NN gig disks (where NN is some huge number
like 24/36), the days of placing objects exactly on such and
such a disk are coming very near the end.  So many systems I've
seen (modest sized ones) have hundreds of gigs of disk but only
a very small handful of devices.

(I like to put similarly sized objects - not necessarily TYPES
of objects -- although for small lookups they are probably one
in the same, small tables).


Subject | Article | Last Updated (East coast time)
Running Reports (Run_product) from forms | article only | Sep 09, 2000 08:23 am
error messaging system | article only | Sep 09, 2000 08:49 am
Migrate/Upgrade from 7.2.2 to 7.3.4 | article only | Sep 09, 2000 03:49 pm
How to insert a string include ' into database ? | article only | Sep 09, 2000 03:52 pm
Function to repeat a character n times | article only | Sep 09, 2000 03:54 pm
hide table name | article only | Sep 09, 2000 04:05 pm
application server | article only | Sep 10, 2000 10:25 am
how create .csv file from table (is there simple command) & automate ftp through oracle /solaris | article only | Sep 10, 2000 10:34 am
Display Tables and Records | article only | Sep 10, 2000 10:41 am
Nested tables and records.. | article only | Sep 10, 2000 11:57 am
SYSDATE within PL/SQL | article only | Sep 11, 2000 06:16 am
Rman recovery condition... | article only | Sep 11, 2000 07:39 am
ENFORCING NAMING CONVENTIONS WHILE CREATING DB OBJECTS | article only | Sep 11, 2000 08:50 am
Executing OS commands from Stored Procedures. | article only | Sep 11, 2000 08:54 am
Calculating the PCTFREE and PCTUSED | article only | Sep 11, 2000 09:26 am
Global Temporary Tables | article only | Sep 11, 2000 09:31 am
Users with SYSTEM as Default Tablespace | article only | Sep 11, 2000 09:33 am
Interface between two DBs | article only | Sep 11, 2000 09:37 am
Exit | article only | Sep 11, 2000 10:05 am
Rule based optimiser and ANALYZE-command | article only | Sep 11, 2000 10:25 am
Logging a Stored PL/SQL procedure using OAS 4.0.7 | article only | Sep 11, 2000 10:38 am
How can i create text file from the CLOB data stored in the Tables | article only | Sep 11, 2000 10:58 am
rman | article only | Sep 11, 2000 04:37 pm
Meaning of CHECKPOINT in ALTER TABLE DROP COLUMN | article only | Sep 11, 2000 07:21 pm
Columns in create table | article only | Sep 11, 2000 07:22 pm
loadjava | article only | Sep 11, 2000 07:36 pm
processing of data captured from E-mail | article only | Sep 12, 2000 06:03 am
Change of Maxextents of lob | article only | Sep 12, 2000 06:16 am
Oracle hints | article only | Sep 12, 2000 06:45 am
Opening a TAR | article only | Sep 12, 2000 06:57 am
Database link | article only | Sep 12, 2000 08:54 am
CHAINED_ROWS table is not corrected defined ? - error ORA-00947!! | article only | Sep 12, 2000 08:57 am
Status of Pro*C applications after migration to 8.0.x | article only | Sep 12, 2000 11:14 am
Calling Pro*C program from a package | article only | Sep 12, 2000 11:18 am
Multiple cursor programming | article only | Sep 12, 2000 11:48 am
snapshots | article only | Sep 12, 2000 11:54 am
Locally Managed Tablespaces | article only | Sep 12, 2000 12:41 pm
external procedures | article only | Sep 12, 2000 02:20 pm
database users | article only | Sep 12, 2000 02:41 pm
Locally Managed TS info in the Data Dictionary | article only | Sep 12, 2000 03:00 pm
How does v$session_longops work ? | article only | Sep 12, 2000 03:18 pm
Oracle ODBC Driver, MFC CRecordset, Oracle stored procedures | article only | Sep 12, 2000 07:33 pm
Is using pctused=1 a reasonable approach | article only | Sep 13, 2000 09:20 am
stability | article only | Sep 13, 2000 01:13 pm
Porting Pro*C from Windows to HP-UX | article only | Sep 13, 2000 01:58 pm
How to get the max "N" Values from a table | article only | Sep 14, 2000 06:51 am
"table scan(long)/ table scan(short)" in v$sysstat | article only | Sep 14, 2000 07:05 am
To stop the execution of a procedure | article only | Sep 14, 2000 07:23 am
Regarding random numbers generation. | article only | Sep 14, 2000 07:47 am
Dtabase Query | article only | Sep 14, 2000 07:54 am
High water mark in Table sapce | article only | Sep 14, 2000 10:16 am
Exp | article only | Sep 14, 2000 04:48 pm
send eMail from PLSQL Procedure | article only | Sep 15, 2000 09:03 am
Preventing tablespaces from blowing out | article only | Sep 15, 2000 10:28 am
EVT and SM tables | article only | Sep 15, 2000 10:48 am
Trigger scripts | article only | Sep 15, 2000 10:49 am
CLOB in SQL Plus | article only | Sep 15, 2000 10:50 am
Verification of backup | article only | Sep 15, 2000 11:07 am
Problems with object sizing | article only | Sep 15, 2000 11:19 am
Stored Procedures | article only | Sep 15, 2000 11:22 am
max open cursors exceeded ora 01000 | article only | Sep 15, 2000 12:35 pm
Uniform Extent Sizes | article only | Sep 15, 2000 12:48 pm
Grants and privileges | article only | Sep 15, 2000 03:38 pm
Search strings in dba_views | article only | Sep 15, 2000 04:15 pm
row(s) 1 - 64 of 64
September 09, 2000 Srivatsa -- Thanks for the question regarding "Running Reports (Run_product) from forms", version Forms 6.0.5.34.0, Report 6.0.5.34.1
You Asked
I wish to run MULTIPLE reports from forms runtime.

Eg. I have 2 reports R1 & R2 which is called from Forms F1.

The user would like an option in which they can view the results
of BOTH reports R1 and R2 in 2 different windows at the SAME
TIME and compare it with. They need the ability to switch back
and forth between these report windows (previewer/screen) and
maybe goto FORMS and run one more report and thereby switch back
and forth between 3 reports and so on.

Hope you understood my requirement

Please let me know how i can please my users

Thanks

==Srivatsa==
and we said...
One method that works is to run HOST instead of run_product.
For example, create a report "dept.rep" and save it somewhere.
Now, create a push button with a button press trigger:

host(
'c:\temp\runrep.cmd "c:\temp\dept.rep userid=scott/tiger"',
 NO_SCREEN );

Where c:\temp\runrep.cmd is a small script you would install
with your forms that has:

start rwrun60 %1

in it.  Thats the reports runtime previewer.  I suggest the cmd
file as that makes it easier to "start" the processes in the
background and to protect yourself from name changes of the
reports runtime.
Review & Followup
Rating: 5
March 26, 2001
Reviewer: Helena Markova from Bratislava, Slovakia

September 09, 2000 habeebuddin -- Thanks for the question regarding "error messaging system", version 2.x
You Asked
Dear Mr. Tom

   I am using one tabular form and I query 4 records and try to
delete the records one by one the first two records I could
delete due to intrigity constraints(child record exist) it is
o.k. but when i tried to delete the 3rd and fourth record which
they do not have child records I could not delete and got the
same error message integrity constraints(child record exist).

   By this I concluded that once an error message will apear on
the form it will not remove untill and unless to clear and close
the form.  In the pl/sql form code I used CLEAR_MESSAGE(bult-in)
but I could not suceed.

Please guide me to fix this problem.
and we said...
I believe what is happening is

o you remove record 1 in forms and hit "save" -- it fails due to
child record

o you do the same for record 2.  This in fact is trying to
delete record 1 and record 2 (you did not do a "clear block" and
"requery" hence forms is still trying to delete that other
record

o you do the same for record 3.  It again fails on the delete of
record 1!  Record 1 is still not on your screen -- forms is
still trying to delete it.  You will have to "undelete" that
record in forms by clearing the block and requerying the data.
Your cumulative transaction at this point is "delete record 1,
record 2, and then record 3".  The failure of the single
statement does not reset the form back to what it was when the
transaction began -- you have to do that.
September 09, 2000 robert -- Thanks for the question regarding "Migrate/Upgrade from 7.2.2 to 7.3.4", version 7.2.2/7.3.4
You Asked
Background :

Our company has decided to migrate/upgrade from 7.2.2 to 7.3.4.
As I read through the migration documentation, it provides two
major option for migration (v6/v7):

1) import/export

2) upgrade

Q1 : In general, for 7.2.2 to 7.3.4, which option is better ?
import/export or upgrade ? I need to retain the 7.2.2
executables and preferably the DB for contigency and
verifications.

Q2 : Can I use the import/export method for 7.2.2 to 7.3.4
migration/upgrade. In these case, do I still need to run the
scripts like CAT7301.sql & etc after the import ?

Q3 : For the upgrade option, do I still need to install the new
7.3.4 executables ? How about the old datafiles from 7.2.2 ?

Q4 : I intend to use the two_task method to allow old 7.2.2 to
connect to new 7.3.4 DB, any comment or pitfall for this
approach ?

Thanks for your attention.

regards,
kta
and we said...
Q1, unless you want to resize your blocksize in the database or
otherwise do some large scale "reorg", an upgrade is preferable
(faster, safer, easier).

Q2, you would follow the steps in the migration guide.  You
would not need to do the upgrade scripts -- just catalog.sql and
catproc.sql and such for other features/options.  cat7301.sql is
an upgrade script to take a 7.2 database and alter the data
dictionary.  If you do a FULL import - the data dictionary is
already a 7.3 data dictionary.

Q3, you would follow the steps in the migration guide.  Yes, you
need to install the new 7.3.4 executables (else you would have
nothing to upgrade to).  The old datafiles from 7.2 will be
opened and used by the 7.3.4 software.  You'll need them as
well.

Q4, once you upgrade -- the 7.2 stuff is obsolete. I don't
understand this part of your reasoning.  You'll be running 7.3.4
software on the server -- all 7.3.4.  You can remove the 7.2
stuff after you install the 7.3.4 code tree.  Once you upgrade -
7.2 is no longer in the picture.

Please give
http://technet.oracle.com/doc/server73x/MIG73/toc.htm
a thorough read through to fully understand your options.
September 09, 2000 zhu -- Thanks for the question regarding "How to insert a string include ' into database ?", version 8.1.5
You Asked
when I insert a long string include ( ) ' etc . word ,
for example :
    insert into tablename(remark) values('people's republic of
china ');
    I was stopped at people' .
    How can i do this work ?
and we said...
The best way to do this is to use a bind variable -- your entire
database will run much much faster if you do.  Building an
insert statement such as the above in a program is very bad
form.  You really want to:

  prepare a statment like:
    insert into tablename ( remark ) values ( :bv );

  bind "people's republic of china" to :bv

  execute the statement (many times without reparsing)

How you do this varies by language but it is the best solution.

In you really feel you must use a character string constant
(terrible thing to do, totally kills the shared pool concept),
you would:

 insert into t values ( 'people''s republic of china' );

two quotes = a quote inside a character string constant.
September 09, 2000 balasubramanian -- Thanks for the question regarding "Function to repeat a character n times", version 8.0.6/8.1.5
You Asked
Dear Tom,
   In other databases there are functions available to repeat a
specified character n times and build a string.Example:
Funcion_name('+',10) may return a value ++++++++++. Is there any
function available in ORACLE to do the same thing ?
and we said...
To get N repeats of a CHARACTER, rpad (or lpad) will do:

ops$tkyte@ORA8I.WORLD> select rpad('+',10,'+') from dual;

RPAD('+',1
----------
++++++++++

To get N repeats of a STRING, replace of rpad will do it:

ops$tkyte@ORA8I.WORLD> select
         replace( rpad('+',10,'+'), '+', 'abc') from dual;

REPLACE(RPAD('+',10,'+'),'+','
------------------------------
abcabcabcabcabcabcabcabcabcabc

ops$tkyte@ORA8I.WORLD>
September 09, 2000 ather -- Thanks for the question regarding "hide table name ", version oracle 7
You Asked
hi tom
  i m a regular reader. i want t ask a how can i hide table.
for exm
  select * from cat
 but i want to particular table will be hide .

Q 2
  how i can use in oracle 7  this command
 create or replace type temp as object
(emp number(10),
name varchar2(10));
i type this but error .
please a.s.a.p .

thanks
and we said...
q1: to "hide" a table -- i do not understand that.  If you mean
-- I do not want the table to show up in the system catalog, the
answer will be, if I have access to the table via a grant (eg: i
have SELECT on it) it will appear in the data dictionary.  If I
do not have access to the table -- it will not.  So the answer
would be -- do not grant access to the table and it will not
appear.

q2:

In a type statment -- the last semi-colon is part of the type
statement itself, not a symbol to "run command now".  You need
to use the / to run it:

ops$tkyte@ORA8I.WORLD>  create or replace type temp as object
  2  (emp number(10),
  3   name varchar2(10));
  4  /

Type created.
September 10, 2000 suya -- Thanks for the question regarding "application server", version 4.0
You Asked
any available information about using oas
can i able use oas to run application developed by developer6
on the web ,how it is do
and we said...
It can be used in conjunction with Developer6 but you need the
Developer server as well (the forms runtime engine running in
"server" mode.)

See
http://www.oracle.com/tools/forms/index.html
for more info.
September 10, 2000 Mamta -- Thanks for the question regarding "how create .csv file from table (is there simple command) & automate ftp through oracle /solaris", version oracle 8i
You Asked
Dear Tom,

I would like to know how to convert a table in oracle to a .csv
file or txt file  . Is there any simple method to do that .

Secondly , I need to automate ftp process . Can I do that from
within oracle if so how .

If it cannot be done through oracle what is the other way .
Please get back to me ASAP .

Regards
Mamta
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:58612348055
...
September 10, 2000 Roy -- Thanks for the question regarding "Display Tables and Records", version 7.3.1
You Asked
Hi Tom,

I wanted to display table name and number of records it has, as
follows.

OM_ITEM     1254
OS_TRAN1    1658
OT_MASTER    500

etc

can you help me to get a report like this please
and we said...
If you analyze your tables frequently, the query:

select table_name, num_rows from all_tables

would give you a very good (and fast) estimate of the rows in a
table.  Analyze will record the number of rows in the table as
of the analyze so it will not be 100% but close.

If you need the EXACT number of rows and the list of tables is
well known, a UNION ALL would work:

scott@DEV816> select 'dept', count(*) from dept
  2  union all
  3  select 'emp', count(*) from emp;

'DEP   COUNT(*)
---- ----------
dept          4
emp          14

It'll be slow as it must count the rows for each table.

If the list of tables is unknown, you'll need to write some
procedural code in 7.3 to achieve this.  How to do that would
vary by what tool you are using so I cannot go further into it
here.  If you let me know what you are USING to generate the
report, I might be able to tell you how.
September 10, 2000 Nikhil -- Thanks for the question regarding "Nested tables and records..", version PL/SQL 8.1.5
You Asked
Hi Thomas,
Please excuse me for the incomplete mail that was sent.I
apologise for that . My IE hung when I tried to open another
page that I was browsing.
In my desperation, I clicked on some of the buttons and did not
realise that the incomplete mail would be forwarded.
I am writing my question again.

I am new to using tables in PL/SQL, so please bear with me…..

I have a record type that I define as:
Type Facility IS RECORD (
     Practice Number (5),
     Location Number (5),
     Name VARCHAR2 (100));

And I declare a nested table of this type Facility declared
above…..
TYPE Facility_List IS TABLE OF Facility;

I declare a local variable of type Facility in my PL/SQL block:
MyList FacilityList;

I want to know
1) How can I reference the individual record elements in the
list? (Maybe MyList (1). Practice? )
2) I want to write a function that returns to me a nested table,
assign that to MyList and then process this data..
Something like:

MyList :    = Fn_GetFacilityList(1234);
For Idx IN MyList (First).. MyList (Last)
           Update Sometable
            Set somefield = SomeValue
           Where prac = MyList (idx). Practice;
LOOP

Could you also please point me to some good reading material on
this topic , I found  the online help to be confusing…

Thanks,
Nikhil
and we said...
1) you are correct --   arrayName(idx).element.  So
myList(1).practice would work.

2) here is an example:

ops$tkyte@DEV816> create or replace package demo_pkg
  2  as
  3
  4      Type Facility IS RECORD
  5      (
  6       Practice Number (5),
  7       Location Number (5),
  8       Name VARCHAR2 (100)
  9      );
 10
 11      TYPE Facility_List IS TABLE OF Facility;
 12
 13      function getFAcilityList( p_id in number )
 14          return Facility_List;
 15  end;
 16  /

Package created.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> create or replace package body demo_pkg
  2  as
  3
  4  function getFAcilityList( p_id in number )
  5  return Facility_List
  6  is
  7      l_data    Facility_list := Facility_list();
  8  begin
  9      for i in 1 .. p_id loop
 10          l_data.extend;
 11          l_data(i).practice := i;
 12          l_data(i).location:= -i;
 13          l_data(i).name    := 'name'||i;
 14      end loop;
 15
 16      return l_data;
 17  end;
 18
 19  end;
 20  /

Package body created.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> declare
  2      my_data demo_pkg.Facility_List;
  3  begin
  4
  5      mY_data := demo_pkg.getFacilityList(5);
  6
  7      for i in 1 .. my_data.count
  8      loop
  9          dbms_output.put_line
 10                  ( my_data(i).practice || ',' ||
 11                    my_data(i).location || ',' ||
 12                    my_data(i).name );
 13      end loop;
 14  end;
 15  /
1,-1,name1
2,-2,name2
3,-3,name3
4,-4,name4
5,-5,name5

PL/SQL procedure successfully completed.

Which online help are you referring.  I learned everything I
know from the PLSQL guide and the concepts manual.  Have you
tried those?
September 11, 2000 Connor -- Thanks for the question regarding "SYSDATE within PL/SQL", version 8.1.6.2
You Asked
Hello Thomas,

When accessing the 'sysdate' function in PL/SQL, you get an
implicit "select sysdate from dual",and thus a context switch. I
remember seeing somewhere that later versions(8i+ perhaps?) of
PL/SQL now had a builtin that would return the date without
having to invoke the sql engine. Is this true ?

Cheers
Connor
and we said...
Nope, you can see this via:

sys@DEV816> delete from dual;
1 row deleted.

sys@DEV816> declare
  2    x date default sysdate;
  3  begin
  4          null;
  5  end;
  6  /
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at "SYS.STANDARD", line 1014
ORA-06512: at line 2

sys@DEV816> rollback;
Rollback complete.

sys@DEV816> select * from dual;

D
-
X

It uses DUAL.  You will see it in the trace file as well. I am
not aware of that changing.

Typically, you should always:

declare
    x date default sysdate;
    ...
begin
   ....

if you need sysdate alot and do not need the most current value.
 Note that using SYSDATE in a SQL statement in PLSQL does not
incurr this context switch.  So, instead of:

   insert into t .... values ( X );

you could

   insert into t ..... values ( SYSDATE );

and if you needed the sysdate yourself to print out a report or
something, you could

   insert into t ..... values ( SYSDATE )
   returning date_column into x;

to insert it and get it back (rather the select it out and then
insert it)
September 11, 2000 Ashok -- Thanks for the question regarding "Rman recovery condition...", version 8.1.6
You Asked
Hi Tom,

   I am using rman in my site for taking prodution database
backup.tell me how would I restrore a database from a RMAN
backup when I loose all my controlfiles and some datafiles.

   here my problem is I can't mount the database for restoration
with out contrilfile also I can't recreate the control file with
missing datafiles.

   How should I go about and do it?

Thanks in advance .

Regds...Ashok
and we said...
See chapter 6 of
http://technet.oracle.com/doc/oracle8i_816/server.816/a76990/toc.htm
it covers how to recover from a loss of control files.
Recovering the datafiles is rather straightforward as that is a
"normal" recovery process.  It is covered in the same manual
however.
September 11, 2000 balasubramanian -- Thanks for the question regarding "ENFORCING NAMING CONVENTIONS WHILE CREATING DB OBJECTS", version 8.1.5/8.0.6
You Asked
Dear Tom,
  Is it possible to enforce the application developers to follow
a naming conventions while creating objects. For example, when a
db user is trying to create a table he must provide a name
prefix (i-e) fin_master - finance master, pur_details (purchase
details). If any user is trying to create a table without any
predefined prefix, his create table command should fail. Can it
be done through any trigger or by any other method? (This can be
helpful us to understand what is the purpose of table and there
will be a uniformity of set of tables for documenting purpose).
and we said...
In Oracle8i release 8.1 you can but not in 8.0.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:646423863863
for an example of a

create or replace trigger trigger_name
after CREATE on schema

DDL trigger.
September 11, 2000 Ripudaman -- Thanks for the question regarding "Executing OS commands from Stored Procedures.", version 8.0.5.0.0
You Asked
Hi,

 I need your help.

 Here is the problem description.

 1)  (a) I am Using Orracle Version 8.0.5.0.0
     (b) I cant use Java stored Procedures.
     (c) I have Visual C++ and Pro*C Compilers.

 2) In My job queue I am executing some procedures as a
    ' Night Time Batch Processes '.
    I need to call Report Runtime ( Developer 6.0) within
    a Pl/sql Block In a stored procedure.
    Can I achieve this Task.
    Or can I some how able to execute any OS Command Within a
    PL/SQL Block.
    Or Can I Assign any OS Utility( executable ) as a "WHAT"
    parameter while submiting a job.

 In hope of your kind cooperation.

 Regards

 Ripudaman Pachauri
and we said...
You are looking for external procedures then.

See
http://technet.oracle.com/doc/server.804/a58236/10_procs.htm#433731
for a discussion of this feature and how to implement.  In a
nutshell, external procedures let you write your stored
procedures in another language such as C.  In 8.0 you will not
be able to use PRO*C in the external procedure (but you can use
OCI to callback to the database if you need to do SQL in the
external routine as well).
September 11, 2000 Lindsay -- Thanks for the question regarding "Calculating the PCTFREE and PCTUSED", version 8.1.6
You Asked
I am trying to calculate the PCTFREE and PCTUSED for my tables.  Do you have any
good scripts or formulas to follow to compute these percentages?  I realize
these values are dependent on how much the rows will be updated etc.

I have some some formulas:

PCTFREE = ((Average Row Size - Initial Row Size) * 100) / Average Row Size

However, I am unsure as to how to calculate the Initial Row Size.

PCTUSED = 100 - PCTFREE - ((Average Row Size * 100) / Available Data Space)

Any pointers or a good rule of thumb is greatly appreciated.
and we said...
In order to calculate the initial row size, the only tried and true method is to
fill a representative table with lots of rows that are of your "initial" size.
If you use a sample of somewhere between 1 and 10% of your final tablesize and
put in "initial" rows (rows as they will be inserted) -- you can analyze the
table and determine the initial row size from user_tables.avg_row_len.

Then, you can update these rows to be what they will be after a couple of
updates -- analyze -- and get the average final row size.  In fact, at that
point you can analyze list chained rows to see if you even need to concern
yourself with this issue at all.

I personally don't change these from the defaults EXCEPT for tables that chain
frequently (which can be found via the analyze table list chained rows).  For
any given table T, I don't worry about it -- it is just the exceptions...
September 11, 2000 Regina -- Thanks for the question regarding "Global Temporary Tables", version 8.1.5
You Asked
We are converting an application from Sybase which makes extensive use of
temporary tables which are created in the T/SQL procedures.  How would this be
accomplished within Oracle?  I can not find much information on the Global
temporary table setup in the manuals.  Are there any performance impacts that we
need to be aware as the app takes on more users?  Concurrent usage will be about
10 users per function of the temp table.

Thanks
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:48812348054
for a comparision/discussion.

You should most definitely not create the tables inside the stored
procedure.  DDL is very costly and you would have to use dynamic sql to access
the newly created object.  It is not too good for our shared pool either.

I would strongly recommend however that as you are migrating from Sybase to
Oracle -- you discontinue the use of temporary tables.  They are a crutch that
we typically do not need.  No 16 table limits, complex joins are something we do
well, the need to copy data over to the side to avoid blocking does not exist
and so on.

We are a totally different environment (as I am sure you know by now).
Temporary tables have very few uses in Oracle.
September 11, 2000 Lindsay -- Thanks for the question regarding "Users with SYSTEM as Default Tablespace", version 8.1.6
You Asked
I have the following users with SYSTEM as the default tablespace:

DBSNMP
MDSYS
OAS_PUBLIC
ORDPLUGINS
ORDSYS
OUTLN
TRACESVR
WEBSYS

They were installed there (I did not create any of these users explicitly).
Should I be concerned and try re-setting their Default tablespace to one other
than SYSTEM?  They already have objects created in their schema.
and we said...
You can safely alter them to point elsewhere if you like but it is not
necessary.

The OUTLN users objetcs should be moved using EXP/IMP if you plan on making
extensive use of the Query Plan Stability feature -- if that means nothing to
you then don't worry the two tables it has won't be used.

Beyond that -- you can leave them be.
September 11, 2000 Reji -- Thanks for the question regarding "Interface between two DBs", version 8.1.6
You Asked
Tom:
    I have two DBs ( 8.1.6 ), one is the master and the other
one is the copy ( not all the tables - a subset of the master
db.
I don't want to use replication mechanism to replicate the data.
Again, the data set that I want to replicate is a very
low-volume and get updated once in a while.  Is triggers is the
way to go?  Would you please point me to some examples? Can I
use
materialized views acrosss dbs?

-Thx
-Reji
and we said...
Well, replication is done via triggers so if you do anything
with triggers you are just rewriting replication so I would use
replication.

A materialized view is simply another name for a snapshot.  A
snapshot was the first way we did replication in Oracle7.0 and
up.  Yes, you can replicate MV's across dblinks -- that is what
they were designed for.

I would recommend to you basic replication -- read only
snapshots.  The way they work is:

o at the master site you'll create a snapshot log. This snapshot
log creates a trigger on the master table. This trigger captures
the primary key and DML operation (I, U, or D for insert/update
or delete) into a log table.

o at the remote site you'll create the snapshot (materialized
view).  This snapshot can use the snapshot log to find all of
the rows it needs to refresh and will then clear out the log.

this replication can be done automatically every N units of time
or on demand via a stored procedure call.  Instead of writing
your own (which would effectively mimick the above), I would
strongly recommend using the builtin facility.
Review & Followup
Rating: 3
June 26, 2001
Reviewer: Pichaimani Balasubramanian from San Jose, CA, USA
Hi Tom,
    Thanks. I'm having a similar need like Reji and I had thought of
implementing the way Regi was planning. Now I feel it is safe and better to use
Oracle Replication.

September 11, 2000 Bjørn Erik -- Thanks for the question regarding "Exit", version 8,1i
You Asked
How to exit an application withut using EXCEPTIONS? A sort of
RETURN/EXIT function..
and we said...
There is no way to exit the PLSQL runtime without throwing an
exception.  If some higher level procedure has an exception
handler that catches that exception, or they have a when OTHERS
-- the exception will stop propagating.

There are no equivalents of C's exit(), longjmp() and so on.
The PLSQL call stack must be unwound to get back to the client.
Typically this is done by throwing an unhandled exception
(unless you use when others which is a very bad practice)
September 11, 2000 Tomas -- Thanks for the question regarding "Rule based optimiser and ANALYZE-command", version 8i 8.1.5.0.0
You Asked
Hey tom

If the RDBMS use rule based optimsing method, can you at all use
ANALYZE-command to get information about the acount of
table-rows
chainded-rows etc. ??

Thanks

Tomas
and we said...
If you analyze the table and compute|estimate statistics AND the
optimizer_goal is set the the default of CHOOSE -- queries will
be generated using the cost based optimizer.

So, to get row counts -- yes, that implies an analyze will if
you are using CHOOSE will start the CBO.

To get chained rows -- no, that will not generate statistics, it
will not jump start the CBO.

To make it so you could analyze if you wanted and still use the
RBO, set the optimizer_goal=RULE in the init.ora of the
database.  The default method of optimization will be rule then
for all sessions, regardless of the presence of statistics or
not.
September 11, 2000 Alan -- Thanks for the question regarding "Logging a Stored PL/SQL procedure using OAS 4.0.7", version 4.0.7
You Asked
Hi, Tom.
I need your help. I'm using Oracle Application Server 4.0.7 and
how can I do to login in a stored PL/SQL procedure using an
HTML page that have two fields "login" and "password". Because I
don't want that the OAS prompt me it's login window. I want to
validate the user in a web page.

                                             Thanks.
                                             Alan.
and we said...
You'll need to use cookies and a DAD that is created with the
username/password stored with the DAD.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:446620083639
for the concept.

You will NOT be logging into the database with that username and
password -- all users will use the same common username and
password.  This is because OAS will quite simply have no access
to any username/password information (its just data on a form as
far as it is concerned).
September 11, 2000 Ashish -- Thanks for the question regarding "How can i create text file from the CLOB data stored in the Tables", version 8.1.5
You Asked
Hi TOM,

We have a Table with two columns. The table structure is as
follows:
abc (col1   number pk,
     col2   clob   nn)

Our requirement is to take the data from the Clob column and
create a text file from it. The name of the text file should be
the value in col1.
PLease help me with this.

Thanks,

ashish
and we said...
You will use the UTL_FILE supplied packge to do this as long as
the clob has a newline character at least every 32k.  UTL_FILE
has two open methods -- the second one goes like this:

  x := utl_file.fopen( '/temp/', 'foo.dat', 'w', 32760 );

that'll let you create a flat file. You'll use fopen to open a
file, select out a lob, and then use dbms_lob.read or
dbms_lob.substr to get a chunk of text and utl_file.put to write
it.  then utl_file.fclose to finish it off.

Search for utl_file on my site - many examples are there.  See
the supplied packages guide for setup information.
September 11, 2000 wallacel -- Thanks for the question regarding "rman", version 8.1.6
You Asked
Tom:

I run two command under Rman to backup system tablespace.

one is:
run{allocate channel c1 type disk;copy datafile 1 to 'df1.bak';}

the other is
run{allocate channel c1 type disk;backup tablespace system;}

and then i check the size of file df1.bak and 01c541s9_1_1.
it is not the same size , 01c541s9_1_1 is smaller than df1.bak

can you tell me why?

Regards
and we said...
copy copies.  full image copy.

backup compresses (does not backup blocks that have never been
used).
September 11, 2000 Andre -- Thanks for the question regarding "Meaning of CHECKPOINT in ALTER TABLE DROP COLUMN", version 8.1.6
You Asked
What exactly does the CHECKPOINT clause in the ALTER TABLE DROP
COLUMN command do ? The manuals and other books are rather vague
as to this matter. What does the term "checkpoint" has to do
with rollback segment in this context ?
and we said...
the checkpoint is sort of like committing in a cursor for loop
that is inserted lots of data (eg: commit every X hundred rows
to release the rollback that has been generated).

Normally, the drop column is an operation that can be rolled
back.  If you were halfway through dropping a column in a
100,000 row table when the system crashed -- upon restart the
table will be restored to it previous state.

If you use checkpoint N, it'll release the rollback (it
"commits" the work it has done in effect) and let you continue.
If the drop column gets interrupted due to that system -- the
table will be unusable upon restart until you drop column
continue -- to finish the work.

It is something you would use on a REALLY big table to avoid
blowing out rollback (although on a REALLY big table I would
probably just set unused and leave it there)...
September 11, 2000 Ram -- Thanks for the question regarding "Columns in create table", version 8.1.6
You Asked
Hi,
  Can you please tell me the limit of number of columns that can
be created in a table. We have a source db(DB2) in which one
table has 300 columns. We are getting that table in a flat file.
I am not sure if i can load that many columns into an Oracle
table.

Thanks,

Ram
and we said...
In Oracle8.0 and up the limit is 1,000 columns per table. In 7.3
and before it was 254 columns per table.
September 11, 2000 wallacel -- Thanks for the question regarding "loadjava", version 8.1.6
You Asked
Tom:

this is an urgent question for me.
I create a user named test and
then try to use loadjava under this user with following
command line:

loadjava -user test/test Hello.class
Error while accessing MD5 table
    ORA-00942: table or view does not exist

Error while updating MD5 of: Hello
    ORA-00942: table or view does not exist

loadjava: 2 errors

however when i use user scott/tiger
everything is ok.

do i need to do anything before i use loadjava?
(actually i grant create procedure,table to user vote before
i use loadjava).

and then i create a new user;
$ loadjava -user test1/test1 Hello.class
Error while accessing MD5 table
    ORA-00942: table or view does not exist

Error while loading Hello
    ORA-00942: table or view does not exist

Error while creating class Hello
    ORA-29506: invalid query derived from USING clause
ORA-00942: table or view does not exist

loadjava: 3 errors

I try some other java file also, both user test and test1 fail
but scott successed.

Thanks & Regards,
and we said...
Ok, this will be because of a tablespace quota probably.  If I
create a user like you say you did -- with create procedure,
create table:

ops$tkyte@DEV816> grant create session, create procedure, create
table to test identified by test;

Grant succeeded.

And then run loadjava I get:

$ loadjava -user test/test ArrayDemo.class
Error while accessing MD5 table
    ORA-00942: table or view does not exist

Error while loading ArrayDemo
    ORA-00942: table or view does not exist

Error while creating class ArrayDemo
    ORA-29506: invalid query derived from USING clause
ORA-00942: table or view does not exist

loadjava: 3 errors

The reason was in my case because the user had a default
tablespace of SYSTEM, loadjava creates a table and I have 0k
quotas on all users on SYSTEM myself (and perhaps you do too).
So i then:

ops$tkyte@DEV816> alter user test default tablespace users quota
unlimited on users;

User altered.

that changes the users default tablespace and lets them put as
much data as they want into it.  Now I can:

$ loadjava -user test/test ArrayDemo.class

without error...
Review & Followup
Rating: 5
July 10, 2001
Reviewer: A reader

September 12, 2000 Raja -- Thanks for the question regarding "processing of data captured from E-mail", version 8.1.5
You Asked
Hi Tom,

Is there any way(tools etc) by which we can capture data(based
on parameters),send to an e-mail address,process it/query from
Oracle database and then send the reply to the sender(as an
e-mail) automatically.

I'm refering to a situation somewhat similar to that of
Microsoft knowledge-base,where one writes the query id in the
subject line and gets a reply of the same via return mail
automatically.

Thanks and regards,

Raja Saha
and we said...
Sure, using Oracle8i, release 8.1.5, you can certainly write a
Java stored procedure that uses POP3 or IMAP4 to read an inbox,
parse the subject line and send a mail.  You would use dbms_job
to schedule this stored procedure to execute on a recurring
basis, say every 5 minutes or so.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:255615160805
for further details.

If you do not have Java in the database, you could use external
procedures as well -- written in C.  See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adg11rtn.htm#1656
for details on that.
September 12, 2000 Sujir -- Thanks for the question regarding "Change of Maxextents of lob", version 8.1.5
You Asked
Hi Tom,

    Was curious to know is there anyway where I can change the
maxextents of lob . As per the notes in oracle it says you have
to export ,drop the table and then recreate it with new
maxextents. Is there any shortest way.,

Thanks,
With kind regards
Sujir.
and we said...
It is the initial extent size that cannot be changed for obvious
reasons (it's already allocated).  The maxextents can be
changed.

It could look like this:

ops$tkyte@DEV816> CREATE TABLE "T" ("X" NUMBER(*,0), "Y" CLOB)
  2  LOB ("Y") STORE AS
  3  (TABLESPACE "SYSTEM"
  4   ENABLE STORAGE IN ROW
  5   CHUNK 8192
  6   PCTVERSION 10
  7   NOCACHE
  8   STORAGE(INITIAL 16384 NEXT 16384 MINEXTENTS 1
            MAXEXTENTS 1  )
  9  )
 10  /

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t values ( 1, empty_clob() );

1 row created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> begin
  2      for y in (select * from t for update ) loop
  3          for i in 1 .. 10 loop
  4              dbms_lob.writeappend( y.y, 32000,
rpad('*',32000,'*') );
  5          end loop;
  6      end loop;
  7  end;
  8  /
begin
*
ERROR at line 1:
ORA-01693: max # extents (1) reached in lob segment
OPS$TKYTE.SYS_LOB0000028127C00002$$
ORA-06512: at "SYS.DBMS_LOB", line 722
ORA-06512: at line 4

ops$tkyte@DEV816>
ops$tkyte@DEV816> alter table t
  2  modify
  3  lob (y)
  4  (storage  ( maxextents 100 ) );

Table altered.

ops$tkyte@DEV816>
ops$tkyte@DEV816> begin
  2      for y in (select * from t for update ) loop
  3          for i in 1 .. 10 loop
  4              dbms_lob.writeappend( y.y, 32000,
rpad('*',32000,'*') );
  5          end loop;
  6      end loop;
  7  end;
  8  /

PL/SQL procedure successfully completed.

ops$tkyte@DEV816>
September 12, 2000 sl -- Thanks for the question regarding "Oracle hints", version Oracle8
You Asked
HI Tom,
    Does /*+ HINT */ work for queries running in pl/sql?

Thanks,
SL
and we said...
Yes but there is an issue with regards to this.  If you code:

  for x in ( select /*+FIRST_ROWS*/ * from T ) loop
     ....

PLSQL will accidently turn that into:

   select /*+IRST_ROWS*/ * from t

make sure to leave, for plsql, a space between the + and the
first character of the hint.
September 12, 2000 Aparna -- Thanks for the question regarding "Opening a TAR", version oracle 7.3
You Asked
Hello Tom,
I have a query regarding TAR. What is meant by opening a TAR ?
How can you use it to store/retrieve files from the database?

Thanks.
and we said...
A TAR is a Technical Assistance Request.  It is a support
acronym.  You open TARS with support to get help.  You can do
this on the web at
http://metalink.oracle.com/
or via phone support.

A TAR file might also be a Tape ARchive.  Thats a unix thing
similar to a ZIP file on Windows (but not compressed).  It is a
file format that contains many files in one big file (which may
be compressed).  You use the tar command to add or extract files
from it.
September 12, 2000 vani -- Thanks for the question regarding "Database link", version 7.3
You Asked
I created a database link from one oracle database to another.
I want to remove permissions to prevent any database updates
using that link.
Nobody should be able to update a table through the link

eg. update table1@dblink set col1 = 'XYZ' should not be allowed.

Thank you
and we said...
Ok, the way to do this would be to create a PROXY link.  For example:

create public database link dblink_name
connect to USER_WITH_READ_PRIV_ONLY
identified by THEIR_PASSWORD
using 'tnsconnect string'
/

You would create a user on the other database, USER_WITH_READ_PRIV_ONLY and
grant them whatever privs you want (eg: no UPDATE on anything).  Now, each user
will connect over the database link using that user/password and will not have
the ability to do anything other then what you have granted directly to that
user and anything you have granted to public.

We do this at Oracle all of the time.  We create an account on the remote
database - set up private synonyms to all requisite objects in that account and
allow people to create database links to that account only. The synonyms point
to objects with SELECT only.
September 12, 2000 Tomas -- Thanks for the question regarding "CHAINED_ROWS table is not corrected defined ? - error ORA-00947!!", version 8.0.5.2.1
You Asked
Hey Tom

I'm trying to collect information about chained rows for all
tables in a databse - but I always got this prblem as shown
in following outprint:

*****************************************************************

SQL> create table CHAINED_ROWS (
  2    owner_name         varchar2(30),
  3    table_name         varchar2(30),
  4    cluster_name       varchar2(30),
  5    partition_name     varchar2(30),
  6    subpartition_name  varchar2(30),
  7    head_rowid         rowid,
  8    analyze_timestamp  date
  9  );

Table created.

SQL> analyze table xal_kirke.slettet4 list chained rows;
analyze table xal_kirke.slettet4 list chained rows
*
ERROR at line 1:
ORA-00947: not enough values
***************************************************************

Always this error, so I guess, that it must be the definition of
the CHAINED_ROWS table that is wrong.

In Oracle 8i 8.1.5 SQL reference is following example, which
shows a completely difference result:

***************************************************************
Chained Rows Example The following statement collects
information about all
the chained rows of the table ORDER_HIST:
ANALYZE TABLE order_hist
LIST CHAINED ROWS INTO cr;
The preceding statement places the information into the table
CR. You can then
examine the rows with this query:
SELECT *
FROM cr;
OWNER_NAME TABLE_NAME CLUSTER_NAME HEAD_ROWID TIMESTAMP
---------- ---------- ------------ ------------------ ---------
SCOTT ORDER_HIST AAAAZzAABAAABrXAAA 15-MAR-96
****************************************************************

So what works??

Thanks in reguard.

Tomas
and we said...
You should use the script utlchain.sql found in
$ORACLE_HOME/rdbms/admin to create the chained rows table.  Use
the version of that file that is correct for each database (eg:
from ITS oracle home).

Subpartition is a column added in Oracle8i release 8.1 in
support of composite partitioned tables (tables with range and
hash partitioning).
September 12, 2000 Mohammed -- Thanks for the question regarding "Status of Pro*C applications after migration to 8.0.x", version 8.0.x
You Asked
Tom,

Thank you verymuch for the quick reply for my earlier question
'migration'.

What will be the status of Pro*C Applications, after migration
to 8.0.x

The document you refered doesn't indicate, we should install the
Pro*C oracle product in the $ORACLE_HOME or $ORACLE_BASE.

Is oracle is getting away with Pro*C and similar products after
8.x inception?

regards,
Ahmed
and we said...
Pro*C is here to stay -- there are significant enhancements in
Pro*C for 8i such as prefetching, ability to code external
procedures in pro*c and so on....

You have the choice of keeping your applications precompiled and
compiled as Oracle8 clients (8.0) or re-precompiling them and
using Oracle8i as the client.

If you keep them as 8.0 clients, you'll need to keep the
Oracle8.0 Oracle home and that will be their oracle home.  They
will use Net8 to connect to the database (no direct connect
across versions).

The preferred method will be to keep the Oracle8.0 oracle home
for them and then to rebuild them elsewhere (so you have the 8.0
binaries up and running) with 8i, using the Oracle8i precompiler
and library.  You would test the 8i binaries as far as
performance and correctness goes.

We don't really cover migration of "clients" in the migration
guide.  That does the database.  The clients, such as pro*c and
so on -- can be upgraded to use the new tools at your
convienence after the database is up and running.  You will just
need to keep the old software installed for them and make sure
to have the Oracle home set to their OLD oracle home when you
run them (and to use Net8 to connect in all cases until they are
at the same release level as the database)
September 12, 2000 don -- Thanks for the question regarding "Calling Pro*C program from a package", version 8.0.5
You Asked
Can you provide any information/examples of
a package that calls a Pro*C program.
The package must pass several parameters to the Pro*C program.
It would be even better if the package could pass
a pointer to a C stucture.

Thanks for your help.

Don Steger
and we said...
In Oracle8.0 as you have, we cannot call a Pro*C application.
We have a feature called "external procedures" which allows us
to write a stored procedure in C and call it.  This C code may
call back into the database using OCI -- but not Pro*C in
version 8.0.

In Oracle8i release 8.1 -- external procedures can be written in
Pro*C as well as OCI.  This would statisfy your needs.

You will never be able to pass a "pointer" from a package
(PLSQL) to an external procedure as PLSQL does not have the
concept of a pointer.  You can, in Oracle8i, pass object types
(lots like records), arrays, and scalars to external procedures.

See
http://technet.oracle.com/doc/server.804/a58236/10_procs.htm#433731
for info on extprocs in 8.0 and
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76939/adg11rtn.htm#1656
for info on this feature as it exists in Oracle8i.
September 12, 2000 vijay -- Thanks for the question regarding "Multiple cursor programming", version SQL*Plus: Release 3.3.4.0.0, Oracle7 Server Release 7.3.4.5.0
You Asked
I have a table person with fields relevent to this question as
PERSON_ID                       NOT NULL NUMBER(10) (Unique)
LAST_NAME                                VARCHAR2(30)
FIRST_NAME                               VARCHAR2(15)
MIDDLE_NAME                              VARCHAR2(2)
I need to find the person_id of the person's last name, first
name and middle name that are the same. i.e I need the person_id
of all the duplicate persons(same last, first, midle names...if
john doe appears twice, i need to retrieve both his person_id)

what I am doing in the procedure is, getting the list of persons
into a cursor, who are duplicated, in the table using
select count(*),last_name,first_name,middle_name
from person
where person_type in (2,4)
group by last_name,first_name,middle_name having count(*) > 1;
and then inside the loop, trying to get their person_id. But
this above query returns more than 1 row for every person
because of "having count(*) > 1" so I need to feed this into a
second cursor where i am having the problem.

the incorrectly working procedure is,
create or replace procedure FixDupPersons as
person_record person%ROWTYPE;
DupPersonId NUMBER(10);
--L_N varchar2(30);
--F_N varchar2(30);
--M_N varchar2(2);

cursor DupPerson_cur is
select last_name, first_name, middle_name
from person
where person_type in (2,4)
group by last_name, first_name, middle_name
having count(*) > 1;

cursor EachDupPerson_cur(L_N varchar(30), F_N varchar(30), M_N
varchar(2)) is
select last_name, first_name, middle_name
from person
where last_name = L_N and
first_name = F_N and
middle_name = M_N;

begin
   for DupPerson_rec in DupPerson_cur loop
        for EachDupPerson_rec in
EachDupPerson_cur(DupPerson_rec.L_N, DupPerson_rec.F_N,
DupPerson_rec.M_N) loop
            select person.* into person_record
            from person
            where last_name = EachDupPerson_rec.last_name and
            first_name = EachDupPerson_rec.first_name and
            middle_name = EachDupPerson_rec.middle_name;
            dbms_output.put_line('Duplicate Person found,
person_id = ' || person_record.person_id );
        end loop;
   end loop;
end;
/

the errors are
Errors for PROCEDURE FIXDUPPERSONS:

LINE/COL ERROR
--------
-----------------------------------------------------------------

13/37    PLS-00103: Encountered the symbol "(" when expecting
one of the
         following:
         := . ) , @ % default
         The symbol ":=" was substituted for "(" to continue.

13/54    PLS-00103: Encountered the symbol "(" when expecting
one of the
         following:
         := . ) , @ % default
         The symbol ":=" was substituted for "(" to continue.

13/71    PLS-00103: Encountered the symbol "(" when expecting
one of the

LINE/COL ERROR
--------
-----------------------------------------------------------------

         following:
         := . ) , @ % default
         The symbol ":=" was substituted for "(" to continue.

I would appreciate if you could help.
and we said...
Well, I would simply code:

select person_id, last_name, first_name, middle_name
  from person a
 where person_type in (2,4)
   and EXISTS ( select null
                  from person b
                 where b.person_id <> a.person_id
                   and b.last_name = a.last_name
                   and b.first_name = a.first_name
                   and b.middle_name = a.middle_name
                   and b.person_type in (2,4) );

It'll get it all in one query, probably faster then what you are
doing now.  Another alternative is:

select *
  from person
 where (last_name,first_name,middle_name) in
            (select last_name, first_name, middle_name
               from person
              where person_type in (2,4)
              group by last_name, first_name, middle_name
             having count(*) > 1 )

which is close to what you have coded procedurally.  Doing it in
sql will be faster then cursors.

But... your code should be:

create or replace procedure FixDupPersons as
person_record person%ROWTYPE;
DupPersonId NUMBER(10);

cursor DupPerson_cur is
select last_name, first_name, middle_name
from person
where person_type in (2,4)
group by last_name, first_name, middle_name
having count(*) > 1;

-- NO LENGTHS on the inputs to a cursor.  they are ALWAYS
-- unconstrained types

cursor EachDupPerson_cur(L_N varchar, F_N varchar, M_N
varchar) is
select last_name, first_name, middle_name
from person
where last_name = L_N and
first_name = F_N and
middle_name = M_N;

begin
   for DupPerson_rec in DupPerson_cur loop
        for EachDupPerson_rec in  -- use the proper field
                                  -- names in the cursor rec
EachDupPerson_cur(DupPerson_rec.last_name,
DupPerson_rec.first_name,
DupPerson_rec.middle_name) loop

            -- this select into by definition will FAIL
            -- it always gets >1 record!!!

            /*
            select person.* into person_record
            from person
            where last_name = EachDupPerson_rec.last_name and
            first_name = EachDupPerson_rec.first_name and
            middle_name = EachDupPerson_rec.middle_name;
            */

            dbms_output.put_line('Duplicate Person found,
person_id = ' || person_record.person_id );
        end loop;
   end loop;
end;
/

I would just code this instead:

ops$tkyte@ORA8I.WORLD> create or replace procedure fixDupPersons
  2  as
  3  begin
  4      for x in
  5      ( select *
  6          from person a
  7         where person_type in (2,4)
  8           and EXISTS ( select null
  9                          from person b
 10                         where b.person_id <> a.person_id
 11                           and b.last_name = a.last_name
 12                           and b.first_name = a.first_name
 13                           and b.middle_name = a.middle_name
 14                           and b.person_type in (2,4) )
 15          )
 16      loop
 17          dbms_output.put_line
 18          ( x.person_id || ' ' ||
 19            x.last_name || ' ' ||
 20            x.first_name || ' ' ||
 21            x.middle_name || ' ' ||
 22            x.person_type );
 23      end loop;
 24  end;
 25  /

Procedure created.

ops$tkyte@ORA8I.WORLD> here is my test data:
ops$tkyte@ORA8I.WORLD> select * from person;

 PERSON_ID LAST_NAME  FIRST_NAME      MI PERSON_TYPE
---------- ---------- --------------- -- -----------
         1 kyte       thomas          j            2
         2 kyte       thomas          j            2
         3 kyte       lori            m            2

ops$tkyte@ORA8I.WORLD> exec fixDupPersons
1 kyte thomas j 2
2 kyte thomas j 2

PL/SQL procedure successfully completed.

This will work best if there is an index in last_name,
first_name, middle_name.  If not, the IN ( subquery ) instead of
EXIST would be better.
September 12, 2000 Reji -- Thanks for the question regarding "snapshots", version 8.1.6
You Asked
Tom:
     Can I create a snapshot based on a view?
     What I would like to do is to replicate a subset of
     information from multiple master tables.  I was thinking
     to create a master view where I can define the columns
     that I want to replicate to the replicated site.  I may
     have to use Materialized View instead of regular view
     that way I will have the data for replication.

     Would you please explain this process little bit in detail?
- How I will be able to accomplish this.

Reji
and we said...
A snapshot can have a subset of columns and a predicate. No need
for a view.  But yes, a snapshot could be on a view.

Here is a sample snapshot command:

scott@DEV816> create snapshot emp_snap
  2  refresh fast
  3  next trunc(sysdate,'hh')+1/24
  4  as
  5  select ename, empno
  6  from emp@remotesite where deptno = 10;

Materialized view created.

That creates a snapshot that will:

o use a snapshot log to get just changes
o only gets the ename and empno column
o uses a predicate to only get rows where deptno = 10
o refreshes (updates) itself every hour on the hour
o shows that a snapshot IS A materialized view!

All i did at the remote site was:

create snapshot log on emp;

Please see the distributed guide and give it a read through.
It'll help a lot in this.
Review & Followup
Rating: 5
August 22, 2001
Reviewer: Deanna from South San Francisco, USA

Rating: 3
simple and useful September 07, 2001
Reviewer: klaus from Germany
a simpe but useful answer

September 12, 2000 Arthur -- Thanks for the question regarding "Locally Managed Tablespaces", version 8.1.5
You Asked
Tom,

I am wondering if there is any real advantage to using locally
managed tablespaces over system managed tablespaces.  I am
looking to implement some new features into our database and was
wondering your opinion on locally managed tablespaces.

Arthur
and we said...
Absolutely love them.  Will use nothing else.  Search for
"locally managed" on my search to see other things I've written
about them.

Main reasons:

o extent sizes.  I really like UNIFORM sized extents and nothing
but.  System allocated extent sizes are great too.  I like that
it totally ignores my INITIAL, NEXT, and especially PCTINCREASE.

o space management -- they are orders of magnitude faster at
this.

I cannot imagine a reason to use dictionary managed tablespaces
anymore, except for SYSTEM which still must be (doc may say
otherwise but its wrong on that point for now).
September 12, 2000 wallacel -- Thanks for the question regarding "external procedures", version 8.1.6
You Asked
Tom:

I Found that the 10th chapter of PL SQL User Guide and reference
version 8.0 and 8.1.6 is different.
for version 8.0 it is External Procedures
for version 8.1.6  is Native Dynamic SQL and didn't mention
external procedures.

does that means 8.1.6 don't support external procedures
or it support some other alternative? if so, what is that?
and we said...
Chapter 10 in the Application developers guide contains this
information in V8.1 doc.  They just shuffled the chapters.
Since external procedures concern C, PLSQL and Java in 8i -- not
just plsql calling C, it was no longer appropriate in the PLSQL
docs.
September 12, 2000 wallacel -- Thanks for the question regarding "database users", version 8.1.6
You Asked
Tom:

when i install oracle. it installed some user for me, such as
ADAMS
AURORA$ORB$UNAUTHENTICATED
BLAKE
CLARK
CTXSYS
DBSNMP
JONES
MDSYS
ORDPLUGINS
ORDSYS
OUTLN
TRACESVR

can you explain to me what those username use for?
or can you tell me where i can find document about that?
for security reason, do i need to drop them or change the
password for it?

Regards,
and we said...
adams, blake, clar, jones should be dropped.  They are demo
accounts. if you installed demos, they got installed.

AURORA$ORB$UNAUTHENTICATED is an internal account used by java
beans.

ctxsys is the interMedia text owner.  It owns the context
packages.  You should change its password.

dbsnmp is part of the Oracle intelligent agent.  If you change
this, pick up <Note:70174.1> from support first.  It goes
through the steps for doing this and what needs to be updated.

mdsys is the spatial (part of interMedia) owner, like ctxsys you
should change the password.

ordplugins and ordsys -- same as mdsys.  part of intermedia,
generic stuff used by them all.

outln -- for the Query Plan stability feature.  Should have the
password altered.

tracesvr - used for Oracle trace.  This password should be
changed.  If you are using Oracle trace, remember to update it
as well.
September 12, 2000 Andre -- Thanks for the question regarding "Locally Managed TS info in the Data Dictionary", version 8.1.6
You Asked
Hi Tom,

If extent management is carried out inside the tablespace for
locally managed tablespaces, why does extent info about these
tablespaces still appear in the data dictionary ? Doesn´t this
continue to add overhead to extent management ?

Regards.
and we said...
Its inn the VIEWS but not in the dictionary.  If you look at the
v8.0 view:

ops$tkyte@8.0> select text from all_views
  2  where view_name = 'DBA_EXTENTS';

TEXT
-----------------------------------------------------------------
---------------
select ds.owner, ds.segment_name, ds.partition_name,
ds.segment_type,
       ds.tablespace_name,
       e.ext#, f.file#, e.block#, e.length * ds.blocksize,
e.length, e.file#
from sys.uet$ e, sys.sys_dba_segs ds, sys.file$ f
where e.segfile# = ds.relative_fno
  and e.segblock# = ds.header_block
  and e.ts# = ds.tablespace_id
  and e.ts# = f.ts#
  and e.file# = f.relfile#

and then compare that to the v8.1 view:

ops$tkyte@DEV816> select text from all_views
  2  where view_name = 'DBA_EXTENTS';

TEXT
-----------------------------------------------------------------
---------------
select ds.owner, ds.segment_name, ds.partition_name,
ds.segment_type,
       ds.tablespace_name,
       e.ext#, f.file#, e.block#, e.length * ds.blocksize,
e.length, e.file#
from sys.uet$ e, sys.sys_dba_segs ds, sys.file$ f
where e.segfile# = ds.relative_fno
  and e.segblock# = ds.header_block
  and e.ts# = ds.tablespace_id
  and e.ts# = f.ts#
  and e.file# = f.relfile#
  and bitand(NVL(ds.segment_flags,0), 1) = 0
union all
select /*+ ordered use_nl(e) use_nl(f) */
       ds.owner, ds.segment_name, ds.partition_name,
ds.segment_type,
       ds.tablespace_name,
       e.ktfbueextno, f.file#, e.ktfbuebno,
       e.ktfbueblks * ds.blocksize, e.ktfbueblks, e.ktfbuefno
from sys.sys_dba_segs ds, sys.x$ktfbue e, sys.file$ f
where e.ktfbuesegfno = ds.relative_fno
  and e.ktfbuesegbno = ds.header_block
  and e.ktfbuesegtsn = ds.tablespace_id
  and e.ktfbuesegtsn = f.ts#
  and e.ktfbuefno = f.relfile#
  and bitand(NVL(ds.segment_flags, 0), 1) = 1

You can see that the locally managed stuff comes from x$
(internal, undocumented) tables -- in memory "virtual" tables.

Its not in the dictionary "really"...
September 12, 2000 Andre -- Thanks for the question regarding "How does v$session_longops work ?", version 8.1.6
You Asked
Hi again Tom,

I have tried to use the v$session_longops view to track database
operations, but I´ve noticed that only some kinds of them really
appear.

Besides, for example, the CREATE INDEX statement is split into
multiple sub-operations (sort, merge, etc.)

I am aware I have to first analyze the object to be tracked and
set TIMED_STATISTICS or SQL_TRACE, so I can use this feature.

The questions are:

- What operations are really "trackable" ?

- Why does some operations are split into sub-operations and how
can I know to which operation these sub-operations belong ?

Regards.
and we said...
In Oracle 8.0, the view V$Session_longops was introduced to
allow Server processes to indicate some idea of how far they had
progressed  (specifically RMAN).

In Oracle8i, this list was expanded to include:

Rman Backup and Restore
Parallel Query
Recovery ( Crash and Media )
Full Table scans               **
Sorting

** Only considered a 'Longop' if the table exceeds 10,000 blocks

   formatted blocks.

why are some operations broken into smaller chunks?  I guess
because it makes sense to. In a parallel index create -- there
are lots of sorts going on and then we need to merge them all
back together into 1 index.
Review & Followup
Rating: 5
6 seconds or 2 seconds November 02, 2001
Reviewer: Nag
To be sure:

The conditions for a operation to appear in v$session_longops, what we require
is

1.the table exceed 10,000 blocks
2.The operation should be more than 6 seconds.
3.The operation should be one of
Rman Backup and Restore
Parallel Query
Recovery ( Crash and Media )
Full Table scans               **
Sorting

( is there  a list of  other server process which are covered by
v$session_longops, can you give the link to the specific page which contains all
the above mentioned information about v$session_longops.)

September 12, 2000 Jon -- Thanks for the question regarding "Oracle ODBC Driver, MFC CRecordset, Oracle stored procedures", version 8.1.6.0.0
You Asked
Hi Tom,

We have an Oracle database that has a table with some CLOB
fields.  We have a stored procedure for inserting data into the
tables - it takes a NUMBER and 4 CLOBs.  Using MFC I created a
derived recordset class that has 5 parameters, 1 long, and 4
CStrings (for the CLOBs).  I set the parameters and open the
recordset with a call to the stored procedure.  This generates
an Oracle error ~ "INCORRECT NUMBER OR TYPES OF PARAMETERS IN
CALL TO STORED PROCEDURE".  If I just use another recordset with
1 long and 4 CString vars, open using a select statement, then
add a new record and update, it inserts into the database just
fine (ie not using the stored procedure).
The Oracle ODBC driver (v. 8.01.61.00) seems to support data
transfer from a CString to a CLOB column in a table.  Does it
not support transfer from a CString to a CLOB parameter in a
stored procedure call?

Thanks,

Jon
and we said...
No, it cannot.

CLOBS live in the database, they have to be "inserted" somewhere
(of allocated if a temporary clob but that is a whole different
thing).

When you insert the string -- the database will do the
allocation of the lob pointer and insert the string into it. It
can do this because you are inserting the data -- it is putting
it in the database.

With the procedure, there is no place to "put" the clob -- there
is no lob locator that points to storage on disk (which is where
all lobs live) that we can use.  Therefore, on the way into a
stored procedure, it is expecting a clob (which is really a
pointer) to be sent.  Not a string -- which would have to be
inserted into a table before it could be converted into a clob.

The stored procedure should take 4 strings as inputs -- as that
is what you are attempting to send to it.  It can then insert
the strings into the database.
September 13, 2000 Trevor -- Thanks for the question regarding "Is using pctused=1 a reasonable approach", version 8.1.6
You Asked
Tom

I am using locally managed tablespaces with uniform extents.
In this context, you have said in one of your replies that you
do not specify storage(), and just code exceptions.

What do you think of the idea of setting all pctused to 1? Won't
this mean that blocks are either empty and available for insert
or non-empty and not available; any insert will fit into any
available block; and searching overhead for available blocks
will be a minimum.

Is the only downside the extra disk space used?

thanks
Trevor
and we said...
No, it would not mean that.

Consider a table such as:

ops$tkyte@ORA8I.WORLD> create table t ( x int )
                                pctused 1 pctfree 1
  2  /

Table created.

That says:

pctfree = 1, reserved 1% of the block for future updates.  Keep
this block on the freelist until it is 99% full.

pctused = 1, once 1% of the block is free again, put this block
back on the freelist so it can be used for updates.

So in this case, pctused 1 would cause the block to be used to
capacity.

I do not know why you would want blocks to either be empty and
available for insert or not empty and not available for insert.
You would have 1 row per block.  In most cases that would not be
a good thing to do.  If you wanted to do that, you would set a
high pctfree and pctused.  for example:

ops$tkyte@ORA8I.WORLD> create table t ( x int )
                                pctused 40 pctfree 60
  2  /

Table created.

That would create a table that would

o remove a block from the freelist when it was 40% full (60%
free).

o a data block used for this table’s data segment is considered
unavailable for the insertion of any new rows until the amount
of used space in the block falls to 39% or less
September 13, 2000 chitao -- Thanks for the question regarding "stability", version 8i
You Asked
if we have one computer A is running the oracle server, I want
to get another one B running everything same (configuartion,
tables, ....), hope it is simultanoues .
in case A is shut down or crush down, we can shift to B
immediately without losing information.
Is there any tool in Oracle to do this and how can get the
documentation for that how to set up it
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:262615352849
or

Standby databases
http://technet.oracle.com/doc/oracle8i_816/server.816/a76995/toc.htm
...
September 13, 2000 Chee -- Thanks for the question regarding "Porting Pro*C from Windows to HP-UX", version 8.1.5.0.0
You Asked
Hi Tom,

We are developing a Pro*C (ver 8.1.5.0.0) application for HP-UX
Unix machine. Instead of waiting for the production environment,
we have started the development on Windows platform using MS
Visual C++ 6.0 (pure ANSI C program) and NT for DB.

Now, it is time for us to port it to HP-UX. I have the following
questions to ask:

1) As I have never done any UNIX C programming, how am I
compiling my C program? Is it using makefile?

2) How do I compile the Pro*C program? Do I need to install the
precompiler for HP-UX?

3) How do I link them?

Apart from the above questions, I would appreciate if you have
more notes or suggestions related to my problem.

Many thanks in advanced.

CM
and we said...
1) yes a makefile.  See
http://govt.oracle.com/~tkyte/proc_makefile/
you might need to tweak it a little but it has served me well.
I asked the same question myself -- but the other way.  It was
painful for me to figure out how to create a makefile on NT.
That gui thing just was too huge.  I do makefiles on NT as well.
 Lean, clean, lightweight.

2) You need the pro*c precomiler and the OPTIONAL ansi C/C++
compiler installed on HP.  The default "basic" C compiler does
not cut it (no ansi support).

3) the makefile does it for you.  You can also just use the demo
makefile directly.  To test out your pro*c install, you should
build the demos anyway.  you would:

$ cd $ORACLE_HOME/precomp/demo/proc
$ make -f demo_proc.mk sample1

until that works -- you won't be precompiling anything.  Once
that works -- its all downhill from there.  test that out first.
 read the demo_proc.mk for more insights.
Review & Followup
Rating: 4
Could you please correct the link to makefile November 08, 2001
Reviewer: Jagjeet Singh from CA, USA
please change govt to osi

September 14, 2000 Krishna -- Thanks for the question regarding "How to get the max "N" Values from a table", version 8.1.5
You Asked
Hi Tom,

I have a table with 3 cols... No, Name, Salary...
These are the contents of the table...

No  Name   Salary
1   kri     5000
2   cho     6000
3   akr     5000
4   avr     4000
5   vij     3000
6   rao     8000
7   asr     7000
8   kvr     2000
9   ksr     1000
10  kkr     9000

Now I want to Get the Top 7 Salaries...

Can u please give a solution for this..

Thanx,
Krish
and we said...
To see how you would do this in 8.1.6, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:750625651018
In Oracle8i release 8.1.5, you can code:

select *
  from ( select distinct salary from t order by 1 )
 where rownum <= 7
/

to get the top 7 salaries.
September 14, 2000 Ravi -- Thanks for the question regarding ""table scan(long)/ table scan(short)" in v$sysstat", version 8.1.5
You Asked
Tom,

The "table scan(long)/ table scan(short)" statistics  in
v$sysstat is incremented each time a full table (long/short) is
encountered by oracle.

My question is whether the increment is taking place only during
for the full table scans as a result of queries or as a result
of any DML statements.

When there is no index on the forign key of the child table and
when we delete the parent table, with delete cascade, full table
scan will result on the child table. Whether such full table
scan is also included in that count or the count in v$sysstat is
only from the Queries.

Hope I have explained good.

Regards
Ravi
and we said...
It counts them, we can see that in the following example:

ops$tkyte@DEV816> create table t1
  2  as
  3  select rownum x, rpad('*',2000,'*') data
  4  from all_objects
  5  where rownum < 1500;

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create table t2
  2  as
  3  select rownum x, rpad('*',2000,'*') data
  4  from all_objects
  5  where rownum < 1499;

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> alter table t1 add constraint t1_pk primary
key(x)
  2  /

Table altered.

ops$tkyte@DEV816> alter table t2 add constraint t2_fk_t1
  2  foreign key (x) references t1
  3  ON DELETE CASCADE
  4  /

Table altered.

ops$tkyte@DEV816>
ops$tkyte@DEV816> select a.name, b.value
  2    from v$statname a, v$mystat b
  3   where a.name like '%table scan%'
  4     and a.statistic# = b.statistic#
  5  /

NAME                                VALUE
------------------------------ ----------
table scans (short tables)             13
table scans (long tables)              10
table scans (rowid ranges)              0
table scans (cache partitions)          0
table scans (direct read)               0
table scan rows gotten              10846
table scan blocks gotten             3579

7 rows selected.

ops$tkyte@DEV816> delete from t1 where x = 499;

1 row deleted.

ops$tkyte@DEV816> select a.name, b.value
  2    from v$statname a, v$mystat b
  3   where a.name like '%table scan%'
  4     and a.statistic# = b.statistic#
  5  /

NAME                                VALUE
------------------------------ ----------
table scans (short tables)             13
table scans (long tables)              11
table scans (rowid ranges)              0
table scans (cache partitions)          0
table scans (direct read)               0
table scan rows gotten              12344
table scan blocks gotten             4079

7 rows selected.

ops$tkyte@DEV816>

and 12344-10846 = 1498 is exactly the number of rows in T2 which
was full scanned.  I made sure t2 was > 2% of my buffer cache to
show it shows as a "long table"
September 14, 2000 Michel -- Thanks for the question regarding "To stop the execution of a procedure", version 8.0.4
You Asked
Good morning Tom,

 I hope this finds you well;
 With Designer(2.0.2) i built a form (Ver. 5.0.6.16) that has 2
buttons. Start and Stop. A program unit (start_button),called by
the when-button-pressed trigger in the form, uses a for_loop
cursor to build a data set of 35 procedures to be called
dynamically in a particular order. Some of these procedures will
run for up to 4 hours. I don't need to stop a procedure in '
mid-air', but i need to be able to access the stop button on the
form and click on it while one of these procedures is running so
that when the procedure has completed successfuly the execution
will stop even if the data set build by the cursor has not run
to the end. There is a check point in the loop when a procedure
ends; If it fails, i exit the loop if it succeeds, i get the
next one.
 I have no idea how to enable the stop button while a procedure
is running
I hope you can give me a hand!
Michel
and we said...
Here is how I would do this -- use dbms_job to run the job in
the background in the database.  Don't run it in the client (for
hours and hours).

If you use dbms_job, and you instrument your stored procedures
with calls to the dbms_application_info package, your client can
monitor its progress by querying the v$session table.  You can
then show people how far the procedure is and allow the client
to go about its work.  Additionally -- to "stop" the running
program, your client can simply insert a row into a table and
your procedure can "look" for that row and stop when it sees it
(or use DBMS_ALERT or any method to get a message to this other
session).

Other then that, if you are really going to run this on the
client, I would use 2 forms and 2 sessions.  Using logic just
like above - the first form would run the second form which
would run the procedures.  The first form would not be blocked.
The first form can signal the other form via a DBMS_ALERT or
insert into a message table to tell it to "stop".  Additionally
you would still use dbms_application_info to allow form1 to
display the progress of form2.
September 14, 2000 Farhad -- Thanks for the question regarding "Regarding random numbers generation.", version 8.1.6
You Asked
Hi Tom,
    Thanx for your answer regarding inserting the values in
table containing ref object. Well this time I want to know that
does Oracle have any function or procedure for random numbers
generation? We can do this with the help of Sequence also and I
tried but couldn't attain the objective.
     Can u please tell me regarding this?
     Hoping for your reply a.s.a.p.

 Thanx,
 Farhad.
and we said...
see
http://osi.oracle.com/~tkyte/Misc/Random.html
..
September 14, 2000 raakhee -- Thanks for the question regarding "Dtabase Query", version version 8.0.6
You Asked
How can you extract all permissions of a specific table in a
database?
PS : I am not the DBA
and we said...
if you own the table, you can select from user_tab_privs and get
them for your tables.

Else you need to be a dba and then you can get them for any
table from dba_tab_privs.
September 14, 2000 Narendra -- Thanks for the question regarding "High water mark in Table sapce", version 7.3.2.2.1
You Asked
Morning Mr.Tom
Thanks for the yesterday the tips.
My question is regarding High Water mark in Tablespace.
What actually it means and how to interprate when it High or
Low.will it affect the performance of system.(We are using
Oracle 7.3.2.2.1).

I have two Tablespace Say A and B on seperate disk.
Tablespace A(total size=600m) is for Datafile and contains two
datafile of size 500m and 100m
Tablespace B(total size=1200m) is for INDEX and contains 3
datafile of size 400m each.
When I use and check the storage usuage using Storage manager .I
found the High water mark indication as below.

Table sapce      size      H.W.Mark (showing at)
A                        600m    416.477m
B                       1200m   847.340m

When I check the individual datafile the H.W.Mark is as below.
Table sapce(A)      size      H.W.Mark (showing at)
D1                          500m   364.50m
D2                          100m    52.45m

Table sapce(B)      size      H.W.Mark (showing at)
I1                           400m   399.230m
I2                          400m    381.311m
I3                           400m   66.744m

Is this ok are there is problem due to High water mark.and if
problem then How to solve it.
Thanks and regards
NP
and we said...
The high water mark of a file shows you the smallest size the
file could be "shrunk" down to.  All the above says is you have
600meg allocated to datafile A, it could be shrunk to 417meg if
you wanted.

The high water mark of a file in a tablespace has no bearing
on performance whatsoever.  The above does not indicate any
problems to me unless you are short on space in the filesystem
in which case the above shows how small you could shrink the
files to.

I myself use the following script to generate alter database
datafile '......' resize commands to shrink files down to their
smallest possible size.  Just bear in mind that unless you have
autoextend on -- if you shrink the file you just gave up all of
that free space.  You might not be able to extend your tables
into new extents!

set verify off
column file_name format a50 word_wrapped
column smallest format 999,990 heading "Smallest|Size|Poss."
column currsize format 999,990 heading "Current|Size"
column savings  format 999,990 heading "Poss.|Savings"
break on report
compute sum of savings on report

column value new_val blksize
select value from v$parameter where name = 'db_block_size'
/

select file_name,
       ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) smallest,
       ceil( blocks*&&blksize/1024/1024) currsize,
       ceil( blocks*&&blksize/1024/1024) -
       ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) savings
from dba_data_files a,
     ( select file_id, max(block_id+blocks-1) hwm
         from dba_extents
        group by file_id ) b
where a.file_id = b.file_id(+)
/

column cmd format a75 word_wrapped

select 'alter database datafile ''' || file_name || ''' resize '
||
       ceil( (nvl(hwm,1)*&&blksize)/1024/1024 )  || 'm;' cmd
from dba_data_files a,
     ( select file_id, max(block_id+blocks-1) hwm
         from dba_extents
        group by file_id ) b
where a.file_id = b.file_id(+)
  and ceil( blocks*&&blksize/1024/1024) -
      ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) > 0
/
Review & Followup
Rating: 5
Thanks, Tom September 21, 2001
Reviewer: Charlotte from Louisiana
This is great!

Rating: 4
Amazing script August 10, 2003
Reviewer: Saeed Ahmed. from India.
I liked this scripts very much, at toms site ever read leads to more thrist and
to learn more about the Oracle stuffs.

May God guide TOM and his team to the straight path.

September 14, 2000 Bala -- Thanks for the question regarding "Exp", version 8.0.4
You Asked
Hi Tom

Would like to know if there is any option available in the export command to
export the table structure and the contents of the table in the text format.

Regards

Bala
and we said...
not on the export but on the imp.

imp userid=/ tables=t indexfile=t.sql

t.sql will have the structure of T in it. Not intuitive to use indexfile to get
this but it works.
September 15, 2000 BELBAHRI -- Thanks for the question regarding "send eMail from PLSQL Procedure ", version ORACLE 8.0.5.0.0
You Asked
How can i send eMail from PLSQL Procedure to an user ?
Thanks
and we said...
In 8.0 your options are:

o using an external procedure written in C.  See chapter 10 of
the PLSQL guide for details on external procedures.  Using this
-- you can write almost any extension you want.

o using UTL_HTTP.  If you set up a URL that runs a cgi-bin
program and that cgi-bin program you setup can "send mail" --
then PLSQL can call that URL to send mail.  What I've done in
the past is to setup a webserver on the database machine running
on IP address 127.0.0.1.  I setup a small script that sends mail
for me and I run it by doing a URL like:

   utl_http.request( 'http:
//127.0.0.1/cgi-bin/domail?p_to=x&p_sub=y&p_body=Hello+There' );

since the webserver is running on 127.0.0.1, you have to be
logged onto the server to use it -- preventing others from
sending mail as "my database account".

o using dbms_pips to write an external process that your plsql
would "talk to".  See
http://osi.oracle.com/~tkyte/plex/index.html
for an example of what I mean by that.  Or see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:16212348050
...
September 15, 2000 Andre -- Thanks for the question regarding "Preventing tablespaces from blowing out", version 8.1.6
You Asked
Hi Tom,

I have this query:

select tablespace_name,
       owner,
       segment_name,
       segment_type,
       next_extent
from dba_segments s
where s.next_extent> (select max(bytes)
                      from dba_free_space f
                      where f.tablespace_name=s.tablespace_name)
order by 1;

It was supposed to list all segments which won´t find enough
contiguous free space in the tablespace in the next extend.
However, it seems to be wrong because what it is really doing is
finding out if the NEXT segment extent fits into the largest
free extent, and not if there is enough contiguous free extents
that would accomodate that next extent.

The problem is I am not able to find a pattern in the dictionary
views where I can discover the contiguous free space in order to
make a query.

Would you please help me rewrite this ?

Regards.
and we said...
First off -- if you use locally managed tablespaces -- not
dictionary managed ones, this will not be an issue at all as
local management of extents automatically tracks adjacent free
space, eliminating the need to coalesce free extents.  Locally
managed tablespaces are the greatest thing since sliced bread.

If you have a dictionary managed tablespace, the easiest thing
to do is "alter tablespace T coalesce".  Now, all free chunks
that are in fact contigous will be coalesced.

Now, can we write a query to get this without coalescing?  Yes
-- if you are willing to use a temp table.  We can use connect
by to get the sum of all contigous extents but since, in 8i and
up, dba_free_space is a union all -- we cannot connect by on it.
 We need to put it into a "flat" table and then connect by.

Here is an example:

ops$tkyte@DEV816> create global temporary table
  2  dba_free_space_temp
  3  as
  4  select *
  5    from dba_free_space
  6   where 1=0;
Table created.

You'll create this ONCE per database...

Now, lets create some "fragmentation".  This works by
HOPEFULLY creating 10 contigous extents -- YOUR MILEAGE MAY
VARY.  On my system -- it did. if your system is fragmented
already it might not!  Now, I use system here since that is the
only tablespace that is not locally managed in my database (and
this is not an issue in those)

ops$tkyte@DEV816> create table t
  2  ( x int )
  3  tablespace system
  4  storage
  5  ( initial 1k
  6    next 1k
  7    pctincrease 0
  8    minextents 10 );

Table created.

ops$tkyte@DEV816> drop table t;
Table dropped.

 I should have 10 free extents in system now.  Hopefully
contigous.

ops$tkyte@DEV816> insert into dba_free_space_temp
  2  select * from dba_free_space;
27 rows created.

ops$tkyte@DEV816> select tablespace_name, max(sum_blocks)
  2    from ( select tablespace_name, file_id, block_id,
  3                ( select max(block_id+blocks-1)-a.block_id+1
  4                    from dba_free_space_temp
  5                   start with file_id = A.file_id
  6                          and block_id = A.block_id
  7                 connect by prior file_id = file_id
  8                     and prior (block_id+blocks) = block_id
  9                ) sum_blocks
 10             from dba_free_space_temp A
 11         )
 12   group by tablespace_name
 13  /

TABLESPACE_NAME                MAX(SUM_BLOCKS)
------------------------------ ---------------
FLOWS_IDX                                 1216
SCATS_DATA                                1216
SCHEDULER_DATA                           23488
SCHEDULER_IDX                             2048
SYSTEM                                      85
USERS                                     2560

6 rows selected.

 that shows, by tablespace, the largest set of blocks
available -- if I just query up dba_free_space I see:

ops$tkyte@DEV816>
ops$tkyte@DEV816> select tablespace_name, max(blocks)
  2    from dba_free_space
  3   group by tablespace_name
  4  /

TABLESPACE_NAME                MAX(BLOCKS)
------------------------------ -----------
FLOWS_IDX                             1216
SCATS_DATA                            1216
SCHEDULER_DATA                       23488
SCHEDULER_IDX                         2048
SYSTEM                                  79
USERS                                 2560

6 rows selected.

they do not agree -- the first query is correct -- the connect
by summed up all of the contigous free space for us... We can
prove this by:

ops$tkyte@DEV816> alter tablespace system coalesce;

Tablespace altered.

ops$tkyte@DEV816>
ops$tkyte@DEV816> select tablespace_name, max(blocks)
  2    from dba_free_space
  3   group by tablespace_name
  4  /

TABLESPACE_NAME                MAX(BLOCKS)
------------------------------ -----------
FLOWS_IDX                             1216
SCATS_DATA                            1216
SCHEDULER_DATA                       23488
SCHEDULER_IDX                         2048
SYSTEM                                  85
USERS                                 2560

6 rows selected.

ops$tkyte@DEV816>

and now they are equal
September 15, 2000 Dave -- Thanks for the question regarding "EVT and SM tables", version 8.05
You Asked
I have a customer database that is continually having a bunch of
tables named EVT* and SM* created.  We need to determine what
Oracle process is creating them, so we can have that process
stopped.  It only occurs in one of the databases, and appears in
the user tables.
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:273615739251
someone is using OEM and is creating a respository.
September 15, 2000 Kofi -- Thanks for the question regarding "Trigger scripts", version 8.0.5.00
You Asked
Hi,

Is there a way to generate a script, that can be used to
recreate a trigger.  I tried to use the following query

"Select 'Create or replace trigger '||description,trigger_body
 from Dba_triggers where trigger_name = 'Name of desired
trigger"

This did not give me the whole script.  Part of it was cut off.
Can this be done.

Kofi
and we said...
The trigger body is stored in a long.

By default, only 80 characters of a long are shown in sqlplus.

Simply issue:

SQL> set long 5000

before you run the query or put that in your login.sql script.
September 15, 2000 Le -- Thanks for the question regarding "CLOB in SQL Plus ", version Oracle 8i - v 8.1.5
You Asked
Dear sir,

   First, Thank you very much for the tip on WebDB you sent the
other day.

   I have a table with a CLOB field. I tried to browse some
lines of text in that field using SQL_PLUS and Oracle just
returned just a line (about 70 or 80 char) even with the SET
SERVEROUTPUT ON SIZE 1000000 (max) format wortd_wrapped was on

   I understand that CLOB is the only LOB you can browse in
SQL-PLUS without resorting to DBMS_LOB and its features since we
try to make things easy for users to browse their authorized
tables.

   Please help. Thank you for your time.
and we said...
SQL> set long NNNN

where NNN is some big number.  that controls how much of a
clob/long gets displayed.
September 15, 2000 Tomas -- Thanks for the question regarding "Verification of backup", version 8i 8.1.5.0.0
You Asked
Hey Tom

Do you got a good tip how to verificate, that your backup was
ok?

In this case Oracle backup facilities are not used.

Thanks

Tomas
and we said...
only one method works -- in all cases (regardless of the backup
method -- ours, theirs, yours).  Find another machine and
restore it.

You can use dbv on the files -- but that won't tell you if you
can actually recover using it.  good practice as well to
practice recovery.  You really don't want to learn how to on the
day of the crash..
September 15, 2000 David -- Thanks for the question regarding "Problems with object sizing", version 8.0.5.2.0
You Asked
Tom,
    I've stumbled across a little puzzler here at the office. I
have built a package to perform the Oracle space calculations
just to make life easier. I was running the package for a group
of 25 tables being built as part of a feed to a data mart. The
puzzler was that all the calculation results were null for one
of the tables. I was stumped by this so I decided to check the
rowsize calculation in SQL*Plus. The table contained 152 records
at time of writing and I have included a description of the
table and one sample record. Any ideas you can suggest would be
gratefully received.

SQL> desc gmf02.sbo_bss_admin_failed
 Name                            Null?    Type
 ------------------------------- -------- ----
 CMS_ID                                   NUMBER(5)
 FAIL_DATE                                DATE
 TABLE_NAME                               VARCHAR2(30)
 RECORD                                   VARCHAR2(2000)
 FLAG                                     VARCHAR2(1)

SQL> select * from gmf02.sbo_bss_admin_failed where rownum < 2
  2  /

    CMS_ID FAIL_DATE   TABLE_NAME
---------- ----------- --------------------
RECORD
-----------------------------------------------------------------
---------------
F
-
           15-SEP-2000 STIN_MIDAS_SCHEDULE
241050,NVOD00000295689,25-AUG-2000,22:00:00,1803
D

Elapsed: 00:00:00.03

1  SELECT NVL( AVG( VSIZE( CMS_ID) ) +
  2  AVG( VSIZE( FAIL_DATE) ) +
  3  AVG( VSIZE( TABLE_NAME) ) +
  4  AVG( VSIZE( RECORD) ) +
  5  AVG( VSIZE( FLAG) ) , -9999999 )
  6* from gmf02.sbo_bss_admin_failed
SQL> /

NVL(AVG(VSIZE(CMS_ID))+AVG(VSIZE(FAIL_DATE))+AVG(VSIZE(TABLE_NAME
))+AVG(VSIZE(RE
-----------------------------------------------------------------
-----

-9999999

Elapsed: 00:00:00.01

Regards,
David.
and we said...
All of the values of CMS_ID must be NULL.  the avg(vsize) for
them is NULL.  NULL+anything = NULL.  This shows the problem
happening, how an update "corrects" the original query, and how
to write the query to avoid the issue:

ops$tkyte@DEV816> create table sbo_bss_admin_failed
  2  (
  3   CMS_ID                                   NUMBER(5),
  4   FAIL_DATE                                DATE,
  5   TABLE_NAME                               VARCHAR2(30),
  6   RECORD                                   VARCHAR2(2000),
  7   FLAG                                     VARCHAR2(1)
  8  )
  9  /

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into sbo_bss_admin_failed
  2  values
  3  ( null, '15-SEP-2000', 'STIN_MIDAS_SCHEDULE',
  4  '241050,NVOD00000295689,25-AUG-2000,22:00:00,1803',
  5  'D' );

1 row created.

ops$tkyte@DEV816> commit;

Commit complete.

ops$tkyte@DEV816> select * from sbo_bss_admin_failed;

    CMS_ID FAIL_DATE TABLE_NAME
---------- --------- ------------------------------
RECORD
-----------------------------------------------------------------
-----------------------------------
F
-
           15-SEP-00 STIN_MIDAS_SCHEDULE
241050,NVOD00000295689,25-AUG-2000,22:00:00,1803
D

ops$tkyte@DEV816>
ops$tkyte@DEV816> SELECT NVL( AVG( VSIZE( CMS_ID) ) +
  2              AVG( VSIZE( FAIL_DATE) ) +
  3              AVG( VSIZE( TABLE_NAME) ) +
  4              AVG( VSIZE( RECORD) ) +
  5              AVG( VSIZE( FLAG) ) , -9999999 )
  6                                          avgsize
  7  from sbo_bss_admin_failed
  8  /

   AVGSIZE
----------
  -9999999

ops$tkyte@DEV816>
ops$tkyte@DEV816> update sbo_bss_admin_failed
  2  set cms_id = 1;

1 row updated.

ops$tkyte@DEV816>
ops$tkyte@DEV816> SELECT NVL( AVG( VSIZE( CMS_ID) ) +
  2              AVG( VSIZE( FAIL_DATE) ) +
  3              AVG( VSIZE( TABLE_NAME) ) +
  4              AVG( VSIZE( RECORD) ) +
  5              AVG( VSIZE( FLAG) ) , -9999999 )
  6                                          avgsize
  7  from sbo_bss_admin_failed
  8  /

   AVGSIZE
----------
        77

ops$tkyte@DEV816>
ops$tkyte@DEV816> rollback;

Rollback complete.

ops$tkyte@DEV816>
ops$tkyte@DEV816> SELECT NVL( AVG( nvl(VSIZE( CMS_ID),0) ) +
  2              AVG( nvl(VSIZE( FAIL_DATE),0) ) +
  3              AVG( nvl(VSIZE( TABLE_NAME),0) ) +
  4              AVG( nvl(VSIZE( RECORD),0) ) +
  5              AVG( nvl(VSIZE( FLAG),0) ) , -9999999 )
  6                                          avgsize
  7  from sbo_bss_admin_failed
  8  /

   AVGSIZE
----------
        75
September 15, 2000 Steve -- Thanks for the question regarding "Stored Procedures", version 7.0.16.6.2
You Asked
Why do I get the error message "PLS-00103: Encountered the
symbol "ALTER" which is an unsupported reserved word" when I try
using an ALTER SEQUENCE statement from within a stored
prodecure.  I can execute the identical statement from PL/SQL
without any errors. Thanks for your help.
Steve
and we said...
7.0.16 -- really, wow that is old....

PLSQL cannot do DDL directly.  When you say above "i can execute
the statement from PLSQL without ..." I believe you mean "i can
execute the statment in SQLPlus without...".  You cannot put
CREATE, ALTER, DROP, GRANT type statements in PLSQL.

In version 7.1 and up of the database we added a package called
DBMS_SQL to the database.  this package allows PLSQL to do
dynamic sql and hence allows PLSQL to do DDL such as you would
like.  This package is not available to be installed in 7.0.
September 15, 2000 rajat -- Thanks for the question regarding "max open cursors exceeded ora 01000", version 8.1.5
You Asked
hi tom:
i have a database procedure that logs user activity to the DB.
this user activity is happening in the form of Java/XML apps.
so everytime a user logs in the Java/XML code calls my DB
procedure passing in parameters like name, id etc. all this
detail is inserted into a DB log table.
the proc is very simple
proc xyz (p1 in number, p2 in varchar2...)
begin
insert into log values(p1 in number, p2 in varchar2...);
end;

thats it. no selects, no explicit cursor openings etc.

also, the open_cursors param is set to 2000. then dml_locks is
about 200 and processes is 100.

so, what in your opinion is causing the max open cursor exceeded
error ? bit stupefied !

thanks in advance for any suggestions/help.

rajat
and we said...
Your java code isn't close the cursors somewhere.  When the java
calls the stored procedure - it gets a cursor.  You are not
closing on of them somewhere.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:741225570852
and take a peek at v$open_cursor which might help you track down
this as well.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:553222846752
for more info on that.
September 15, 2000 Arthur -- Thanks for the question regarding "Uniform Extent Sizes", version 8.1.5
You Asked
Tom,

In dealing with locally managed tablespaces, if you use the
uniform clause, all the entents are allocated to the same size.
Are these blocks necessarily contiguous?  What happens to the
free space when deleting records?  Is there a still a need to
coalesce a tablespace?

Arthur
and we said...
The blocks within an extent are always contigous - regardless of
the tablespace type.  That is unchanged.

The free space in a locally managed tablespace is treated in the
same exact fashion as a dictionary managed one.  Once an extent
is allocated to a table (segment, i'll just use table as an
example), its blocks are for the exclusive use of that table.
When I delete rows from a table, if the amount of free space on
the block is larger then the PCTUSED setting for the block -- we
will put it on the tables freelist.

There is no need to coalesce a locally managed tablespace -- the
bitmap does that automagically for us.
September 15, 2000 raja -- Thanks for the question regarding "Grants and privileges", version 8
You Asked
I have say two schemas in my database say
sch1 and sch2. Tables are owned by sch1 and there are tiggers
associated with these tables.
The user sch2 has been granted select on these tables through a
role.
The user sch2 is not able to see the triggers associated with
these tables in his all_triggers but can see the table_name in
this all_tables.What all privilege do i need to grant on the
table so that user sch2 can see the trigger in his all_triggers
Thanks in advance
and we said...
You can see a trigger if:

o you own it
o you have the CREATE ANY TRIGGER priv

Its like a package body -- execute does not give you the ability
to see the code.  triggers are handled in the same way.

Alternatively, you can grant this person access to dba_objects
which lets you see everything.  You could create a view on
dba_objects that sch2 has access to that lets him see all of
sch1's objects.
September 15, 2000 -- Thanks for the question regarding "Search strings in dba_views", version 7.3.4
You Asked
How can we search for a string in the text column (long dataype)
of dba_views?
For example, I need to find all the views that have the string
'customer_address'
in the sql text.

Thanks.
and we said...
Not in SQL, you'll have to do something like:

set serveroutput on

begin
  for x in (select * from dba_views ) loop
        if ( x.view_text like '%customer_address%' ) then
           dbms_output.put_line( x.view_name );
        end if;
  end loop;
end;
/

That'll work as long as the view text is 32k or less.
Review & Followup
Rating: 5
Very Handy July 23, 2002
Reviewer: Mike

Rating: 5
Search strings in dba_views April 18, 2003
Reviewer: MBluhm from KANSAS CITY, MO USA
Exactly what I was looking for.


Subject | Article | Last Updated (East coast time)
decode function | article only | Sep 16, 2000 09:53 am
SQL -- timing it. | article only | Sep 16, 2000 09:59 am
Question regaring TRANSACTION_AUDITING parameter | article only | Sep 16, 2000 10:12 am
Primary and unique keys on same column | article only | Sep 16, 2000 10:25 am
Logon | article only | Sep 16, 2000 11:55 am
Query performance | article only | Sep 16, 2000 04:31 pm
SQL Script | article only | Sep 17, 2000 09:47 am
Inserting Default Value | article only | Sep 17, 2000 09:54 am
Updation of values in the collection (Nested Table) | article only | Sep 17, 2000 11:54 am
Questions regarding parse and space and listener | article only | Sep 17, 2000 01:46 pm
HA Oracle | article only | Sep 17, 2000 02:46 pm
DBA SCRIPTS -- where are 10 scripts every dba should have by Kevin Loney | article only | Sep 17, 2000 07:39 pm
Oracle user | article only | Sep 18, 2000 06:23 am
Installing all available PL/SQL packages | article only | Sep 18, 2000 07:07 am
a complex algorithm | article only | Sep 18, 2000 08:08 am
Table and index in disk | article only | Sep 18, 2000 08:16 am
Hash operation and it's memory usage | article only | Sep 18, 2000 08:21 am
database sequence | article only | Sep 18, 2000 08:30 am
Export/Import vis SQLLOADER | article only | Sep 18, 2000 09:13 am
Application error | article only | Sep 18, 2000 09:22 am
Export data to Flat file | article only | Sep 18, 2000 10:45 am
HA Oracle for sun | article only | Sep 18, 2000 10:48 am
Table "real" used space | article only | Sep 18, 2000 10:59 am
Execute procedure with my objects in another schema | article only | Sep 18, 2000 01:40 pm
attach sequence to a primary key | article only | Sep 18, 2000 07:19 pm
Autonomous Transaction | article only | Sep 18, 2000 07:23 pm
NLS changes in 8i -- NLS_COMP vs NLS_SORT | article only | Sep 18, 2000 07:31 pm
Context Server Cartridge | article only | Sep 18, 2000 07:39 pm
Header Files | article only | Sep 18, 2000 07:48 pm
XML parser | article only | Sep 18, 2000 08:12 pm
Returning Arrays From JAVA Stored Function | article only | Sep 18, 2000 08:51 pm
Appropriate option to work with Microsoft Cluster Server | article only | Sep 19, 2000 06:47 am
article only | Sep 19, 2000 07:00 am
jobs getting delayed , log_buffer | article only | Sep 19, 2000 07:44 am
PL/SQL package | article only | Sep 19, 2000 08:12 am
blocks in use by a table | article only | Sep 19, 2000 09:14 am
Data migration from 7.3.4 to 8.1.6 | article only | Sep 19, 2000 09:26 am
Creating foreign Key.. | article only | Sep 19, 2000 11:29 am
Select statement | article only | Sep 19, 2000 11:40 am
concurrent users and init.ora | article only | Sep 19, 2000 12:18 pm
How to access User defined arrays from out side pl/sql environment. | article only | Sep 19, 2000 12:51 pm
primary key datatype | article only | Sep 19, 2000 01:42 pm
reclaim space in blob | article only | Sep 19, 2000 07:12 pm
Portability of diagrams generated from designer | article only | Sep 20, 2000 10:43 am
character set | article only | Sep 20, 2000 01:16 pm
row(s) 1 - 45 of 45
September 16, 2000 lynn -- Thanks for the question regarding "decode function", version 8.05
You Asked
Dear Tom,

I have a question about the function decode for fisco year
information.  Our fy starts 7/1.  The business rule is: if it is
the month of Jul., Aug., Sept., Oct., Nov., and Dec., the fy is
2001, if not the fy is 2000.  So after failed a lot of times, I
got:

select decode(to_char(sysdate, 'MM'), '07', to_char(sysdate+365,
'YYYY'), '08', to_char(sysdate+365, 'YYYY'),.......
/* until I finished Dec. */
to_char(sysdate, 'YYYY') from dual;

I tried to put 07-12 into in (), and other range expressions so
that I don't need to type so much, but failed.  Do you have any
suggestion that I can reduce the typing for decode a range of
values?

Thanks a lot.

Lynn Zhao
AAMC
and we said...
I don't think you need decode at all but here is how to with
decode and with a simple add months.  If we simply add 6 months
to any date and just look at the YYYY portion, that'll give us
your fiscal year. SIGN() is the trick to making the decode
easier if you want to use that (but add_months will be much
easier):

ops$tkyte@ORA8I.WORLD> create table dates
  2  as
  3  select add_months(sysdate,rownum-12) dt
  4    from all_objects
  5   where rownum <= 36
  6  /

Table created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select dt,
  2             to_char( add_months(dt,6), 'yyyy') ,
  3         decode( sign( to_char(dt,'mm')-7 ),
  4                   -1, 'first half',
  5              /* default */ 'second half' )
  6    from dates
  7  /

DT        TO_C DECODE(SIGN
--------- ---- -----------
16-OCT-99 2000 second half
16-NOV-99 2000 second half
16-DEC-99 2000 second half
16-JAN-00 2000 first half
16-FEB-00 2000 first half
16-MAR-00 2000 first half
16-APR-00 2000 first half
16-MAY-00 2000 first half
16-JUN-00 2000 first half
16-JUL-00 2001 second half
16-AUG-00 2001 second half
16-SEP-00 2001 second half
16-OCT-00 2001 second half
16-NOV-00 2001 second half
16-DEC-00 2001 second half
16-JAN-01 2001 first half
16-FEB-01 2001 first half
16-MAR-01 2001 first half
16-APR-01 2001 first half
16-MAY-01 2001 first half
16-JUN-01 2001 first half
16-JUL-01 2002 second half
16-AUG-01 2002 second half
16-SEP-01 2002 second half
16-OCT-01 2002 second half
16-NOV-01 2002 second half
16-DEC-01 2002 second half
16-JAN-02 2002 first half
16-FEB-02 2002 first half
16-MAR-02 2002 first half
16-APR-02 2002 first half
16-MAY-02 2002 first half
16-JUN-02 2002 first half
16-JUL-02 2003 second half
16-AUG-02 2003 second half
16-SEP-02 2003 second half

36 rows selected.
Review & Followup
Rating: 5
DECODE with IF March 23, 2001
Reviewer: Hector Ulloa Ligarius from Santiago , Chile
Hi TOM :

I need :

select decode(a,0,'Cero',if a < 1 then Negative) result
from table1;

The table1 is :
Field1
-------------
 0
-1
-2
 0

Execute :

Result
------
Cero
Negative
Negative
Cero

How do you do?

My English is so so

Rating: 3
DECODE with IF October 29, 2003
Reviewer: naresh from Delhi
hi
this will give u the reqd result i guess
select decode(sign(<field>), -1, '-ve', 1, '+ve', 'zero') from <table_name>

September 16, 2000 Dave -- Thanks for the question regarding "SQL -- timing it.", version 8i
You Asked
hi

how can i have the time elapsed when excuting a sql statment

exemple:
select count(*) from table

Elapsed----

thanks in advance
and we said...
In sqlplus, simply issue:

SQL> set timing on
SQL> select count(*) from table;

In plsql, you can make a call to dbms_utility.get_time before doing the query
and again after, subtract the two and divide by 100 to get seconds.

If this is embedded in a program, you can set timed_statistics on and sql_trace,
run the program, and get all of the timings.  See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76992/ch14_str.htm#1018
for details.
September 16, 2000 Ashish -- Thanks for the question regarding "Question regaring TRANSACTION_AUDITING parameter", version 8.1.6
You Asked
Hello Tom,

I recently installed Oracle 8.1.6.0 on Sun Solaris 5.6
and then created the database.

After few days I noticied small text files with .aud extension
in the auditing subdirectory.

Via svrmgrl I checked that TRANSACTION_AUDITING parameter
is set to TRUE.(documentation on it say this is by default,
which is surprising).

Anyway via documentation I was able to find out that
this TRANSACTION_PARAMETER helps in using the redo logs
via the latest log analyzer tool.(by giving more information
etc)

Here are my questions
1)What is the performance implications of setting
TRANSACTION_AUDITING=TRUE.
2)In init<sid>.ora file how due you set it to false

and if you any more pro and cons on this parameter
Please let me know

Thanks

Ashish
and we said...
The .aud files have nothing to do with the transaction_auditing.
 They are part of our C2 compliance, they must be generated and
you cannot disable them.  One will be generated upon connecting
internal.

If TRANSACTION_AUDITING is TRUE, the transaction layer generates
a special redo record which contains session and user
information. This information includes the user logon name, user
name, the session ID, some operating system information, and
client information. On each successive commit, the transaction
layer generates a record that contains only the session ID
(which links back to the first record since it also contains the
session ID). These records might be useful if using a redo log
analysis tool.

The implications are very small.

to set it off, just add

transaction_auditing=false

in the init.ora and restart the database.
September 16, 2000 Randy -- Thanks for the question regarding "Primary and unique keys on same column", version 8.1.6
You Asked
I'm working with some consultants who have written table
creation scripts.  On many tables, they've indicated a UNIQUE
key AND a PRIMARY key constraint on the same column.  I don't
see the point in having the unique constraint since the primary
is really doing the job.

Two questions:

1)The PRIMARY key seems to take precedence over the UNIQUE when
actually creating an index segment.  Given that you cannot index
the same column twice, I assume the UNIQUE key just uses the
index created by the PRIMARY key constraint to enforce
uniqueness.  Is this always the case or is this ever in reverse?

2)Why does Oracle allow you to create both when they do the same
thing (as far as enforcing uniqueness of the column) and a
primary will also not allow nulls?

Thanks.
and we said...
Both the PRIMARY KEY and UNIQUE constraints will "hijack" any
existing index or create one if need be on the underlying
columns.

I cannot get it to create both myself:

ops$tkyte@ORA8I.WORLD> drop table emp;

ops$tkyte@ORA8I.WORLD> create table emp as select * from
scott.emp;

ops$tkyte@ORA8I.WORLD> alter table emp add constraint emp_u
unique(empno);

ops$tkyte@ORA8I.WORLD> alter table emp add constraint emp_pk
primary key(empno);
alter table emp add constraint emp_pk primary key(empno)
                                      *
ERROR at line 1:
ORA-02261: such unique or primary key already exists in the
table

ops$tkyte@ORA8I.WORLD> drop table emp;

ops$tkyte@ORA8I.WORLD> create table emp as select * from
scott.emp;

ops$tkyte@ORA8I.WORLD> alter table emp add constraint emp_pk
primary key(empno);

ops$tkyte@ORA8I.WORLD> alter table emp add constraint emp_u
unique(empno);

alter table emp add constraint emp_u unique(empno)
                                     *
ERROR at line 1:
ORA-02261: such unique or primary key already exists in the
table

UNLESS I do it in the create table:

ops$tkyte@ORA8I.WORLD> create table emp ( empno int primary key,
  2                          constraint emp_u unique(empno) );

Table created.

ops$tkyte@ORA8I.WORLD> select constraint_name, constraint_type
from user_constraints;

CONSTRAINT_NAME                C
------------------------------ -
SYS_C0030857                   P
EMP_U                          U

I'm at a loss to say "why" this is the case.
September 16, 2000 Bjørn Erik -- Thanks for the question regarding "Logon", version Oracle 8i
You Asked
I understand from previous posts that you recommend "basic
oracle" logon for authentication for web-apps.

I have some questions on this topic.

As I understand it, Oracle App. Server have divided its auth.
into two:

- Digest/Basic etc. on the listsener level, to protect the
virtual directories. Users/password is stored in a file on the
server.

- Basic oracle - where the user have to log on to the database.
User/pw is stored in database.

---
My questions:
1. Why is "basic oracle" better then an custom made
authentication on application level? With cookies with a session
ID written to the client.

2. How does "basic oracle" manage without cookies? How does it
handle sessions?

3. Does it support WAP?

4. Can the database user table be updated/modified from a
browser?

5. Isn't a custom made solution more flexible?

Thanks alot in advance.

Bjørn Erik Pedersen, Norway.
and we said...
There is basic authentication and "cookie based -- do it
yourself" authentication.

With base authentication, the browser is responsible for
maintaining your "identity", your credentials.  It will encode
them and transmit them in the HTTP header record with each
request.  It is sort of a "free" cookie without using a cookie.
That is how it is done without cookies -- the browser sends the
credentials encoded in the header just like it does with
cookies.

With OAS we support basic authentication whereby the
user/password can be stored in a flat file.  We can also do
basic authentication whereby the username and password are valid
database accounts.  This is useful for protecting files and
cgi-bin programs (making sure only authorized people can access
them).

When building a database application to generate dynamic pages
(eg: with the PLSQL cartridge -- I like to use a DAD that is
created without storing the username/password with the DAD.
This looks very much like Oracle Basic above. the user will have
to supply a username and password to log into the database to
run the application.

So that is a little background.  The difference between "basic"
and "OracleBasic" is only where the credentials are stored --
other then that, they are identical.  Same with "do not store
the username/password with the DAD" -- that tells us to use
basic authentication to get the credentials at runtime.

Now, we do I prefer this?  (I is bold because this is
somewhat of an opinion).  I prefer this because by using a real
database account I:

o can use roles and grants to allow/disallow access to
procedures.

o can use database auditing to see who is doing what

o can use a simple "select user from dual" to see who is running
my application

o use the same privelege model I've been using for years and
years.

If I was to implement my own login screen -- I would have to
write the authentication (verify user and password -- safely
store the username/password, validate it and so on).  I would
have to write my own authorization scheme.  With the database --
this is all done very securely for me and we have lots of tools
to maintain it (like OEM and so on).

My mantra is -- if the database can already do it -- I'll use
that feature of the database rather then re-implement it.  I am
very (some say excessively) database centric.  Using database
accounts is a natural thing for me.

So, that answers #1 and #2 above.  As for #5 -- that is purely a
matter of opinion.  My opinion is "no" -- but only because I am
100% comfortable using database accounts, I have over 30,000 of
them in my database right now and they take care of themselves.
The application owners just grant roles to individuals as needed
and thats that.

As for #3, WAP can use this -- you just have to write it.  I
don't see the connection here.

For #4, Yes, the database users can be created/modified and
dropped via the web.  In fact that is the way I do it with all
of my users.  They request an account on a non-secure page by
entering their email id.  We validate that against our HR table
and send them a randomly generated password after verifying
their data.  We grant them a series of generic roles that
everyone can have.  Once they have their accounts, they can
request other roles from other applications (request and
approval done on the web)...
September 16, 2000 -- Thanks for the question regarding "Query performance", version 8.0
You Asked
Hello sir,

I would like to ask 2 doubts...

1)
Part_no is a field of Varchar2(12) length(base table item). On
the form/screen there are three text items as
part1,part2,part3(Non basetable items). On insertion
part1||part3||'-'||part3 will be moved to part_no. In the table
part_no is unique.  Here on the screen user must enter atleast
part1 completely....

I am doing something like this..

select count(*) into x from part_master where
substr(part_no)=:part1;

if x<1 then
....
end;

The above query is slow and it leads to full table scan. Can u
suggest me what to do to increase the query performance. I am
using oracle 8.0.5 and forms 5.0. Should I move to oracle 8.1 ?
or use hints in the query ?

2) I dont want more than one forms session on a client machine.
I used win_api_session.one_session, and attachted d2kwutil.pll
to the main form. But I kept all applications fmx's on server.
When I run the application on client machine one message is
displayed "Cannot attach D2KWUTIL.PLL". How should I overcome
this?

thank you, thank you very much

regs
mubeen
and we said...
1) why not use:

select count(*) into x
  from part_master
 where part_no LIKE :part1 || '%';

That will do the same thing and use an index on part_no.  Using
a hint would not work -- once you use substr on the database
column -- the index cannot be used. In Oracle8i release 8.1, you
could use a function based index (create an index on
substr(part_no)) -- however, the LIKE will work just as well.

2) if you do not have d2kwutil.pll, you can use the advice on
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:368618111895
to get it (available via ftp)
September 17, 2000 Arindam -- Thanks for the question regarding "SQL Script", version 8.0.4
You Asked
how will i truncate the trailing filename in a directory list?
Let me explain, I'm using vdump to backup my datafile, and vdump
works on directory level only. I have written a script to get
the dbf files(both the data & logfile) of my database the
listing is like

/../../../../d.dbf
/../../../../c.dbf
/../../../../f.dbf etc

i want to use rtrim to get /../../../../ listing.

can you pls help me

thanks

Arindam
and we said...
Well, rtrim won't be able to do that but substr and instr can.
We can use instr to find the last / and then substr the leading
edge of the string.  It would look like this:

ops$tkyte@ORA8I.WORLD> variable x varchar2(25)
ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> exec :x := '/tmp/foo/bar/x.dbf'

PL/SQL procedure successfully completed.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select :x,
  2             substr( :x, 1, instr(:x,'/',-1) )
  3    from dual;

:X                               SUBSTR(:X,1,INSTR(:X,'/',-1))
-------------------------------- ----------------------------
/tmp/foo/bar/x.dbf               /tmp/foo/bar/
Review & Followup
Rating: 4
I need further formatting for my output like March 26, 2002
Reviewer: A reader
ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select :x,
  2             substr( :x, 1, instr(:x,'/',-1) )
  3    from dual;

:X                               SUBSTR(:X,1,INSTR(:X,'/',-1))
-------------------------------- ----------------------------
/tmp/foo/bar/x.dbf               /tmp/foo/bar/

Instead of /tmp/foo/bar/ , I need to separate tmp , foo and bar,  AND THEN give
them a description  like

if tmp then description
if foo  then foobar
bar then barcool    etc

Further, the catch is i do not know if the string will be just  /tmp/foo/bar/ ,
it can contain any number of elements( of different size like
/tmp/foo/bar/xxxx/yy/zzoooo/iiddi  etc.

It is also not necessary that the delimiter be / , it can be anything like
/tmp,foo'bar;xxxx||yy|zzoooo.iiddi

What is constant is that the string will be alwasy enclosed by parenthesis
(/tmp,foo'bar;xxxx||yy|zzoooo.iiddi)

My question is ...

How should I separate it like

tmp
foo
bar
xxxx
yy
zzoooo
iiddi

and also add description to it

thank you

September 17, 2000 Jayasri -- Thanks for the question regarding "Inserting Default Value", version 8.1.6
You Asked
Hi Tom
   I am student and learning Oracle. I had this question in one
of my interviews.

I have  to create a table with single column with default value.
Example
create table x (x number default 0);

How to insert the default value.

Regards
Jayasri
and we said...
It is a trick question.  You cannot if the table has but one
column.  The answer is:

insert into x (x) values (0);

Inserting NULL or any other values for x.x will override the
default.  The above table with a DEFAULT is a meaningless
example -- the default will never be used in any circumstances.
September 17, 2000 Farhad -- Thanks for the question regarding "Updation of values in the collection (Nested Table)", version 8.1.6
You Asked
Hi Tom,
   Thanks for the answer for the previous question on random
number generation. Well this time I am facing the problem of
updating the values of the column of the nested table.
      Well, actually I am having one of column in the table as
the nested table in which I want to update the value of that
particular column of the nested table.
       Please tell me how to go about it?
   Hoping for your mail a.s.a.p.

 Regards,
 Farhad.
and we said...
Here is a quick example -- just using sql.  There are other ways
but they depend on what environment you are using.  for example,
i could use a PLSQL variable and update T directly instead of
using THE as I did below...

ops$tkyte@DEV816> create or replace type
  2  myScalarType as object
  3  ( x int,
  4    y int
  5  )
  6  /

Type created.

ops$tkyte@DEV816> create or replace type
  2  myTableType as table of myScalarType
  3  /

Type created.

ops$tkyte@DEV816> create table t
  2  ( a int primary key,
  3    b myTableType
  4  )
  5  nested table b store as b_tab
  6  /

Table created.

ops$tkyte@DEV816> insert into t values
  2  (1, myTableType( myScalarType(1,1), myScalarType(2,2) ));

1 row created.

ops$tkyte@DEV816> insert into t values
  2  (2, myTableType( myScalarType(3,3), myScalarType(4,4) ));

1 row created.

ops$tkyte@DEV816> update
  2     THE ( select t.b from t t where t.a = 1 )
  3     set y = y * 2
  4  /

2 rows updated.

ops$tkyte@DEV816> column b_col format a40
ops$tkyte@DEV816> select t.a as A_col, t.b as B_col
  2    from t t
  3  /

     A_COL B_COL(X, Y)
---------- ----------------------------------------
         1 MYTABLETYPE(MYSCALARTYPE(1, 2), MYSCALAR
           TYPE(2, 4))

         2 MYTABLETYPE(MYSCALARTYPE(3, 3), MYSCALAR
           TYPE(4, 4))
September 17, 2000 Praveen -- Thanks for the question regarding "Questions regarding parse and space and listener", version 8.1.5
You Asked
Hello Sir,
1)I  wanted to know what does the parse in the library cache
really mean, is it something to do with english like sql being
converted to c code via something like yacc or is it something
else.?
2)Even if my listener is up and running ,and i start sqlplus via
a telnet connection on the same unix box on which the oracle
database server is installed,does the sqlplus connection to
oracle go thru the listener using sockets framework on the same
machine/or thru the ipc--unix pipes.
what does local=yes tell using ps-ef|grep local=yes ,that the
sqlplus is going in via unix pipes or is the sockets in use.
3)I have a tablespace of 12 gb for an appln's data.
One time the tables in the tablespace had so much data which
made the high water mark for the tablespace reach 12 gb.then the
data was deleted in the tables by the test deveopers and now oem
storage manager shows us the used space as around 4gb.i tried to
recover the free space by resizing datafiles ,but it doesn't
allow mw saying that the space being asked for is mor than that
can be provided.
Is export/import and truncation the only option left for us.we
even tried the tablespace manager for new oem,which doesn't show
up records ,don't know why .
Please suggest a better method

Thanks a lot
and we said...
1) parsing is the act of taking the string (eg: "SELECT * FROM
EMP") and breaking it down into its component pieces -- figuring
out what they mean -- resolving references (such as EMP is
really SCOTT.EMP) and then developing the plan to answer the
query.

2) if you do not specify a TNS connect string and do not have a
TWO_TASK environment variable set, Oracle will use IPC to talk
to the database.  Your executable (sqlplus for example) will
fork and exec the Oracle process (dedicated server).  These are
the LOCAL=YES processes you see.  They are not using TCP/IP
sockets but they may very well be using socketpairs to perform
IPC.

3) The only ways to reduce a high water mark is to
   - unload and reload (not recommended)
   - alter table TNAME move (new storage options) (my preferred
     method if you must reclaim the space)

You can export the table, drop it or truncate it, and import it.
 that will works.

You can also just "move" the table -- either within the same
tablespace or to a new tablespace.  You can specify new storage
parameters when you do this.  After moving the table you would
have all of its old extents as free extents.  You will need to
rebuild all indexes on this table afterwards.
September 17, 2000 Praveen -- Thanks for the question regarding "HA Oracle", version 8.1.5
You Asked
Where can i get some good reading matter on implementing HA
Oracle and its concepts.

Thanks
Praveen
and we said...
Oracle Parallel Server is our Highly Available configuration.
You can read all about it at:
http://technet.oracle.com/doc/oracle8i_816/paraserv.816/index.htm
start with the concepts guide.  Oracle8i version 8.1.6 added a
"basic high available configuration" which may be of special
interest to you.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:262615352849
for the pointers into the documentation about that feature.
September 17, 2000 Phyllis -- Thanks for the question regarding "DBA SCRIPTS -- where are 10 scripts every dba should have by Kevin Loney", version Oracle 8
You Asked
As per the below quote, which issue of Oracle magazine contains
this article.

"This is the sixth of Kevin Loney's "10 Scripts Every DBA Should
Have." Watch for a complete article on how to use these scripts
in a future issue of Oracle Magazine. There are other valuable
scripts as well, but these ten--covering backup/recovery, space
management, account management, maintenance, and tuning--provide
basic guideposts to start from during your administration
activities. "

Thanks
and we said...
I believe is was the January 1997 issue.  Not 100% sure.  See
http://www.kevinloney.com/
and specifically
http://www.kevinloney.com/freebies.htm
Some of the links on his page are dead -- Oracle Magazine does
not have 1997 and before online anymore, just 98 on up.

update: found them looking for something else
http://www.oracle.com/oramag/code/96index.html
they must have brought them online again...
September 18, 2000 Bjørn Erik -- Thanks for the question regarding "Oracle user", version 8i
You Asked
Is this possible? If yes, how?

I want to have a general oracle user (like "scott") with
password saved in the DAD.
This one is supposed to have access to some levels of the
application.

But when the user enters procedyres that does some not so
general changes etc. to the database, I want him/her to log on
with his/hers username.

Thanks in advance.

Bjørn Erik Pedersen.
and we said...
Yes it is possible -- you need two DADs and you need to grant
more selectively.

You have 2 sets of packages,

o one set should be granted either to PUBLIC or to "Scott"

o the other set should be granted only to a role, a role that
neither PUBLIC not SCOTT has

That role will be granted to the people who are allowed to use
the application.

You will create one DAD mapped to SCOTT/TIGER.  You'll create
another one whereby the password is not stored in the DAD.  The
DAD mapped to scott/tiger will NOT be able to run the special
procedures/packages as they are not granted to scott or public.
In order to run those, the URL must point to the DAD that
requires people to log in.  They will be able to run (or not)
these packages due to the grant.
September 18, 2000 Gediminas -- Thanks for the question regarding "Installing all available PL/SQL packages", version 8.1.6
You Asked
After Oracle 8.1.6 installation I didn't find
dbms_obfuscation_toolkit and
dbms_shared_pool. Later I installed them from
$ORACLE_HOME/rdbms/admin directory. Why doesn't Oracle Installer
install all available PL/SQL packages?
and we said...
Various features are installed on a case by case basis after the
standard install is done.  The DBA would choose to install (or
not) the various components that should be available.
dbms_obfuscation_toolkit, with encryption capabilities -- is one
of those features.  the shared pool package, because of some of
its capabilities is another.

dbms_shared_pool is installed as part of the statspack
(statscusr.sql installs it and other components).

dbms_obfuscation_toolkit is installed via catobtk.sql.
Review & Followup
Rating: 5
Important scripts for developers September 25, 2001
Reviewer: A reader
Is there a document which gives the description of all the scripts available in
the rdbms/admin directory.

Scripts like utldtree.sql are very usefull for the developers, what are the
scripts available in the said directory which are of very good use to the
developers( and what are the scripts which you use from this directory)

Thank you

September 18, 2000 Servet -- Thanks for the question regarding "a complex algorithm", version 3.3
You Asked
Hi Tom,
i need to implement an algoritm with SQL.
i have two tables;
Table1 (has two fields named 'id' and 'Out')
id --- Out
1      120
2       50
3      150
4      200
5      160
6      500
      ----
Sum(out) 1180

Table2  (Has two fields named 'id' and 'in')
id ---  in
1       60
2       75
3       70
       ---
Sum(in) 205

Well, after the subtraction (Sum(out)-Sum(in)=975) i get 975.
What i need is that i want to write a query that returns the
records from table 1 ,which dont overlapped by 975.Below is the
operation thats needed

id --- Out             id---in         id---(out-in)
1      120              1   60          1        0
2       50              2   75          2        0
3      150      -       3   70     =    3      115
4      200                              4      200
5      160                              5      160
6      500                              6      500

as its seen above, sum of the records in table2 is overlapping
the the first (120), second (50) and 35 of the third records  of
table1.So I want to return 115 of the third, 4th,5th,6th of
table1.
I tried many different SQL Staments for that but i couldnt get
the result.
(simply i need to implement something like the below expression
with SQL
 SumOut=Sumout+out
 if sumout>Sumin then
    'And the rest..   )

To me it Seemed impossible with SQL.
Id be very pleased if you help me, if any way to solve this
exists.
Thank you For Your Help....
and we said...
Impossible -- nothing is impossible.

In Oracle8i, release 8.1.6 -- this will be much easier (i'll
show that at the end) using the analytic functions available in
that release.  In 7.3 which you appear to have -- its "doable"
but only for somewhat smallish result sets.  On the above data,
the following works well:

ops$tkyte@ORA8I.WORLD> select * from t1;

 ID XOUT
--- ----
  1  120
  2   50
  3  150
  4  200
  5  160
  6  500

6 rows selected.

ops$tkyte@ORA8I.WORLD> select * from t2;

 ID        XIN
--- ----------
  1         60
  2         75
  3         70

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select id,
  2         xout,
  3         decode( sign(prec_total-sum_xin),
  4                       -1, decode( sign(sum_xout - sum_xin),
  5                                     -1, 0,
  6                                      0, 0,
  7                                      1, sum_xout-sum_xin),
  8                           xout ) out_minus_in,
  9         sum_xout,
 10         sum_xin,
 11         prec_total
 12    from ( select a.id,
 13                  a.xout,
 14                  sum(b.xout) sum_xout,
 15                  sum(decode(b.id,a.id,0,b.xout)) prec_total
 16             from t1 a, t1 b
 17            where a.id >= b.id
 18            group by a.id, a.xout ),
 19         ( select sum(xin) sum_xin
 20             from t2 )
 21  /

 ID XOUT OUT_MINUS_IN   SUM_XOUT    SUM_XIN PREC_TOTAL
--- ---- ------------ ---------- ---------- ----------
  1  120            0        120        205          0
  2   50            0        170        205        120
  3  150          115        320        205        170
  4  200          200        520        205        320
  5  160          160        680        205        520
  6  500          500       1180        205        680

6 rows selected.

It works like this:

o we get the sum(xin) from t2.  This is 205.  It is what we need
to subtract from a running total of sorts on T1.  This will be
joined to every row in the other result set in the from clause.

o we join every row in T1 to every other row in T1 that "comes
before it or is itself" (the non-equi join we do).  I am
assuming that ID is unique here.  We do this to get two extra
numbers -- the sum of all PRECEDING rows and the sum of all
PRECEDING plus current rows.

o when we join these, we have all of the data we need.  Now --
on a row by row basis we have:

  - id
  - xout
  - sum_xin = sum of T2
  - sum_xout = sum all preceding and current row
  - prec_total = sum all preceding rows

The number you want is:

   if PREC_TOTAL < SUM_XIN
   then
       if ( SUM_XOUT <= SUM_XIN )
       then
            return 0  -- this is the case for id = 1, 2
       else
            return SUM_XOUT-SUM_XIN  --this is the case for id=3
       end if
   else
       return xout; -- this is the case for id=4,5,6
   end if;

the decode does that with SIGN....

Again, with a smallish amount of data -- this will be
acceptable.  On a large set, this could be expensive to compute
all of those running totals.

In Oracle8i release 8.1.6 using the new analytic functions -- we
can make this perform much better and the query is a little
easier to understand.  We do not need the non-equi join anymore,
we can sum the preceding rows (a running total) easily.
consider:

ops$tkyte@DEV816> select id,
  2         xout,
  3         decode( sign(prec_total-sum_xin),
  4                       -1, decode( sign(sum_xout - sum_xin),
  5                                     -1, 0,
  6                                      0, 0,
  7                                      1, sum_xout-sum_xin),
  8                           xout ) out_minus_in,
  9         sum_xout,
 10         sum_xin,
 11         prec_total
 12    from ( select id,
 13                  xout,
 14              sum(xout) over (order by id) sum_xout,
 15              sum(xout) over (order by id) - xout prec_total
 16             from t1 ),
 17         (select sum(xin) sum_xin
 18            from t2 )
 19  /

 ID       XOUT OUT_MINUS_IN   SUM_XOUT    SUM_XIN PREC_TOTAL
--- ---------- ------------ ---------- ---------- ----------
  1        120            0        120        205          0
  2         50            0        170        205        120
  3        150          115        320        205        170
  4        200          200        520        205        320
  5        160          160        680        205        520
  6        500          500       1180        205        680

6 rows selected.
September 18, 2000 Seo -- Thanks for the question regarding "Table and index in disk", version 8.1.5
You Asked
An OCP Preparation book I read said : 'put table and index on
separate disks. It reduce contention.'
But, oracle manual said : 'you can put table and index on the
same disk, because process will go sequentially. First,
index is read and then, table is read.'

So, I become confused. Which is right?
and we said...
They both are.

With disks are they are today -- it typically doesn't matter.
We have very large disks with short seeks times and typically
have employed some level of striping.

In the beginning, disks were slow and systems were small.  The
advice was to split index and data onto separate devices so the
single user using the system would have the heads positioned
right in the right place when they wanted to access data.  In a
multi-user system, this is not nearly as relevant.

The put the index and data on separate devices is still good
advice.  It is true that if we are using an index to access a
table -- we are doing single block scattered reads.  It is not
really relevant whether it is on a single disk or 2 disks as the
head will be flying all over the place anyway -- to read the
index and to read the scattered blocks in the table it points to.
September 18, 2000 Seo -- Thanks for the question regarding "Hash operation and it's memory usage", version 8.1.5
You Asked
I leared what hash is in the school, but I can't understand
what hash join is. Could you explain the mechanism occur
in oracle during hash join operation? I also want to know
the memory usage during hash join(in sequential join / parallel
join)
and we said...
In a hash join -- the "keys" you are joining on are hashed and
stored in temporary segments.  We might be building a hash index
on the fly.

Say you issue:

select *
  from emp, dept
 where emp.deptno = dept.deptno
/

And we use a hash join.  It might take the dept table and build
a "hash table" out of it.  Now, we full scan the EMP table and
look for deptno = 10 in the dept table.  We find it in this
temporary space by hashing deptno=10 into an address and get the
data.  So, we build a hash table, hash the join key, and access
it -- completing the join.
September 18, 2000 greeshma -- Thanks for the question regarding "database sequence", version 8.0.6.0.0
You Asked
hi!  tom
thankx for all your help.
i have a trigger on a table,which transfers data to a temp table
when a record is manuplated on the base table.I am passing
timestamp,changetype and sequence number from a sequence
generator.when a batch file is run ,it inserts or updates or
deletes records on the base table.it generates hundereds of
records per second.my problem is when i observe my temp table, i
see certain sequence numbers missing from sequence column
generated by a database sequence generator.
and this is happening to a particular table which generates
thousands of records per minute (by the batch processing) and
not in other tables which have less record generation,i feel
that some records r being missed from inserting into my temp
table.can u explain me, is there any chance to happen this. if
so, why?.
is there a way out for this.
pl. help me.
and we said...
A sequence object is not subject to "rollback" so if you
select'ed a nextval and rolled back -- it will have a gap.

A sequence object is subject to flushing from the shared pool.
If your shared pool is not large enough, it could be getting
flushed at some point and you will lose cached values (by
default we cache 20 entries).  To avoid that you can pin the
sequence.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:46212348053
It is normal for a sequence to have gaps -- you must expect a
sequence to have gaps.  There is only 1 way to generate a gap
free sequence and that is to use a single database table to
generate them (and hence you will serialize all operations --
very very slow).
September 18, 2000 Louise -- Thanks for the question regarding "Export/Import vis SQLLOADER", version 8.0
You Asked
Hi Tom,

I am trying to export data from NT to IBM/OS390.  The NT is
8.1.5 and IBM is 8.0.4.  The exp is run on IBM to use sqlnet
export data from NT.  The export was failed NT table's column
with date format.  The error message is ORA-00904: invalid
column name.  I tried to export same table to UNIX SUN Solaris
Oracle 8.0.5, it was fine.

Someone suggested to use Sqlloader.  I have no idea that SQLLDR
can do an database export or load data out.  Can SQLLDR load
data out to a flat file?
and we said...
Well, you can use a sqlplus script I have for Unix (nt version
as well).  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:386018742619
or
http://osi.oracle.com/~tkyte/flat/index.html
but if you use the 2cnd link -- it'll not preserve the TIME
component of the date unless you alter the date formats as I did
in the first link...

You know, if you can sqlnet to the database from IBM, you can
use the sqlplus copy command to move the data as well (it'll
even create the table if you ask it to).  See
http://osi.oracle.com/~tkyte/Misc/MoveLongs.html
for a quick example and the sqlplus docs for all of the options.
September 18, 2000 MURUGUPANDIYAN -- Thanks for the question regarding "Application error", version DEVELOPER/2000 RELEASE 2.O
You Asked
Dear TOM,

System os : Windows 98. (node)

Server    : Windows NT Release 4.0

Front end : Developer/2000  Release 2.0 for Windows NT and
Windows 95

Back end  : Oracle 7.3.3

One package developed in the above said configuration.   While I
run the package I receive the following  error message occur
rarely.  Please advice me how to solve it.

      F50run32

      This program is performed has an illegal       Close
      operation and will be shutdown.

      If the problem persists,  contact the program
      Vendor.                                        Detail>>

      F50run32 caused on invalid page fault in
      Module F50RCM32.DLL

Regards
Murugupandiyan.M.S.
DBA.
and we said...
The only supported releases of developer on Win98 are:

o D2K 1.3.3 16-bit
o D2K 1.6.1 32-bit
o D2K 2.1 32-bit
o Developer 6.0
o Forms/Reports 6i

D2k 2.0 is explicity not support on that platform (and does not
work).  Microsoft has 5 distinctly different operating
systems:

win95
win98
winME
winNT
win2k

None are the same as the other and while there is a chance an
app that runs on one will run on the other -- its not by any
means assured.
September 18, 2000 Chella -- Thanks for the question regarding "Export data to Flat file", version 8.1.5
You Asked
I have used SQL LOADER to load data from a TXT file into Oracle
table and then I have to an export into a TXT file from the same
table. Wrote a .sql script and stored it in the directory
c:\bsp\EPREC.sql and here is the EPREC.sql file contents.

spool c:\bsp\TransEPOCREC.txt

SELECT TransCode|| ',' ||TransDateDays||','||SUBSTR(ReferenceID,
1,6)||','||
    CustSortCode||','||CustAcNumber||','||(Amount*100)
    FROM tblMailBoxData
    WHERE TransCode = 11 AND (CustAcNumber = '11318624'  OR
CustAcNumber = '60773638' );

spool off

Then I goto the SQL*PLUS prompt and type;

SQL>start @C:\BSP\EPREC.SQL

The command gave an error 'Unable to open file
'C:\BSP\EPREC.SQL'
I have tried various combinations to run this sql start file but
having problems. Then I cams across PL/SQL UTL_FILE package. I
am new to this theme and would appreciate any help about
exporting Oracle data to a flat file. This will be a scheduled
job and can I use the Enterprise Manager to do this work ? Help
and suggestions much appreciated. Thank you in advance.

Chella
and we said...
Well -- first to solve your issue above, you either use:

SQL> start c:\bsp\eprec.sql

OR

SQL> @c:\bsp\eprec.sql

but not START and @ together....

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:68212348056
for how to do this in PLSQL using UTL_FILE in a generic fashion.
 You can use oem to schedule or (my preference) would be to use
DBMS_JOB in the database itself to schedule the job.  In that
fashion the job only runs when the database is actually up...
September 18, 2000 Praveen -- Thanks for the question regarding "HA Oracle for sun", version 8.1.5
You Asked
Hi Tom,
Could you please tell me some good documentation for HA Oracle
from Sun.
Thanks
Praveen
and we said...
Oracle Parallel Server is our Highly Available configuration.
You can read all about it at:
http://technet.oracle.com/doc/oracle8i_816/paraserv.816/index.htm
start with the concepts guide.  Oracle8i version 8.1.6 added a
"basic high available configuration" which may be of special
interest to you.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:262615352849
for the pointers into the documentation about that feature.
September 18, 2000 Guy -- Thanks for the question regarding "Table "real" used space", version All from 7.3.x to 8.1.6
You Asked
How to rapidly find the "real used" space size of a table in a database. Total,
by extents and by blocks.

The purpose maybe for:
.. do i defragmentation or not?
.. or there is enought space in that tablespace to take a copy of this table?
.. and so on ...

Thank's
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
If you need to see the utilized space under the high water mark, there is only
analyze.  Depending on the size of the table "rapidly" may not be achievable.
September 18, 2000 Dusan -- Thanks for the question regarding "Execute procedure with my objects in another schema", version 8.1.6
You Asked
Hi Tom,

Let me outline our scenario:
USER1, USER2, ... USERX schemas with tables and procedures:
USER1
  TABLE1
USER2
  TABLE1
...

USERX
  TABLEX
  PROCEDUREX ( contains TABLE1,TABLEX)

User1, User2, ...  have granted execute on USERX.PROCEDUREX
There is public synonym (and grants) on TABLEX for USER1, USER2,
... schemas

USERX cannot compile PROCEDUREX, because the TABLE1 is not in
his schema. We cannot give public synonym to TABLE1,
because this table (the same table) is in many schemas.

We want USER1, USER2 ... to run USERX.PROCEDUREX - is it somehow
possible?
and we said...
Well, he can compile it but it would have to be bound to one of
USER1.TABLE1 or USER2.TABLE2 and it sounds like you want it to
access either or -- depending on WHO is running the procedure.

If USERX has been granted DIRECT access to the table (via GRANT
SELECT on USER1.TABLE1 to USERX), then USERX can compile a
procedure that accesses that table.  If USERX has the priv to
select from the table via a role -- USERX will not be able to
create a procedure (see
http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
for why).....

In any case -- it sounds like you want the procedure to access
USER1.TABLE1 when user1 runs it and USER2.TABLE1 when user2 runs
it.  If that is the case -- and since you are running Oracle8i
release 8.1.6 -- here are your options:

o Grant userx direct access on both USER1.TABLE1 and
USER2.TABLE1.  Verify this access exists by logging into SQLPlus
and executing:

SQL> set role none;
SQL> desc user1.table1
SQL> desc user2.table2

if that succeeds -- you granted correctly, if not -- you need to
grant directly.  Make that work and go onto the next step.

In the procedure now, instead of coding STATIC sql, you'll use a
ref cursor and dynamic sql.  for example:

declare
   type rc is ref cursor;
   l_cursor rc;
begin
    open l_cursor for
      'select a, b, c from tableX, ' || USER || '.table1
        where .....';

    loop
       fetch l_cursor into ...;
       exit when l_cursor notfound;
       ....
    end loop;
    close l_cursor;
end;

The tablename will be built dynamically at runtime depending on
who is running the procedure.

o OPTION 2: use invokers rights.  USERX will need to create a
"template" object TABLE1 in his schema -- it'll just be an empty
table.  USERX will create the procedure as:

create procedure procedurex
AUTHID CURRENT_USER
as
   ...
begin
   for x in ( select * from userX.tableX, table1 where .. ) loop
      ...
   end loop;
end;
/

In this case - userx will own tablex and an empty table1.  user1
and user2 will NEED a grant on tableX and the procedure will run
with their priveleges at runtime (the need select on
userx.tablex either via a ROLE or a GRANT).  Since this
procedure runs as invoker -- the reference to table1 in the
above query is done with respect to the currently logged in
users schema so it will be user1.table1 or user2.table1
depending on who uses it.
September 18, 2000 saigals -- Thanks for the question regarding "attach sequence to a primary key", version 8.0.6
You Asked
Tom,

How do I attach a sequence to a primary key in a table?

Thanks,
Saigals
and we said...
You use a trigger to do this.  Something like:

create or replace trigger my_trigger
before insert on T for each row
begin
  if ( :new.id is NULL ) then
      select myseq.nextval into :new.id from  dual;
  end if;
end;
September 18, 2000 Andre -- Thanks for the question regarding "Autonomous Transaction", version 8.1.6
You Asked
G´day !

Tom, I´d like you to shed some light on the topic "Autonomous
Transactions". Could you give me an example ? I tried to find
this issue in your archives but all I got was a broken link.

Thanks, mate !!!
and we said...
See
http://osi.oracle.com/~tkyte/autonomous/index.html
it should work (i was just there)
September 18, 2000 Andre -- Thanks for the question regarding "NLS changes in 8i -- NLS_COMP vs NLS_SORT", version 8.1.6
You Asked
Hi Tom,

Would you please explain the changes in NLS in Oracle8i ? I did
not understand the NLS_COMP parameter and its relation to
NLS_SORT. I think the online books are not very clear about
that.

Thanks in advance.
and we said...
Comp is for comparision.
Sort is for sorting (order by).

Comp changes the behavior of <, =, between
Sort changes order by.
September 18, 2000 Tom -- Thanks for the question regarding "Context Server Cartridge", version OAS 4.0.8.1
You Asked
I am trying to do some scoring on CLOB fields using the score
function in the context server cartridge.  I am getting some
weird results.  Here is an example:  I am searching for the word
"Sales" in the clob field and I get the results belowfrom the
score function.  The records were also sorted by the score desc.
 If I could figure out how the score ties into the number of
occurances I can extrapolate back to find the percentage, since
I know the number of search items.

Score         Actual occurances
100           32
100           29
100           33
99            26
99            26
95            24
91            26
91            23
4              1

Here is the actual SQL if it helps.

SELECT distinct applicant_id, keyskills, position_applied_for,
home_phone_no, -1 ks_score, score(2) res_score
FROM   search_candidates_view, all_docs
WHERE( search_candidates_view.applicant_id = all_docs.FKEY_ID(+)
AND all_docs.doc_header is not null) and (
contains(DOC_TEXT,'Sales',2) > 0) and ( 1=1 )  order by
res_score desc

Any help would be appreciated.

Thanks,
Tom Deseamus
and we said...
See
http://technet.oracle.com/doc/oracle8i_816/inter.816/a77063/ascore2.htm#2841
for the algorithm.  It is a function of the number of documents
in the set and other factors.
September 18, 2000 Petroula -- Thanks for the question regarding "Header Files", version 8.1.6.0.0
You Asked
Hello Tom

I am working with external procedures and have a few questions.

1-  In my c program I use my own header file "stpu.h" which
includes macros such as
#define MY_BEGIN_DECLARE_SECTION \
    static void VariableDeclaration() { \
    EXEC SQL BEGIN DECLARE SECTION;\
    long h_sc_code;\
    char h_sc_id[SC_H_ID]

#define MY_END_DECLARE_SECTION \
    EXEC SQL END DECLARE SECTION; }

However my c program does not see this, what precompiler option
do I have to add in order for it to work asside from specifying
the path in the include directory of the precompiler options.

2- In the following procedure

void __declspec(dllexport) SP_I_ORG(OCIExtProcContext *ctx,char
*name,short n_ind,char *parent_id,short p_id_ind,long
type_id,short t_id_ind,short rec_user,short r_us_ind)
    {

     EXEC SQL
INSERT INTO TMT(RANK, PARENT_ID, ELEMENT_ID, ELEMENT_NAME,
TYPE_ID, LEVEL_ID, REC_USER)
SELECT
RTRIM(RANK),:*parent_id:p_ind,:h_uniqueID,:*name:n_ind
,:*type_id:it_id_ind,LEVEL_ID + 1,:*rec_user:r_us_ind
FROM TMT WHERE ELEMENT_ID IS NuLL;

}
I get undeclared identifier errors.
and we said...
1) Due to the way the precompiler works you cannot do that EXEC
SQL statements must be in the source code file itself, not in
headers and not macro.

2) you need to use "parse=full" on the proc command line.  On
NT, it defaults to "parse=none".  With parse=none, you need to
have variables in EXEC SQL BEGIN/END DECLARE...
September 18, 2000 Eli -- Thanks for the question regarding "XML parser", version 8.16
You Asked
HI
In my project we used InerMidia text option, in order to improve
performance we concatenate same search fields to one filed.
for example in the begin the ITEM table was  include the
following fields:

ID             number (20)
TITLE         varchar(30)
CATEGORY         varchar2(30)
LOCATION         varchar2(30)

For the above table stretcher we create TREE interMidia text
index .
And in query time the performance was very bad.
For example :
In order to retrieve ID of Clarion hotel the following contain
query need to  be perform  Agnes demo table:

SELECT id
   FROM item
WHERE CONTAINS(title,’ Clarion’) >0
    AND CONTAINS(category,’hotel’)>0;

So
we create new ITEM table like the following:

ID number
SEARCH varchar2(100)

The below is view of 1 recored existing in the new ITEM table.

ID  SEARCH
1   < title >Clarion Hotel</ title >< cat >Hotels</cat>< loc
>DallasTXUSO</ loc >

And now the data of the tree search field  are in the SEARCH
column and the data was separate by XML tags which are section
groups in the interMidia text index preference.

The following query will return the same result and better
performance:

SELECT id
   FROM demo
WHERE CONTAINS(SEARCH   ,’ clarion WITHIN my_title  and hotel
WITHIN my_cat’) >0;

I hop you understand what we do and now my quetion is:
The CONTAINS operator return Boolean result ,I want to know if
there is a option to retrieve the data locate in the SEARCH
column when I perform the contain query .
and we said...
Contains does not return booleans, it returns the score of the
hit (a number).  In any case -- the  SEARCH column is definitely
available to you -- just

select id, search from T where contains( search, .... ) > 0

It is a column in the table -- it is there for the selecting..

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:440419921146
for an alternative solution to actually storing the data in one
big field as well (you can index a function in interMedia, the
function can return the marked up text and you could store the
real stuff in the three original columns).
September 18, 2000 Phillip -- Thanks for the question regarding "Returning Arrays From JAVA Stored Function", version 8.1.6
You Asked
In response to a question in comp.databases.oracle.server
(which I would post to if my ISP's news server wasn't busted)
you responded (in part)

 Another way is to use a result set and "select * from
 plsql_function". It could look like this:

 ops$tkyte@8i> create or replace type myTableType as table of
 varchar2 (64);
   2  /

 Type created.

 ops$tkyte@8i>
 ops$tkyte@8i>
 ops$tkyte@8i> create or replace
   2  function demo_proc2( p_rows_to_make_up in number )
   3  return myTableType
   4  as
   5      l_data            myTableType := myTableType();
   6  begin
   7      for i in 1 .. p_rows_to_make_up
   8      loop
   9          l_data.extend;
 10          l_data(i) := 'Made up row ' || i;
 11      end loop;
 12      return l_data;
 13  end;
 14  /

 Function created.

 ops$tkyte@8i>
 ops$tkyte@8i> select *
   2    from the ( select cast( demo_proc2(5) as mytableType )
   3                from dual );

 COLUMN_VALUE

----------------------------------------------------------------
 Made up row 1
 Made up row 2
 Made up row 3
 Made up row 4
        [Image]
 Made up row 5

 So, your JDBC program would just run the query to get the data.
 If the function "demo_proc2" cannot be called from SQL for
 whatever reason (eg: it calls an impure function in another
piece
 of code or it itself tries to modify the database via an insert
 or whatever), you'll just make a package like:

 ops$tkyte@8i> create or replace package my_pkg
   2  as
   3
   4          procedure Make_up_the_data( p_rows_to_make_up in
 number );   5          function Get_The_Data return
myTableType;
   6  end;
   7  /

 Package created.

 ops$tkyte@8i>
 ops$tkyte@8i> create or replace package body my_pkg
   2  as
   3
   4  g_data myTableType;
   5
   6  procedure Make_up_the_data( p_rows_to_make_up in number )
   7  as
   8  begin
   9          g_data := myTableType();
 10      for i in 1 .. p_rows_to_make_up
 11      loop
 12          g_data.extend;
 13          g_data(i) := 'Made up row ' || i;
 14      end loop;
 15  end;
 16
 17
 18  function get_the_data return myTableType
 19  is
 20  begin
 21          return g_data;
 22  end;
 23
 24  end;
 25  /

 Package body created.

 ops$tkyte@8i>
 ops$tkyte@8i> exec my_pkg.make_up_the_data( 3 );

 PL/SQL procedure successfully completed.

 ops$tkyte@8i>
 ops$tkyte@8i> select *
   2    from the ( select cast( my_pkg.get_the_data as
mytableType
 )   3                from dual );

 COLUMN_VALUE

----------------------------------------------------------------
 Made up row 1
 Made up row 2
 Made up row 3

 And you'll call the procedure followed by a query to get the
 data...

I have tried this, and it all works beautifully.  I would
like to make this a standard of sorts.  _However_, I would
also want the choice to write the stored function in
java.  When I try that, the call from SQL*Plus fails
with a variety of errors.  I think I am either using
the wrong wrapper for the function, or defining the
wrong return type in the java class.  So, my question
is, how would the above look if the stored function was
written in java?
and we said...
Here is a quick and dirty example for you.  A java function to
return a list of files in a directory as an array suitable for
SELECT'ing.  Notice I use an easier (8.1) syntax for casting the
table as well.  Note that the owner of this java procedure must
have javasyspriv granted to them and that is extremely
powerful so be careful with that one. It is needed to read the
file system as we are:

ops$tkyte@DEV816> create or replace type fileList as table of
                            varchar2(255)
  2  /

Type created.

ops$tkyte@DEV816> create or replace
  2     and compile java source named "DirList"
  3  as
  4  import java.io.*;
  5  import java.sql.*;
  6  import oracle.sql.*;
  7  import oracle.jdbc.driver.*;
  8
  9  public class DirList
 10  {
 11  public static ARRAY getList(String directory)
 12                               throws SQLException
 13  {
 14      File path = new File( directory );
 15
 16      Connection conn =
 17            new OracleDriver().defaultConnection();
 18      ArrayDescriptor descriptor =
 19        ArrayDescriptor.createDescriptor( "FILELIST", conn );
 20      return new ARRAY( descriptor, conn, path.list() );
 21  }
 22
 23  }
 24  /

Java created.

ops$tkyte@DEV816> create or replace
  2  function get_dir_list( p_directory in varchar2 )
  3    return fileList
  4  as language java
  5  name 'DirList.getList( java.lang.String )
  6        return oracle.sql.ARRAY.ARRAY';
  7  /

Function created.

ops$tkyte@DEV816> select *
  2    from TABLE ( cast (get_dir_list( '/tmp' ) as fileList) );

COLUMN_VALUE
----------------------------------
lost+found
.rpc_door
ps_data
.pcmcia
.X11-unix
.X11-pipe
page.html
owinst.log
wwvcb.log
xxx.dat
mpAwaWAs
mp3saOFs
wwvcbus.log
sbddl.log
help.log
helpctxs.log
helprela.log
ups_data
helpindx.log
wwvsbus.ctl
tkyte.dbg
1.txt
exec29047
mpljaa3p
2.txt
3.txt
mpwUaGCo
4.txt
5.txt
q_invalid.sql
xxtmpxx.sql
mm.sql
xxx
xxx.sql
mpUQaq6l
test_tbs.dbf
data.dat
afiedt.buf
a.sql
mpYxaizE
mpNcaGOW
mpzqayTW
mp1ra4wY
mp77aqXl
.removable

45 rows selected.
September 19, 2000 James -- Thanks for the question regarding "Appropriate option to work with Microsoft Cluster Server", version 7.3.4
You Asked
Dear Tom,
  One of our client is planning to use Microsoft Cluster Server
which is a part of NT Server 4.0 Enterprise Edition.  In order
to achieve the availability of database.  Which options like
Standby database, Replication, Parallel Server is most
appropriate for this configuration?

  The installed Oracle database on the site is v7.3.4 for NT.
Client is using D2K 1.5 to connect ot the server.

Thanks and regards
James
and we said...
See
http://www.oracle.com/nt/clusters/failsafe/
for 7.3.4.  Later releases of Oracle support OPS on this
configuration as well.

This is what would take advantage of the cluster.

Replication, standby database -- they do not need or want the
cluster.  They want separate, network connected computers.
September 19, 2000 -- Thanks for the question regarding "SQL> --> system@live.world>", version 8.0.4 , 3.3.4
You Asked
Hi Tom,

How can i display alias- tnsname (not instance name) in SQL
prompt of Sql*Plus ?

ie: SQL> --> system@live.world> ?

Thanks Tom

trandt@yahoo.
and we said...
By the time you get to the server -- the tnsnames alias (which
can be specific to your machine) is gone.  Its been turned into
a big long tns connect string.  That simple little name that you
made up on your client is not sent along anywhere.  Therefore it
is not visible.

What I like to do is ALWAYS use a tns alias that is exactly the
same as the GLOBAL_NAME of the database.  This makes sense for
many reasons and since the global name should be made globally
unique, won't overlap.  Now I can have a login.sql that has:

column global_name new_value gname
set termout off
select lower(user) || '@' || global_name from global_name;
set termout on
set sqlprompt '&gname> '
Review & Followup
Rating: 3
July 02, 2002
Reviewer: A reader

September 19, 2000 Kenneth -- Thanks for the question regarding "jobs getting delayed , log_buffer", version 8.0.5
You Asked
Dear Tom,

Thanks for all the previous help which you have rendered.

I have some few more strange queries.

1. I have submited 10 jobs  which are placed relatively a good
time distance so that not more that 3 jobs are overlapping.
I have 5 SNPs configured.  job_queue_process = 5 ,
job_queue_interval = 60
One observation I see is that my  jobs configured to start at
09:00:00 am today with an interval of 24 hours will start
tommorrow at 09:00:12 am tomorrow. this happens for all jobs.
they start after an interval of 24 hrs and 10-12secs the next
time. Hence my  I have to reset my jobs every week.

moreover the total_time displayed in db_jobs for one of my jobs
is 57363 seconds . does this mean that this jobs is taking 956
mins ( 15 hours)
If this is true then for most part of the day my
dbA_jobs_running would have showed some records which actually
isn't

Are there are furter settings that I must make so that jobs
start at correct time and not of a delay of 10-12 secs.

2. My log_buffer in the init.ora is 16384 which is 16K. But show
sga shows
log_buffer 524288 ( 512K ) . If I set log_buffer in init.ora to
525312 (513 K)  then then show sqa shows this correct result but
for any value below 512K ( in init.ora ) it takes the value 512K
by default .

any Idea why this is always taking a default value

Kenneth
and we said...
The job "sliding" like that is a normal side effect of the way
the job queues work.  The NEXT_DATE is computed right before the
job runs -- you are probably just using:

   sysdate+1

as the next date.  To get something scheduled at a fixed time of
the day, you should always use an absolute, not a relative date.
Your next should be:

  trunc(sysdate)+1+9/24

That'll always set next to 9am the next day -- regardless of
when the job happens to be run (eg: if a job was to get stuck
and some other job wasn't able to be run until 11am today -- the
NEXT would still evaluate to 9am tomorrow).  Typically -- you
always want to use an absolute calculation like that with the
job queues to avoid the "slide" -- unless its a job that should
happen every 5 minutes or so.

The total time is a cumulative counter.  The value of 15 hours
shows we've spent 15 hours TOTAL over the life of this job --
running it.

The log_buffer parameter can be set smaller than 512K but
if it is less than a port-specific value then it is increased to
this value. The default minimum is 512K but this can be changed
on a platform basis dependant upon what is felt to be the most
optimum value for the given port.  That value is compiled into
Oracle and cannot be changed.  On your platform -- it must be
512k.
September 19, 2000 Tamas -- Thanks for the question regarding "PL/SQL package ", version 8.0.x and 8i
You Asked
Hi Tom,

Oracle encripts the PL/SQL packages it supplies with the
database. I would like to do the same with my packages, not for
copyright reasons, but to make code modification for our users
impossible.

Can this be done? Does it work for Java too?

TIA,

Tamas Szecsy
Geometria GIS Systems House Ltd.
and we said...
You would use the tool "wrap" to do this.  See the PLSQL guide,
it is documented.

For Java, you would deliver the class files only -- not the
.java files.  There is no need for wrap in this case.  You would
compile the java code and load the class files into the
database.
September 19, 2000 Chris -- Thanks for the question regarding "blocks in use by a table", version 7.3.4.5.0
You Asked
I have been using the query:

SELECT
  COUNT (DISTINCT SUBSTR(ROWIDTOCHAR(rowid), 1, 8))
FROM
  < table_name >

to work out how many blocks contain rows in certain tables in a 7.3.4 database.
When I run this query for one particular table (transaction_header) I get back
2579. However, if I create a copy of transaction_header (different name
obviously but identical ddl and storage clause) and populate it from
transaction_header and run the query to find out how many blocks are used in the
table, I get 2047, can you explain this ?.

Thanks in anticipation of your answer
Chris Adkin
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
for how to really get this (quickly).

The problem with your approach above is that it only counts blocks with HEAD
rowid pieces on them.  I cannot tell you if EITHER number is even remotely
accurate above.  If you have a 2k blocksize for example and your rows are 4k --
each row will consume 2 blocks but its rowid will only tell you about 1 of them.
 Additionally -- if rows migrate (they don't fit on the block anymore), you will
only see the block they USED to be on, not the one they are on now.

Counting blocks via rowids just doesn't work.  In your case above, by rebuilding
the table you optimized our use of space (you had inserted/updated/deleted over
time leaving holes here and there that we would eventually reuse but hadn't
yet).  By creating the table you cleaned all of that that.

You cannot count rowids to count blocks.  There is no relationship between the
two other then the rowid points to where the row begins.
September 19, 2000 KK -- Thanks for the question regarding "Data migration from 7.3.4 to 8.1.6", version 8.1.6
You Asked
I would like to export full database from an Oracle database
7.3.4 by using system account.  Can I import the whole dump
file into the 8.1.6 database including the system tables?

Will the system tables in 8.1.6 be overrided by those in 7.3.4?
and we said...
SYSTEM doesn't really own any tables outside of some queue
tables -- and these will be taken care of by export.

SYS -- no sys objects are exported.  They are all filled in via
DDL.  The act of issuing a create table populates the tables --
the tables themselves will not be exported.

You can take a full export from 7.3 and import it into 8.1.  See
the server migration guide for the steps.

It is not that the system tables are overwritten -- rather --
the act of running IMP and letting it execute DDL will fill them
in.
September 19, 2000 Iceymole -- Thanks for the question regarding "Creating foreign Key..", version 7.3
You Asked
Hi!

I  need to create a foreign key in schema (X) which references a
constratint in a different schema(Y). The schema(X) has created
a synonym to that table in (Y) and has got select, update,
delete and insert privileges on the table.

When I try to create the synonym it tells me

ORA-01031: insufficient privileges

What other privileges is required for (X) to create the foreign
key.

Cheers.
Iceymole.
and we said...
grant references on T to USERNAME;

They need the references grant...
Review & Followup
Rating: 5
April 08, 2002
Reviewer: A reader

September 19, 2000 santosh -- Thanks for the question regarding "Select statement", version 8.1.5
You Asked
Hi tom
i  have a table(Y) with 10 columns and i want to write a select
statement so that it starts with a particular string say "XXX"
followed by rest of the 10 columns of that table(Y).
how could i do that.
Th most obvious answer semed to be
writing
select 'XXX',col1,col2,col3......col10 from Y;

but i want to skip selecting col1,col2,etc and use * to get the
SQL executted. is there any way i could do that.

wat i intend to do is somethin like

select 'XXX',* from Y;
Thanks
and we said...
select 'xxx', y.* from y;

will do it.  in fact, you can do things like:

select 'xxx', y.*, z.foo from y, z where y.id = z.id;
September 19, 2000 Christophe -- Thanks for the question regarding "concurrent users and init.ora", version 8.1.6
You Asked
Which parameters in init.ora should we change when the average
number of concurrent users increases ?

Thanks !
and we said...
processes, sessions and transactions are the major ones to be
concerned with.  Processes will drive sessions will drive
transactions.

if you are on unix, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:454420165038
for OS related stuff as well.
September 19, 2000 Sateesh -- Thanks for the question regarding "How to access User defined arrays from out side pl/sql environment.", version 8.1.5
You Asked
Hi ,

    A pl/sql stored procedure returns an array of values into
user defined array's.
The array has been created using the following statement.

CREATE OR REPLACE TYPE typ_number AS TABLE OF NUMBER(17,4);

The procdure retuns the above type as an output.
How to access the above variable from other than pl/sql
encironment. WE tried it in Delphi, VB but was invain.
Is there any other way that a procedure can return an array and
can easily be used in any other environment.

Thanks & Regards
Sateesh
and we said...
Only if the client supports it.  Using Java - yes, using C+oci,
yes, using Pro*C, yes....  Using delphi and VB, -- I don't think
so but would not be the right person to ask as I do not use
those tools.

One thing that will work in all clients is to use SQL.  Select *
from (f(x)) where f(x) is your plsql function.  Consider:

ops$tkyte@DEV816> create or replace type myTableType as table of
number;
  2  /

Type created.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> create or replace function getMyTableType
return myTableType
  2  as
  3          l_x     myTableType :=
  4                  myTableType( 1, 2, 3, 4, 5, 6, 7, 8, 9 );
  5  begin
  6          return l_x;
  7  end;
  8  /

Function created.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> select a.column_value  val
  2    from THE ( select cast( getMyTableType() as mytableType )
  3                             from dual ) a
  4  /

       VAL
----------
         1
         2
         3
         4
         5
         6
         7
         8
         9

9 rows selected.
September 19, 2000 Richard -- Thanks for the question regarding "primary key datatype", version 8.1.6
You Asked
Hi!

If I have a choice between having a primary key on a table of
char(25) or number(38), which should I choose? What are the
strengths and weaknesses of each choice?

Does a 38 digit number require the use of "big" integer
libraries? Is it faster to maintain an index of numbers than
char? When comparing char, does the database server need to go
through language support algorithms that are avoided by using a
number?

TIA

Richard
and we said...
I would never use a CHAR(25) for anything -- chars are simply
VARCHAR2's that are ALWAYS blank padded to the maximum length.
When you try to compare them -- you have to blank pad stuff.
When you store them -- they consume a fixed amount of storage.

The difference between a varchar (or char) and a number for
comparisions is neglible -- except in 2 special cases below.
Both types are stored in a binary format that allows for fast
sorting and comparsions (all done in binary).  All Oracle
numbers, regardless of the precision and scale are stored in a
device independent format.  They are never stored in native 4
byte ints.  You need not use any special libraries with them --
we use the Oracle libraries on them. See the server concepts
guide for info on exactly how they are stored.

All that aside - a varchar2(25) and a number field will consume
virtually the same amount of space as a number is really like a
varchar2(22) itself.

So, to answer the question -- here it really won't matter.  They
will be about the same.  If you use a CHAR, the number will
always take less space so I would vote for the number in that
case.  If you use varchar -- won't really matter that much.

The only times a number will be faster for sure is if you set
NLS_SORT or NLS_COMP which will prevent us from using a binary
comparision on a string.  This setting does not affect a number
since a number is a number is a number in any language.
September 19, 2000 brenda -- Thanks for the question regarding "reclaim space in blob", version 8.1.5
You Asked
My table looks like:

mcparts.mc_comment
 Name                            Null?    Type
 ------------------------------- -------- ----
 PC                                       NUMBER(4)
 NOTEDATE                                 DATE
 AUTHOR                                   CHAR(5)
 COMTYPE                         NOT NULL CHAR(1)
 COMMENTS                                 VARCHAR2(1200)
 SEQENG                          NOT NULL NUMBER
 SEQCOM                          NOT NULL NUMBER
 SEQPART                                  NUMBER
 PART_IMAGE                               BLOB

The Blob column is stored in a separate tablespace.   10M was allocated and it
was consumed in no time.   Found out that the photo files were being loaded in
the wrong format.  The were deleted and reloaded with the correct format.   The
extents are showing all allocated but are only 2% full of data.   Is there a way
that I can reclaim this space easily?    My plan was:

grab the photos from the database and store
drop the column
drop the tablespace (of the blob)
add the tablespace back
add the column
reload the photos

Is there an easier way?

Thanks in advance if you have the answer!
and we said...
The only way to get back data segment extents is to give them totally up.  Your
approach is sound and easier then it sounds.

Create table temp as
select rowid rid, part_image from T;

alter table t drop column part_image;

alter table t add column part_image blob ....;

update t set part_image = (select part_image from temp
                           where rid = t.rowid );
September 20, 2000 subirkumar -- Thanks for the question regarding "Portability of diagrams generated from designer", version designer6
You Asked
How I can view a diagram generated in designer (say data flow
diagram) without using the designer tool. If I print the diagram
to a file it generates a .prn file . Which I could not open.
and we said...
You can display an ERD is a document in two ways as far as I
know:

   o embedded as an OLE2 object
   o pasted as a picture

To Embed as an OLE2 object:

o Select your diagram in the Entity Relationship Diagrammer
o Select Edit & Copy (or Ctrl+C)
o Open Microsoft Word
o Select Edit & Paste Special (or Ctrl+V)
o Select Entity Relationship Diagram Object from the dialog list

  and click OK.

Note: Ctrl+V won't display this dialog.

To paste as a picture:

o Select your diagram in the Entity Relationship Diagrammer
o Select Edit & Copy (or Ctrl+C)
o Open Microsoft Word
o Select Edit & Paste Special (do not use Ctrl+V)
o Select Picture from the dialog list, and click OK.

You can then resize the (sometimes tiny) diagram by dragging a
corner drag bar to maintain the aspect ratio of the diagram.
September 20, 2000 wallacel -- Thanks for the question regarding "character set", version 8.1.6
You Asked
Tom:

I have a database which isUS7ASCII, now i need to change the
character set to UTF8,
I follow the instruct of oracle8i national language support
guide
page 3-19, but it don't work for me.

what i did is:
1.SQL>shutdown
2.SQL>startup mount
3.SQL>alter system enable restricted session;
4.SQL>alter system set job_queue_processes=0;
5.SQL>alter database open;
everything goes fine so far, however when i go to next one.
6.SQL>alter database character set UTF8;
it give me the following error message:
RROR at line 1:
ORA-01679: database must be mounted EXCLUSIVE and not open to
activate

if i skip the step 5, it is the same.

can you tell me what's wrong?

>>>>Are you using OPS? If so, setting parallel_server=false will
work.
no, i didn't use OPS

>>>If there is any other session going on -- it'll fail as well
(other people with
restricted session)?

no other session going on.
==========================================================
==========================================================
Tom:
before I get your last email, I make a cold backup of my
database
and then reinstall Oracle8i, after that i restore my database
back and try again, everything is OK.
But I still don't know what's going on there, for that database,
because it is for test purpose, I am the only user, i installed
Oracle 8i, Oracle application server, and Portal-to-go on it,
do you believe it is because of OAS or PTG?
I shutdown and restart it several times , so i am pretty sure
there are no other session going on.

Thanks,

Regards,
and we said...
Not sure.  both OAS and PTG will attempt to connect to the
database so if they were running -- there is a very good chance
that they were attempting to log in and had started a dedicated
server.

Glad to here it is fixed now however.


Subject | Article | Last Updated (East coast time)
Client GUI connections -- dead client detection | article only | Sep 23, 2000 11:58 am
Source Code | article only | Sep 24, 2000 09:15 am
Using External BFILEs | article only | Sep 24, 2000 10:36 am
Converting long int to Date | article only | Sep 24, 2000 03:09 pm
Oracle Server on Windows NT | article only | Sep 25, 2000 07:52 am
Security | article only | Sep 25, 2000 07:55 am
Using a Non-Primary key to enforce relational integrity | article only | Sep 25, 2000 07:57 am
Logical Backup Query | article only | Sep 25, 2000 08:03 am
DATE MATCHING | article only | Sep 25, 2000 08:09 am
storage size when creating new table | article only | Sep 25, 2000 08:54 am
OWA_COOKIE.SEND | article only | Sep 25, 2000 11:01 am
Function Based Indexes | article only | Sep 25, 2000 11:38 am
SQL utility to work out percentages | article only | Sep 25, 2000 01:23 pm
UID | article only | Sep 25, 2000 01:25 pm
joins with different datatype makes poor performance | article only | Sep 25, 2000 03:22 pm
The new RESIZE feature to expand datafiles | article only | Sep 25, 2000 03:27 pm
inspdver | article only | Sep 25, 2000 05:13 pm
several question | article only | Sep 25, 2000 07:57 pm
Opening html file from forms 6 menu | article only | Sep 26, 2000 07:43 am
Loading Data by Using Oracle Forms | article only | Sep 26, 2000 07:46 am
Unselect item of type textbox | article only | Sep 26, 2000 08:15 am
Incremental Export-import | article only | Sep 26, 2000 10:56 am
Hex to Number | article only | Sep 26, 2000 11:26 am
Probl;em with package with record set on 8.0.6 which was ok on 8.1.5 | article only | Sep 26, 2000 11:42 am
q: long data type | article only | Sep 26, 2000 11:54 am
q: table storage requirement | article only | Sep 26, 2000 11:57 am
Indexes | article only | Sep 26, 2000 12:29 pm
Indexing a bi-temporal table | article only | Sep 26, 2000 12:50 pm
Compiling PL/SQL program units | article only | Sep 26, 2000 01:09 pm
DBMS_JOB() + SNAPSHOTS | article only | Sep 26, 2000 01:34 pm
detect create view error | article only | Sep 26, 2000 01:35 pm
Row counts with Ref cursors | article only | Sep 26, 2000 04:35 pm
tables in a database | article only | Sep 26, 2000 05:38 pm
EXPORT of Oracle 8.1.6 Spatial Option - MDSYS objects - How? | article only | Sep 26, 2000 08:46 pm
combine two file | article only | Sep 26, 2000 08:50 pm
PROCEDURE FOR UPDATE | article only | Sep 27, 2000 07:40 am
Date Calculation | article only | Sep 27, 2000 07:46 am
Deleting from all tables | article only | Sep 27, 2000 07:54 am
Executables from Dev 6i forms | article only | Sep 27, 2000 08:04 am
Restricting CPU/Memory usage by User | article only | Sep 27, 2000 08:08 am
Delete Columns in a Table | article only | Sep 27, 2000 08:34 am
OAS Security | article only | Sep 27, 2000 08:45 am
Owa_sylk utility | article only | Sep 27, 2000 03:59 pm
Basics of Orapwd utility | article only | Sep 28, 2000 07:46 am
v$session | article only | Sep 28, 2000 07:48 am
triggers | article only | Sep 28, 2000 08:27 am
How to use a variable tablename in update clause . | article only | Sep 28, 2000 09:38 am
CRASH RECOVERY IN ORACLE8I PARALLEL SERVER | article only | Sep 28, 2000 10:56 am
Display 'A' from Sql | article only | Sep 28, 2000 01:45 pm
Cron Jobs in Windows NT envrioment | article only | Sep 28, 2000 01:58 pm
Performance | article only | Sep 28, 2000 02:36 pm
Links in a chase chain | article only | Sep 28, 2000 02:58 pm
pro*c samples on redhat 6.1 won't compile | article only | Sep 28, 2000 03:26 pm
chat using oracle | article only | Sep 29, 2000 08:04 am
Migrating the database | article only | Sep 29, 2000 08:18 am
tables its usage | article only | Sep 29, 2000 08:25 am
How can I schedule(JOB) sqlplus Statement | article only | Sep 29, 2000 09:02 am
Arrays in Oracle 8.0.5 / Mutating table error | article only | Sep 29, 2000 09:09 am
Character sets | article only | Sep 29, 2000 10:02 am
Determining the row locked ina table | article only | Sep 29, 2000 11:55 am
Executing a Procedure from PL/SQL Dynamically | article only | Sep 29, 2000 11:58 am
Char to Varchar2 Conversion | article only | Sep 29, 2000 11:59 am
q: sqlloader and clob question | article only | Sep 29, 2000 05:36 pm
row(s) 1 - 63 of 63
September 23, 2000 Ron -- Thanks for the question regarding "Client GUI connections -- dead client detection", version Oracle 7.3.4
You Asked
I have been asked to give a count of users currently connect to
the Oracle Applications system.  We are using both character
based (telnet) and GUI clients.  I can show the correct number
of connections for the telnet sessions, even when they closed
the session with out logging off properly thru v$session but
when it comes to the GUI side I am having problems.  If the user
logs off correctly, then all is well, but if they "X" the
windows instead of doing it the right way, the connection
remains and my counts are all wrong.  What am I missing?
and we said...
You can enable dead client detection to clean these sessions up.
 As far as Oracle is concerned -- they are still alive, still
connected, still going.  TCP/IP does not notify anyone when the
client abruptly disappears.

See
http://technet.oracle.com/doc/network23x/NWUS233/apa.htm#deadconn
for details for 7.3.
....
September 24, 2000 Radha -- Thanks for the question regarding "Source Code", version Ver. 7.x & 8.x
You Asked
I have earlier wrapped a procedure and executed.  Now I want to
get the source code but its in wrapped form in the database
dictionary.  How go I get it back to the normal readable form as
the actual source code file has been lost in the disk crash.

Please help me out.

Regards.
and we said...
sorry -- if we could unwrap wrapped code -- it would defeat the
purpose.  Wrapped code is like compiled object code, it cannot
be reversed back into its original format.  I am not aware of
any tools to decompile wrapped code.
September 24, 2000 Geeta -- Thanks for the question regarding "Using External BFILEs ", version 8.1.6
You Asked
Hi Tom,
Need Your Help Here...
The query is i want to use external bfiles kept at web server or
client machine.

as far as i have understood bfile lob is that i can use them
after getting a bfile locator, and that can be return by
bfilename function, but for which the directory alias that is
referred should be on the server where the database is there or
rather where the oracle user has atleast read only rights.

My requirement is that bfiles are not going to get stored in
database but just being referred in the application and that to
ishouldbe able to use them if they are on the client machine or
from where the application is running .

Is it possible to use a bfile which is not in the os dir of the
database server in packages or using java but being kept in a
harddisk of client machine or where the application is running.
If yes,how pls let me know ???
Pls let me know.
Thanks and Regards,
Geeta
and we said...
The BFILE is read by the server processes -- if the server
processes (on the machine where the database is located) cannot
access the file system containing the files -- it will not be
able to read them.

Only if the webserver or client file systems are MOUNTED to the
server will you be able to use a BFILE.  Otherwise, the access
to the file is limited to a process running on the client
machine (namely -- your program).  Your program would read these
files using normal OS file IO.

So, if the files are on the client and the client filesystems
are not available to be read by the server -- this will not
work, your program running on the client will be responsible for
reading the file.
September 24, 2000 Nishat -- Thanks for the question regarding "Converting long int to Date", version 2.3.4.0.0
You Asked
Is there any way I can convert a long integer to Oracle date ???

I have a number value ( say 86400 , number of seconds) and wanna
put this number into a column which is of type date so that the
said column of the table will hold the date corrosponding to the
first day from the base date. I Also wanna know whtaz the base
date, if any , of oracle database...is it 00:00:00 of 1st JAN ,
1970 ???

Is there any way, I can use to_date func. or any other func. to
convert this number into date ???

Thanxs.
and we said...
See
http://osi.oracle.com/~tkyte/Misc/CTime.html
for how to do this.

there is no "base date" in Oracle.  We store dates in a 7 byte
format:

1- century
2- year
3- month
4- day
5- hour
6- minute
7- second
September 25, 2000 Bhavesh -- Thanks for the question regarding "Oracle Server on Windows NT", version 8.1.5
You Asked
Hi Tom,
       One of my colleagues argues that we can install Oracle
server with multiple instances on a Windows NT workstation but I
am bit skeptical on this issue. Can you throw some light if this
can be done or not.
Thanking you in anticipation.
Regards

Bhavesh
and we said...
First a definition:

an instance is a set of processes and an SGA.

a database is a set of files (data, redo, control).

A database may be mounted and opened by many instances of Oracle
simultaneously -- this is known as Oracle Parallel Server.  Each
instance will be on a different node (separate physical
computer) in a cluster.  The database is accessible to each
node.

So, you can have >1 instance open the same database on NT but
you need more then 1 computer to do that.

You can also have >1 isntance on a single NT machine -- each
instance on the same machine will mount and open a database
separate from every other instance on that machine.  So yes, it
is possible to have >1 instance on an NT machine -- as long as
each instance has its own database.
September 25, 2000 wisnu -- Thanks for the question regarding "Security", version version 8.1.5
You Asked
Dear Mr Tom,

First Of All, I am very sorry for disturbing Your time.
I have a problem. I would like to explain you about that :

I have two database. One is in node, and the other is in server.
Each of database connected by remote via internet.

My question is " What kind of the best safety security for
handling this connection (my oracle is version 8.1.5) ? (exp :
RSA,DES,PGP, or SSL , they are for my point of view) or Is there
anything else for safety security ?

Sir,
Once again, Thanks very much for help

Respectifully yours,
-Wisnu-
and we said...
It will totally dependent on your requirements. See
http://www.oracle.com/ip/deploy/database/8i/index.html?advsec.html
for starters.
September 25, 2000 Tet Cheng -- Thanks for the question regarding "Using a Non-Primary key to enforce relational integrity", version 7.2/7.3 and 8
You Asked
Hi Tom,

I have a table in which I want a non-primary key column to be
the parent of a referential integrity constraint.  I have tried
implementing a unique index on this column but it does not work.
 Is there any way to do this at all?

Thanks a lot,

Tet Cheng
and we said...
The parent key in a foreign key relationship must either be:

o a primary key.
o a unique constraint (different from a unique index).

To refer to a non primary key column(s) in a foreign key
relationship, you need to:

  alter table parent_table add constraint parent_unqiue
    unique( a, b, c );

Then, you can use (a,b,c) as a foreign key in another table.  If
there exists a unique index on (a,b,c) already, the unique
constraint will just "take over" that index -- you'll not have
to create another one.
September 25, 2000 Rajesh -- Thanks for the question regarding "Logical Backup Query", version 8.0.6
You Asked
Dear TOM

I would like to know whether the Logical (Import/Export) Backup
of the 8.0.6 Database can be successfully imported to 8.0.5
Database considering the the same Operating system on both the
machines where 8.0.5 is running and 8.0.6 will be installed.

Thanks in advance

Best regards

Rajesh R
Tech Support Engineer
Aspect Development India
Bangalore INDIA
and we said...
export and import are backwards compatible.  What that means is
that IMP can read and use a file from an earlier release of EXP
-- but it cannot in general read and use a file from a LATER
release of EXP.

So, if the export of the 8.0.6 database was done via the 8.0.6
export tool -- in general, it will NOT be the case that the
8.0.5 import tool can read it.  I know for a fact that if you
export from 8.1.6, 8.1.5 cannot read the dmp file at all (file
format changed between releases).  Another issue is that there
will be objects in the new release that simply did not exists in
the earlier versions and that will break the import.

You should use the 8.0.5 export tool over Net8 to the 8.0.6
database to create the export file.  Then, both 8.0.5 and 8.0.6
will be able to use it.  Note however that if there are any
features/functions of 8.0.6 that are not available in 8.0.5 --
the 8.0.5 export tool will not export it.
September 25, 2000 malik -- Thanks for the question regarding "DATE MATCHING", version version 3.3
You Asked
dear sir,

i have tried my best to run this query but it always
unsuccessful by giving a message

no rows selected.

the query is

select end_date
from price
where end_date between '01-jan-80' and '01-may-81';

thanks
and we said...
Well, the real question is "what is your NLS_DATE_FORMAT".  You
have the classic Y2K problem above.  Is that 01-jan-1980 OR is
it 01-jan-2080???

You probably mean 1980.  If you have the default date mask of
dd-mon-yy, the computer thinks you mean 2080.

Step 1 to correct this:  Never never never use 2 digits for a
date!!

Step 2: run:

SQL> select to_char( to_date( '01-jan-80' ), 'dd-mon-yyyy' )
       from dual;

TO_CHAR(TO_
-----------
01-jan-2080

to see that the date is in fact 2080....

Step 3: use

  between to_date('01-jan-1980','dd-mon-yyyy') and
          to_date('01-may-1981','dd-mon-yyyy')

in the future.  be explicit -- convert the strings into DATES
(to avoid possible conversions of DATES into strings -- you want
to compare dates -- not ascii strings!).  Always be explicit...
September 25, 2000 robert -- Thanks for the question regarding "storage size when creating new table", version 7.3.4
You Asked
I am a new DBA and have some questions on the storage parameters
:

1) How can I calculate or estimate record length based on the
table structure alone:

e.g
table test (
field1 varchar (5);
field2 number (5);
field3 Date;
)

2) What is the general consideration for the storage parameter
for initial, next, percentage free, percentage used, percentage
increate for data tables.

3) For the following requirement :

table structure :
field1 varchar (5);
field2 number (5);
Date;

estimated initial record: 1000
          Annual Growth : 1000
          Max. record: 20000

What should be the optimal create table storage parameter ?

Thanks in advance.
robert
and we said...
1) you cannot.  You can get the MAX size.  The max size for the
above will be:

6 bytes for the varchar2(5)
5 bytes for the number
7 bytes for the date

But the varchar2 can vary from 0 to 6 bytes, and the number can
vary from 0 to 5 bytes.

The only TRUE way to get accurate average row lengths for YOUR
data is to load some representative sample of it (from 0.1% to
10% depending on the size of the final table) and analyze it --
then the avg_row_len will be in the data dictionary for you.

2) see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:421419463648
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:407619241062
http://www.kevinloney.com/free/extperf.doc
for some advice in that area.  I'm going to say
INITIAL=NEXT and PCTINCREASE=0 in all cases.  pctfree and
pctused -- you are the only one that can answer that.  If you
never update data -- pctfree=0.  If you constantly update rows
and make them larger -- you'll need a higher number.

3) thats a tiny table.  a 50k initial, 50k next might work just
fine.  You have 18bytes/row max.  1,000 rows.  That is only
18,000 bytes.  Add 50% overhead max and you get about 24k.  Hard
to size something so small....

September 25, 2000 Joe -- Thanks for the question regarding
      "OWA_COOKIE.SEND", version 2.2

      You Asked
I've been attempting to utilize the above procedure to write
(and later to read) cookies to the client's machine with the
following code

OWA_COOKIE.SEND('COLORJHG1','Blue','12-DEC-00');

I've tried this in both the before displaying page and after
displaying header.  The message "Set-Cookie: COLORJHG1=Blue;
expires=Tuesday, 12-Dec-2000 08:00:00 GMT;" appears at the top
of the page, but no cookie entry is made to cookies.txt.

Any ideas ?

      and we said...
This demonstrates how to set a cookie and get it:

CREATE OR REPLACE PROCEDURE demo
IS
     v_cookie owa_cookie.cookie;
BEGIN
   v_cookie := owa_cookie.get('COLORJHG1');

   owa_util.mime_header('text/html', FALSE);
   OWA_COOKIE.SEND('COLORJHG1','Blue','12-DEC-00');
   owa_util.http_header_close;

   IF (v_cookie.num_vals > 0)
   THEN
      htp.bold( 'cookie is set and is ' || v_cookie.vals(1) );
    ELSE
      htp.p( 'cookie is not set' );
   END IF;
END;
/

The first time you run that, it will say "cookie is not set".
The second time you run it -- it will.

The trick is to START a header and don't close it (mime_header(
..., FALSE) ) and then send the cookie and close the header.
You do this before any calls to htp.*

Review &
      Followup

      Rating:
      3
owa_cookie.send  February 20, 2002

Reviewer:  Mauricio Bevilacqua  from S?o Paulo,
      Brasil
That's exactly what I've did, but still I don't got a good result.
May I reproduce my code?:

...
   owa_util.Mime_Header('text/html',FALSE);
   valorCookie := fn_PegaBiscoito('Limite');
   if valorCookie <> 'Farinha' then
     pc_DissolveBiscoito('Limite', 'Farinha', '/');
     pc_DissolveBiscoito('Pagina', 'Farinha', '/');
     pc_DissolveBiscoito('Paginas', 'Farinha', '/');
     for h in 1..to_number(valorCookie) loop
       pc_DissolveBiscoito('id' || to_char(h), 'Farinha', '/');
     end loop;
   end if;
   open resultado for csql;
     i := 0;
     p := 0;
     j := 0;
     LOOP
       fetch resultado into rec;
         EXIT when resultado%NOTFOUND;
           j := j + 1;
           pc_FabricaBiscoito(to_char(j), rec.id, SYSDATE, '/');
   end loop;
   CLOSE resultado;
   i := trunc(j / 6);
   if mod(j,6) <> 0 then
     i := i + 1;
   end if;
   pc_FabricaBiscoito('Limite', to_char(j), SYSDATE, '/');
   pc_FabricaBiscoito('Pagina', '1', SYSDATE, '/');
   pc_FabricaBiscoito('Paginas', to_char(i), SYSDATE, '/');
  owa_util.Http_Header_Close;
   --for h in 1..i loop
      --htp.anchor('PesquisaDigitais.ed_MostraFotos?limite=' || j || chr(38)
||'pagina=' || h || chr(38) || 'paginas=' || i, h);
    ed_MostraFotos(j,1,i);
EXCEPTION
   WHEN OTHERS THEN
      htp.htmlopen;
      htp.headopen;
      htp.title('Página de erro');
      htp.headclose;
      htp.bodyopen;
...
      htp.print ('erro: ' || TO_CHAR(SQLCODE) || ' ' || SQLERRM);
      htp.bodyclose;
      htp.htmlclose;
END ed_Busca;

PROCEDURE ed_MostraFotos (limite in number, pagina in number, paginas in number)
is
h number(5);
p number(5);
i number(5);
c number(5);
l number(5);
k number(5) := 1;
idfoto edt.v_ed_fotos_termos.id%type;
caminho varchar2(256);
csql varchar2(2000);
cwhere varchar2(2000);
BEGIN
   htp.htmlOpen;
   htp.headOpen;
   htp.title('Pesquisa de fotos digitais');
   htp.headClose;
   htp.bodyOpen;
...
   htp.tableOpen('BORDER="1"',cattributes=>'width="750"');
   h := 0;
   --p := pagina * 6 - 5;
   --i := 1;
   if pagina < paginas then
     l := pagina * 6;
   else
     l := limite;
   end if;
   c := pagina * 6 - 5;
   k := c;
   p := 1;
   LOOP
     EXIT when k > l;
         h := h + 1;
         if h = 1 then
           htp.tableRowOpen;
         end if;
         if fn_PegaBiscoito(to_char(k)) <> 'Farinha' then
           idfoto := to_number(fn_PegaBiscoito(to_char(k)));
         else
           idfoto := 0;
         end if;
         if fn_PegaCaminho(idfoto, caminho) is not null then
           htp.tabledata(htf.Img(caminho, calt=>'leia aqui',
cattributes=>'width="100"'), calign=>'center');
         else
           htp.tabledata(idfoto || htf.br || htf.bold(g_mens || ' Foto ' || k),
cattributes=>'HEIGHT="100"');
         end if;
         if h = 3 then
           htp.tableRowClose;
           h := 0;
         end if;
         --p := p + 1;
         k := k + 1;
   end loop;
   if h < 3 then
     htp.tableRowClose;
   end if;
   --if p > limite then
     --p := limite;
   --end if;
   htp.tableClose;
   htp.br;
   htp.paragraph('right');
   for h in 1..paginas loop
      htp.anchor('PesquisaDigitais.ed_MostraFotos?limite=' || limite || chr(38)
||'pagina=' || h || chr(38) || 'paginas=' || paginas, h);
   end loop;
   htp.br;
   htp.paragraph('left');
   htp.line;
   --htp.formClose;
   htp.bodyClose;
   htp.htmlClose;
EXCEPTION
   WHEN OTHERS THEN
      htp.print ('erro: ' || TO_CHAR(SQLCODE) || ' ' || SQLERRM);
END ed_MostraFotos;

FUNCTION fn_PegaCaminho (idfoto in number, caminho in out varchar2)
RETURN varchar2
--
-- Esta função recupera os caminhos das fotos.
--
is
BEGIN
  select edt.pg_ed_fotos.fn_edft_traz_caminho_foto(idfoto,'HB') into caminho
from dual;
   if length(caminho) > 0 then
      RETURN caminho;
   else
      RETURN '';
      g_mens := 'ERRO: A foto não foi encontrada. ' || to_char(SQLCODE) || ' - '
|| SQLERRM;
   end if;
EXCEPTION
   WHEN OTHERS THEN
     g_mens := to_char(SQLCODE) || ' - ' || SQLERRM;
     RETURN '';
END fn_PegaCaminho;

PROCEDURE pc_FabricaBiscoito (nomeCookie in varchar2, valorCookie in varchar2,
dataExpira in date, endereco in varchar2)
is
BEGIN
  owa_util.Mime_Header('text/html',FALSE);
  owa_cookie.Send(nomeCookie, valorCookie, dataExpira, endereco);
  owa_util.Http_Header_Close;
END pc_FabricaBiscoito;

PROCEDURE pc_DissolveBiscoito (nomeCookie in varchar2, valorCookie in varchar2,
endereco in varchar2)
is
BEGIN
  owa_util.Mime_Header('text/html',FALSE);
  owa_cookie.Remove(nomeCookie, valorCookie, endereco);
  owa_util.Http_Header_Close;
END pc_DissolveBiscoito;

FUNCTION fn_PegaBiscoito (nomeCookie in varchar2) RETURN varchar2
is
  valorCookie owa_cookie.Cookie;
BEGIN
  valorCookie := owa_cookie.Get(nomeCookie);
  if valorCookie.Num_Vals > 0 then
    RETURN(valorCookie.Vals(1));
  else
    RETURN('Farinha');
  end if;
END fn_PegaBiscoito;

Sorry, and tanks.

September 25, 2000 Jacob -- Thanks for the question regarding
      "Function Based Indexes", version 8.1.6.2

      You Asked
Dear Tom,

We have an application which zaps data on the fact table which
is in excess of 20M records. It takes the following form:

 DELETE measurements WHERE  last_modified_by
 LIKE '%'||'&1'||'#'||'&2'||'#%'

This currently takes nearly 2-3 hrs each time its run. Is there
a way we can speed this up ?.

Thanks

Additional Info:

&1 is fixed and &2 is of varying length and mixed case. The
character in front of &1 is a '#'.
The table is not modified.
last_modified_by is varchar2(50)

Hope this answers your questions.

      and we said...
Ok, lets say the &1 is after the 1'st #sign and the &2 is after
the second, upto the 3'rd.  Then I might do something like:

SQL> create table t ( last_modified_by  varchar2(50) );
Table created.

SQL> insert into t values
  2  ( 'stuff#amper1_data#amper2_data#more_data' );
1 row created.

SQL> create index t_idx on
  2  t(substr( last_modified_by,
  3            instr(last_modified_by,'#',1,1)+1,
  4            instr(last_modified_by,'#',1,3)
  5             - instr(last_modified_by,'#',1,1)-1 )
  6   )
  7  /
Index created.

if i have the placement of the #'s off -- you just need to
adjust the 4'th parameter to instr in the above -- I'm looking
for the 1'st and 3'rd ones...

SQL> create or replace view t_view
  2  as
  3  select t.*,
  4    substr( last_modified_by,
  5            instr(last_modified_by,'#',1,1)+1,
  6            instr(last_modified_by,'#',1,3)
  7             - instr(last_modified_by,'#',1,1)-1 ) idx_col
  8    from t
  9  /

View Created.

SQL> alter session set QUERY_REWRITE_ENABLED=TRUE;
Session altered.

SQL> alter session set QUERY_REWRITE_INTEGRITY=TRUSTED;
Session altered.

SQL> set autotrace on explain
SQL> delete /*+ index( t_view t_idx ) */ from t_view
  2   where idx_col = 'amper1_data#amper2_data';

1 row deleted.

Execution Plan
----------------------------------------------------------
   0      DELETE STATEMENT Optimizer=CHOOSE (Cost=1 Card=1
   1    0   DELETE OF 'T'
   2    1     TABLE ACCESS (BY INDEX ROWID) OF 'T' (Cost=1
   3    2       INDEX (RANGE SCAN) OF 'T_IDX' (NON-UNIQUE)

SQL> set autotrace off

That can make use of an index.  See

http://osi.oracle.com/~tkyte/article1/index.html#how
for more info on that feature.  If you analyze the table, you
might not need the hint.
September 25,
      2000 Jason -- Thanks for the question
      regarding "SQL utility to work out percentages", version 3.1.3.7.2

      You Asked
Tom

Assume that I have a script below

break on report
compute sum of sum(loan_amount) on report
select officer, sum(loan_amount)
from table_x
group by officer

the results will be as follows

officer          sum(loan_amount)
-------          ----------------
Mr Q                3000
Mr W                4000
Mr T                6000
Mr X                7000
-------          ----------------
sum                20000

I would like the results to look like the following

officer          sum(loan_amount)        percentage
-------          ----------------        ----------
Mr Q                3000                     15
Mr W                4000                     20
Mr T                6000                     30
Mr X                7000                     35
-------          ----------------        -----------
sum                20000

So could you help me with the relevant code to calculate the
respective percentage of each officer's total in relation the
the grand total

Thanking you in advance

Jason

      and we said...
Something like this (deptno = officer, sal=loan_amount)

  1  select deptno, sum(sal), sum(sal)/tot_sal
  2  from emp, ( select sum(sal) tot_sal from emp )
  3* group by deptno, tot_sal
scott@ORA716.WORLD> /

    DEPTNO   SUM(SAL) SUM(SAL)/TOT_SAL
---------- ---------- ----------------
        10       8750       .301464255
        20      10875       .374677003
        30       9400       .323858742

will do it.
September 25, 2000
      Naveed -- Thanks for the question regarding
      "UID", version 8.1.6

      You Asked
Does UID has any meaning in Oracle Database.

when I execute:

select uid from dual;

i get 33 as a result...

From where this value is coming..

Thanks

      and we said...
UID is the UserId.

scott@ORA716.WORLD> select uid, user, username, user_id from
all_users
  2  where user_id = UID and username = USER;

       UID USER    USERNAME      USER_ID
---------- ------- ---------- ----------
         8 SCOTT   SCOTT               8

It is a function -- like USER is.
September 25, 2000 Nag -- Thanks for the question regarding "joins
      with different datatype makes poor performance", version Oracle 7.3

      You Asked
Hi,
Thanks lot for the answers given for all my questions. Now I
have   very simple question.

All my queries are joined based on different datatypes.

table test1  (cust_num varhcar2(10),
               cust_add varchar2(30));

table test2  (obligor number(10),
              obligation number(10));

Now all my queries are like
  select obligation
  from test2 a, test1 b
 where a.obligor =cust_num;

In this as obligor is number and cust_num is charector, will it
degrade the performance. To make both in the same datatype can I
use to_number() function. The total no. of records will be 10
millions. In this case how can I tune this queries.

      and we said...
It will work OK but you'll need to put thought into it when
TEST2 is the "driving" table.

Lets say you join them together and have a predicate on
test2.obligation.  You would like to use an index on
test2.obligation to find just the few rows in test2 that match
and then pick up their matches in test1.  But when we compare
the NUMBER to a VARCHAR2, the varchar2 will be converted into a
number  -- precluding the use of an index.  So in this case --
we need to make sure to convert the NUMBER from test2 into a
string to compare to test1.  Here is an example:

SQL> create table test1  (cust_num varchar2(10),
  2                 cust_add varchar2(30));
Table created.

SQL> create index test1_idx on test1(cust_num);
Index created.

SQL> create table test2  (obligor number(10),
  2                obligation number(10));
Table created.

SQL> create index test3_idx on test2(obligor);
Index created.

SQL> set autotrace on explain
SQL> select * from test1, test2
  2  where test1.cust_num = test2.obligor;

no rows selected

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   NESTED LOOPS
   2    1     TABLE ACCESS (FULL) OF 'TEST1'
   3    1     TABLE ACCESS (BY ROWID) OF 'TEST2'
   4    3       INDEX (RANGE SCAN) OF 'TEST3_IDX' (NON-UNIQUE)

When TEST1 is the driving table and you want it to be the
driving table -- it will naturally use the index on TEST2 since
the varchar2 in TEST1 will be cast as a number and the number
can be used in the index... However

SQL> select * from test1, test2
  2  where test1.cust_num = ltrim(to_char(test2.obligor));

no rows selected

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   NESTED LOOPS
   2    1     TABLE ACCESS (FULL) OF 'TEST2'
   3    1     TABLE ACCESS (BY ROWID) OF 'TEST1'
   4    3       INDEX (RANGE SCAN) OF 'TEST1_IDX' (NON-UNIQUE)

When you want test2 to be the driving table -- you must be
careful to cast test2.obligor as a STRING (and a correctly
formatted one at that!) before you compare.  Else the index on
TEST1 could not be used since the comparision:

  where test1.cust_num = test2.obligor

is the same as:

  where to_number(test1.cust_num) = test2.obligor

and the to_number would (in 8.0 and before) preclude the use of
an index...

So, you can do it -- you just have to thing about "which table
will drive the query" and when the driving table has the NUMBER,
remember to convert it.

SQL> set autotrace off
September
      25, 2000 -- Thanks for the question
      regarding "The new RESIZE feature to expand datafiles", version 8.1.6

      You Asked
Should I use the resize feature instead of add datafiles
whenever possible ? Are there situations where one is
recommended over the other ?

Thanks,

Winston Douglas

      and we said...
Thats a hard one to answer.

Some people never use it.  Some people use it all of the time.
I use it until my files get to 2gig -- then I add another file.
I hate having files >2 gig, too many things (OS utilities) have
potential problems and they are just too big at that point.

So, I like to use it until they get to 2 gig (I set a maxsize on
all autoextent file).

I like to use resize to shrink files as well -- thats a nice
feature.  Works well on tablespaces you use to hold "temporary
permanent objects", things that might be around for a couple of
days.  I use a script like:

set verify off
column file_name format a50 word_wrapped
column smallest format 999,990 heading "Smallest|Size|Poss."
column currsize format 999,990 heading "Current|Size"
column savings  format 999,990 heading "Poss.|Savings"
break on report
compute sum of savings on report

column value new_val blksize
select value from v$parameter where name = 'db_block_size'
/

select file_name,
       ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) smallest,
       ceil( blocks*&&blksize/1024/1024) currsize,
       ceil( blocks*&&blksize/1024/1024) -
       ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) savings
from dba_data_files a,
     ( select file_id, max(block_id+blocks-1) hwm
         from dba_extents
        group by file_id ) b
where a.file_id = b.file_id(+)
/

column cmd format a75 word_wrapped

select 'alter database datafile ''' || file_name || ''' resize '
 ||
       ceil( (nvl(hwm,1)*&&blksize)/1024/1024 )  || 'm;' cmd
from dba_data_files a,
     ( select file_id, max(block_id+blocks-1) hwm
         from dba_extents
        group by file_id ) b
where a.file_id = b.file_id(+)
  and ceil( blocks*&&blksize/1024/1024) -
      ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) > 0
/

---------------------------------------------

to generate ALTER's that shrink my files as small as they can
be.

So, if you feel comfortable with it -- use it.  If you don't,
don't.  I don't like to have lots of files so I let them grow to
2 gig but add new ones after that.

September 25, 2000 murali -- Thanks for the question regarding
      "inspdver", version 8.1.6

      You Asked
Hi

I have installed Oracle 8.1.6 on Solaris 2.6 platform. After
installing i couldn't localte "inspdver" command to check the
verssions. How will i check the versions... or any other command
is available.

While i installed 8.0.5 on the same os it was asking whether you
are going to use raw device for oracle (raw device support). But
 8.1.6 it never asks me that...will it still support raw
devices..?

Please help

Thanks & Regards

Muali

      and we said...
Previous versions of Oracle supplied the 'inspdver' utility in
the $ORACLE_HOME/orainst directory.  It relied on information
maintained by the 'orainst' utility to display information about
which Oracle components were installed in a given $ORACLE_HOME
directory.

With Oracle8i, the Installer is completely new and the
'inspdver' utility is no longer provided.  However, information
about installed products can be obtained by running the Oracle
Universal Installer (runInstaller) and clicking on the
'Installed Products' button located on the opening screen.

Oracle8.1.6 supports RAW devices -- they are no different then
"cooked" devices as far as we are concerned.  You just give us a
device name instead of a file name.  See the system specific
docs for your OS for details (such as the number of blocks you
must set aside on your platform for raw device overhead).

September 25, 2000 wallacel -- Thanks for the question regarding
      "several question", version 8.1.6

      You Asked
Tom:

I have several question as below,please help me, thanks!

1.question about : back up control file after structure changes.
scenario:
    control file is \t02\oradata\c1
Time T: consistent database backup with tablespace t1,t2.
   T+1:    user create tablespace t3 and drop t1.  and then
backup
        control file to \backup\c2
   T+2:    user create tablespace t4 and drop t2.
   T+3: if now a media crash destroy all datafile, can i use c1
        + "cold backup at time t" + all the archived redo log to

        recover the database?
        i think c1 now only record information about t3 and t4,
how it correspond the structure of backup since it only have t1
and t2? why i need to backup control file after structure
changes
(c2)?  what is c2 used for?

2.If i want to create a tablespace test, which include table
a,b,c and now the content of a is 100m, b is 50m and c is 30m,
and a will grow to 200m , b will to 100m and c will to 100m,
how do i create tablespace and table?
create tablespace test datafile '/temp/test.dbf' size 180m
--equal to 100+50+30
autoextend on next 20m maxsize 400M                 --equal to
200+100+100.

create table a (whatever)
tablespace test
storage(initial 100M next 20M minextents 1 maxextents 6)
create table b (whatever)
tablespace test
storage(initial 50M next 10M minextents 1 maxextents 6)
create table c (whatever)
tablespace test
storage(initial 30M next 10M minextents 1 maxextents 8)

I should always set table's initial as big as it's current size.
set tablespace's initial as big or bigger than the total size of
all table inside the tablespace.and I should create a table with

storage parameter set with not exception, am i right?

3.some times I can connect sys without problem, but some time
system ask me to use sys/sysPassword as sysdba. why?
ORA-28009: connection to sys should be as sysdba or sysoper

4.if I issue shutdown abort. uncommitted transactions are not
rollback.but when next time i startup database, system will
recover database automatically.am i right?

5. i found the following information in udump
Session 6 exceeded soft sessionspace limit of 0x100000 bytes.
what does that mean?

6.when using show parameter in my system,
log_archive_buffers, log_archive_buffer_size didn't show. why?

7.when doing cold backup, do i need to backup files which
belogns to temporay tablespace?
( in case of dictionary or locally managed tablespace).

8.when using locally managed tablespace compare autoallocate and

uniform manage space allocation.when should use which?

9.oracle8i Administrator's guide page 11-5
when a mix of transaction is not prevalent,each rollback segment

should be 10% of the size of the database's largest table
because most sql statements affect 10% or less of a table.

my question is when talking about database's largest table, does

it include system table or not? any other tip for define
rollback segment's size? how to read v$rollstat to determine if
current setting for rollback segment is correct?

Regards,

      and we said...
Wow, thats alot.  Ok, lets see what we can do here.

1) you can still recover the database however, you'll need to
recreate the control files using your backup control file as a
starting point.  You'll have us turn that backed up control file
into an ascii "create controlfile" statement.  You'll edit that
to reflect the "real world" and recover using it.  All of the
steps are covered in depth at:

http://technet.oracle.com/doc/oracle8i_816/server.816/a76993/recoscen.htm#11872
"c2" in your case is used as a starting point to create an
initial create controlfile statement (or you can do the whole
thing by hand).

2) I love uniform sizing.  For those objects -- I would use a
locally managed tablespace with UNIFORM extent sizes of save
10M.  I would create an load each of A, B, and C with just 1
extent and load them -- let them grow as they will over time.
Each will use 10m extents and nothing else.  Search for the
words locally and managed on my search to see other tidbits
(like each datafile in a locally managed tablespace should add
64k and so on).  I never set the initial equal to the table size
to begin with -- I use uniform sized extents period.

3) would really need more information.  There must be something
different between the environments when you connect -- using a
different tool, on a different platform or something.

4) When you shutdown abort -- we just stop.  When we start up,
we begin by recovering (rolling forward) everything and then
roll back all uncommitted transactions.  So, we roll forward and
then roll back.

5) Check the following settings and increase as appropriate:

   JAVA_MAX_SESSIONPSPACE_SIZE
   JAVA_SOFT_SESSIONSPACE_LIMIT

Increasing the JAVA_SOFT_SESSIONSPACE_LIMIT should suppress this
warning message.

6) Both of those parameters are obsoleted in Oracle8i, they
don't count anymore.

7) If they are true temporary tablespaces with tempfiles - no,
not in any case.  If they are real datafiles, no -- not really
but it *complicates* the recovery process so I would recommend
you do.  Otherwise -- at the moment you really want things to go
smooth -- you've added unnecessary complications to a process
you really want to go smoothly.

8) Autoallocate = you don't know what is happening which can be
scary.  I like to know exactly what is happening.  I prefer
uniform sizes period.  Autoallocate seems to allocate the first
few extents small and then much larger for the rest.  I prefer
to just set the size myself and use the same size for all
extents.

9) I don't like rules of thumb because they are not very well
defined.  They mean the largest table you affect via DML (eg:
your tables, not ours).

I use v$waitstat to see if there is contention for rollback.  If
there is -- you might need more.  If not, you are OK.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:233214228495
for more info.

September 26, 2000 Prashant -- Thanks for the question regarding
      "Opening html file from forms 6 menu", version forms 6

      You Asked
How can I open Html file from a forms 6 menu. I have created the
html file for help. I want to open it as any form or report from
the menu.

      and we said...
I would use the same method I demonstrate in

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:721425255411
for running >1 report previewer.

I would setup a small script that knows how to start the users
browser.  If the associations are setup correctly -- this can be
as easy as just running "foo.html", or better yet, start
foo.html to run it in the background (lets forms continue on).
Then, use HOST to run that script.  In that fashion, if the way
to start the HTML ever changes, you can update the script and
not have to redeploy your form.
September 26, 2000 Adam -- Thanks for the question regarding
      "Loading Data by Using Oracle Forms", version Dev2000 Forms v6

      You Asked
How to Load Data with Forms Without Using Sql Loader

      and we said...
You can use the same method I outline in

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:322417112080
That does it in a stored procedure in the database (not forms)
so you will have to replace UTL_FILE with TEXT_IO to make it
work on the client.

You would probably want to replace the calls to DBMS_SQL with
calls to EXEC_SQL as well (although the dbms_sql should work
fine in forms)
September 26, 2000
      Paolo -- Thanks for the question regarding
      "Unselect item of type textbox", version 5.0.6.8.0

      You Asked
How can remove the highlight from text in a item whenever the
item gets the focus with FORM builder?

Thanks and regards
Paolo

      and we said...
Get the d2kwutil library from
ftp://oracle-ftp.oracle.com/dev_tools/patchsets/dev2k/Win95NT/d2k
wutil/

and then you can put a when-new-item-instance trigger on the
items you do not want selected by default with the code:

DECLARE
   pos pls_integer;
BEGIN
   pos := get_window_property(FORMS_MDI_WINDOW, WINDOW_HANDLE);
   win_api_shell.sendkeys(pos, '^{Home}', FALSE);
END;

that'll do it.
September 26,
      2000 Narendra -- Thanks for the
      question regarding "Incremental Export-import", version 7.3.2.2.1

      You Asked
Hi Tom,
Please explain more about Incremental ,cumulative Export and
then
Import the same with suitable example.
When use incremental Import  ,how import will import data when
existing table contain the previous data.Is the duplicat rows
are inserted or only updated and new rows will insert.
How can I update my secondary database on second machine with
this utility with mininmum time and effort.
Thanks
NP

      and we said...
To use incremental or cumulative exports, you must start with a
complete export.  After that you can do incremental exports --
these will export any TABLE that has been modified since the
last complete, incremental or cumulative export.  It exports the
entire table -- not just changed rows.

A cumulative export will export all tables that have been
modified since the last complete or cumulative export -- you can
now discard all intervening incremental backups you have done.

Lets say you do the following:

o a complete database export (should use consistent=y).  That
will generate an export with everything in it.

o you add a row to tables T1, T2 and T3.

o you do an incremental export.   That will export T1, T2, and
T3 only.

o you add a row to T3, T4 and T5

o you do an incremental export.  That will export T3, T4, and
T5.

Now, you can take that full complete export and apply it to an
empty database -- then apply the first incremental.  That will
drop and recreate (and populate) T1..T3.  Apply the next
incremental and it'll do the same for T3..T5.

It is important to note that, since importing an incremental
export file imports new versions of existing objects, existing
objects are dropped before new ones are imported. This behavior
differs from a normal import. During a normal import, objects
are not dropped and an error is generated if the object already
exists.

You may find that taking a HOT backup of the source database and
restoring that and doing a point in time recovery may be faster
if the volumne of changed data is high in the source database.
Rather then dropping and recreating the table (and all indexes)
-- just copy the datafiles after putting the database into hot
backup mode and apply some logs to the copy to get it going.

September 26, 2000 Lisa -- Thanks for the question regarding "Hex to
      Number", version version 7.3.4

      You Asked
Tom,

Before pulling my hair out on trying to figure this one out, I
figured I ask you first.  Is there already something written
that converts a hexadecimal into a number.  I found a function
that converts numbers to hex, which is great.  But I haven't
been able to find anything for number to hex.

Any help would be great.

Thanks,

Lisa

      and we said...
see

http://osi.oracle.com/~tkyte/
and specifically:

http://osi.oracle.com/~tkyte/hexdec/index.html
for this.

September 26, 2000 SUNIL -- Thanks for the question regarding
      "Probl;em with package with record set on 8.0.6 which was ok on 8.1.5",
      version ver 8.0.6 and 8.1.5 on solaris /NT

      You Asked
Hi Tom
Iam facing some problem with Stored procedure which is using
Record set as  out Parameter
The incidence is the Server is Oracle 8.0.6 on solaris and it is
called by com object with MTS
1.    I have two packages which is  wriiten in the same style
which is given below of this the first one doesnot compile and
gives error while the other one doesn't
CREATE OR REPLACE package spKT_RecipeVersioN is
type recset is ref cursor;
procedure get1
(
id in recipe.id%type,
rec out recset
);
procedure getparentlinks
(
id in recipe.id%type,
specifier in recipe.specifier%type,
version in recipeversion.version%type,
rec out recset
);
end spKT_RecipeVersion;
CREATE OR REPLACE package body spKT_RecipeVersioN

is
procedure get1

(

id in Recipe.ID%TYPE,

rec1 out recset

)
is

lc_id Recipe.ID%TYPE default null;

ln_b_VersionExists number;
BEGIN

lc_id := get1.id ;

IF LENGTH( get1.ID) != 38 THEN

LC_ID := NULL ;

ELSE

lc_id := get1.ID;

END IF;

open rec1 for

select * from dual where 1>2;

spKT_RecipeVersionExists(lc_ID, ln_b_VersionExists);

if ln_b_VersionExists =0 then

spKT_ErrorRaiseError ('RMS_E_RECIPE_VERSION',
'spKT_RecipeVersionGet');

RETURN;

END IF;

open rec1 for

SELECT Version Version , Editor Editor,EditTimestamp
EditTimestamp,

AttrChgTimestamp AttribChgTimestamp, ApprovalCode ApprovalCode,

Executable Executable, Verified Verified, Comments Comments,

DeploymentInfo DeploymentInfo
FROM RecipeVersion

WHERE ID = lc_ID;

dbms_output.put_line('Iam here to after upadet' );

Return;
end get1;
procedure GetParentLinks

(

id in Recipe.ID%TYPE,

Specifier in Recipe.Specifier%Type,

Version in RecipeVersion.Version%TYPE,

rec1 out recset

)
is

lc_id Recipe.ID%TYPE default null;

LC_Specifier Recipe.Specifier%Type default null;

LC_Version RecipeVersion.Version%TYPE default null;

LC_RecipeVersionID Recipe.ID%TYPE default null;
BEGIN

lc_id :=GetParentLinks.ID ;

LC_Specifier :=GetParentLinks.Specifier;

LC_Version := GetParentLinks.Version;

IF LENGTH( GetParentLinks.ID) != 38 THEN

LC_ID := NULL ;

ELSE

lc_id := GetParentLinks.ID;

END IF;

open rec1 for

select * from dual where 1>2;

spKT_RecipeValidateAndReturnID(LC_ID, LC_Specifier, LC_ID);

IF LC_ID IS NULL THEN

spKT_ErrorRaiseError ( 'RMS_E_RECIPE',
'spKT_RecipeVersionGetParentLinks');

RETURN;

END IF;

begin

SELECT ID INTO LC_RecipeVersionID
FROM RecipeVersion

WHERE (RecipeID = lC_ID) AND (Version = LC_Version)

AND (DeletedID IS NULL);

exception

when others then

null;

end;

IF (lC_RecipeVersionID IS NULL) THEN

spKT_ErrorRaiseError ('RMS_E_RECIPE_VERSION',
'spKT_RecipeVersionGet');

RETURN;

END IF;

open rec1 for

SELECT rcp.ID, rcpVer.ID, rcp.Specifier ||';'||rcpVer.Version
FROM Recipe rcp, RecipeVersion rcpVer, RecipeLink rcpLinks
WHERE (rcpLinks.SubrecipeVersionID = LC_RecipeVersionID)

AND (rcpLinks.RecipeVersionID = rcpVer.ID) AND

(rcpVer.RecipeID = rcp.ID) ;

dbms_output.put_line('Iam here to after upadet' );

Return ;
end GetParentLinks;

begin
null;
end spKT_RecipeVersioN;

when I compile this on Oracle 8.0.6 i get this error  where as
in 8.1.5 it works fine
PLS-00323: subprogram or cursor 'GET1' is declared in a package
specification and must be defined in the package body
PLS-00323: subprogram or cursor 'GETPARENTLINKS' is declared in
a package specification and must be defined in the package body
Another package of similar style works fine the script was
CREATE OR REPLACE package spKT_ClassGet is
type recset is ref cursor;
procedure AgentsForClass

(id in class.id%TYPE,

rec1 out recset

);
procedure RecipeNames

(DeletedStatus in Integer,

ID in Recipe.id%type,

Specifier in Recipe.specifier%type,

out_ID out Recipe.id%type,

rec1 out recset

);
end spKT_ClassGet;
/
CREATE OR REPLACE package body spKT_ClassGet

is
procedure AgentsForClass

(id in class.id%TYPE,

rec1 out recset

)
is

ln_cnt number;
begin
open rec1 for select * from dual where 1 > 3;

dbms_output.put_line('Iam here ' ||ln_cnt);
SELECT count(*) into ln_cnt FROM Agent WHERE ID IN (

SELECT AgentID FROM ClassAgent WHERE ClassID =
AgentsForClass.ID);

dbms_output.put_line('number ' ||ln_cnt);

IF ln_cnt = 0 then

null;

---- dbms_output.put_line('Errors occurs ' );

else
dbms_output.put_line('starting ' );

open rec1 for

SELECT ID, InstrumentType, SWVersion FROM Agent WHERE ID IN (

SELECT AgentID FROM ClassAgent WHERE ClassID =
AgentsForClass.ID);

dbms_output.put_line('end with the result ' );

END IF;
end AgentsForClass;

procedure RecipeNames

(DeletedStatus in Integer,

ID in Recipe.id%type,

Specifier in Recipe.specifier%type,

out_ID out Recipe.id%type,

rec1 out recset

)
IS
lc_id Recipe.id%type default null;

lc_specifier Recipe.specifier%type;

ln_cnt number;

ln_cnt1 number;

Sto0_error integer ;
BEGIN

Sto0_error := 0;

ln_cnt :=0;

ln_cnt1 :=0;

open rec1 for
SELECT * FROM dual
WHERE 1>2;
lc_specifier := RecipeNames.Specifier;

lc_id := RecipeNames.ID;

IF LENGTH(RecipeNames.ID) != 38 THEN

LC_ID := NULL ;

ELSE

lc_id := RecipeNames.ID;

END IF;
Select count(*) into ln_cnt from Class where ID = lc_id AND
Specifier = lc_specifier;

Select count(*) into ln_cnt1 from Class where ID = lc_id AND
ParentID is NULL;

out_ID := null;

IF lc_ID IS not NULL and lc_specifier is null then

spKT_classgetspecifier(lc_id,lc_specifier);

if lc_specifier is null then

spKT_ErrorRaiseError ('RMS_E_CLASS',
'spKT_ClassGetRecipeNames');

Rollback;
RETURN;

end if;

elsif lc_ID IS NULL and lc_specifier is not null then

spKT_classgetHandle(lc_specifier,lc_id);

if lc_id is null then

spKT_ErrorRaiseError ('RMS_E_CLASS',
'spKT_ClassGetRecipeNames');

Rollback;
RETURN;

end if;

elsif lc_ID IS NULL and lc_specifier is null then

spKT_ErrorRaiseError ('RMS_E_CLASS',
'spKT_ClassGetRecipeNames');

Rollback;
RETURN;

elsif ln_cnt = 0 then
spKT_ErrorRaiseError ('RMS_E_CLASS',
'spKT_ClassGetRecipeNames');

Rollback;
RETURN;

end if;

if ln_cnt1 >0 then

spKT_ErrorRaiseError ('RMS_E_CLASS',
'spKT_ClassGetRecipeNames');

Rollback;
RETURN;

end if;

out_ID := lc_id;

if RecipeNames.DeletedStatus =0 then

open rec1 for
SELECT ID, Specifier FROM Recipe WHERE ParentID = lc_ID;

elsif RecipeNames.DeletedStatus =1 then

open rec1 for
SELECT ID, Specifier FROM Recipe WHERE ParentID = lc_ID
AND DeletedID IS NOT NULL;

elsif RecipeNames.DeletedStatus =2 then

open rec1 for
SELECT ID, Specifier FROM Recipe WHERE ParentID = lc_ID
AND DeletedID IS NULL;

end if;

end RecipeNames;
begin
null;
end spKT_ClassGet;

This above package works fine
Can u tell me y this happens for the previous package
2. This package compile in 8i and not in 8.0.6
CREATE OR REPLACE package spKT_ClassFind is

type recset is ref cursor;

procedure Recipes
(Criteria in Class.Description%TYPE,

rec1 out recset
);

end spKT_ClassFind;
/

CREATE OR REPLACE package body spKT_ClassFind

is

procedure Recipes
(Criteria in Class.Description%TYPE,

rec1 out recset
)

is

lc_criteria Class.Description%TYPE default null;

begin

lc_criteria := ' '||Criteria ;

open rec1 for lc_criteria;

EXCEPTION When Others Then

open rec1 for select * from dual where 1>2;

dbms_output.put_line('Error - ' || sqlerrm);

Return ;

end Recipes;

begin

null;

end spKT_ClassFind;
/
The error is
PLS-00103: Encountered the symbol "LC_CRITERIA" when expecting
one of the following:
   select
PLS-00103: Encountered the symbol "end-of-file" when expecting
one of the following:
   begin function package pragma procedure form external

Hope u would help to get to solve my problem

Thank U
Sunil

      and we said...
I do not believe the first one compiled in either release.  In
the specification you have:

..
procedure get1
(
id in recipe.id%type,
rec out recset
);
...

in the body you have:

procedure get1
(
id in Recipe.ID%TYPE,
rec1 out recset
)
...

the parameter names DO NOT match.  use rec in both places.  I
cannot compile that in 8.0 or 8.1.

Also, in 8.0 for a ref cursor to be opened, you MUST define it
to be IN OUT.  In 8.0, once you fix the parameter name mismatch,
you will get:

ops$tkyte@8.0> show err
Errors for PACKAGE BODY SPKT_RECIPEVERSION:

LINE/COL ERROR
--------
-----------------------------------------------------------------

10/2     PL/SQL: SQL Statement ignored
10/7     PLS-00361: a cursor variable must be IN OUT to be
OPEN'ed

the solution is to change the type to IN OUT in the spec and
body.

the second error is more straightforward.  The ability to
dynamically open a ref cursor ala:

  open X for Y;

where Y was a query -- was introduced in 8.1.  It is not
available in 8.0.  You simply cannot do that in 8.0

September 26, 2000 ted -- Thanks for the question regarding "q: long
      data type", version 8.1.5

      You Asked
thomas,

1. can I use utl_raw.length to find out the length of long field
?

2. how do i convert long to a long raw field.

thnx in advance
ted chyn

      and we said...
1) no.  you can use

create or replace function long_length( p_cname in varchar2,
                                        p_tname in varchar2,
                                        p_rowid in rowid )
return number
as
    l_cursor    integer default dbms_sql.open_cursor;
    l_n         number;
    l_long_val  varchar2(32760);
    l_long_len  number;
    l_buflen    number := 32760;
    l_curpos    number := 0;
begin
    dbms_sql.parse( l_cursor, 'select ' || p_cname ||
                               ' from ' || p_tname ||
                              ' where rowid = :rid',
                    dbms_sql.native );

    dbms_sql.bind_variable( l_cursor, ':rid', p_rowid );

    dbms_sql.define_column_long(l_cursor, 1);
    l_n := dbms_sql.execute(l_cursor);

    if (dbms_sql.fetch_rows(l_cursor)>0)
    then
        loop
            dbms_sql.column_value_long(l_cursor, 1, l_buflen,
                                       l_curpos ,
                                       l_long_val, l_long_len );
            l_curpos := l_curpos + l_long_len;
            exit when l_long_len = 0;
      end loop;
   end if;
   dbms_sql.close_cursor(l_cursor);
   return l_curpos;
exception
   when others then
      if dbms_sql.is_open(l_cursor) then
         dbms_sql.close_cursor(l_cursor);
      end if;
      raise;
end long_length;
/

and if you made that an AUTONOMOUS_TRANSACTION in Oracle8i
release 8.1, you could even call that from SQL.  As you can see
-- use it sparingly, it'll take a while to run on lots of rows.

2) you can convert UPTO 32k of LONG to LONG RAW using PLSQL and
UTL_RAW.CAST_TO_RAW.  Beyond that -- you would need to use a 3gl
such as C, Java, etc to perform this operation.

You can convert a LONG to a CLOB and then a CLOB to a BLOB all
in PLSQL and in 8.0 and up -- you should really be using LOBS,
not LONGS (all of these problems go away with LOBS)....

September 26, 2000 ted -- Thanks for the question regarding "q:
      table storage requirement", version 8.1.5

      You Asked
thomas,
how do i finding out the actual storage of a table beside
looking at allocating space and high water mark because neither
this info in the catalog takes into account of unused space in a
block ?

thnx in advacne
ted chyn

      and we said...
Analyze the table is the only way.  It will look at each block
and at the end you have AVG_SPACE -- free space on the block.

You can use my show_space to see the number of blocks on the
freelist -- given that you know what the pctfree and pctused for
the tables are -- you can make a good guesstimate without having
to analyze the table.  my show_space will show you the number of
blocks never used (totally empty) and the number of blocks on
the free list (which must have more the pctfree % free space).

search for show_space in my search screen....

September 26, 2000 Arthur -- Thanks for the question regarding
      "Indexes", version 8.1.5

      You Asked
Tom,

I am interested in your opinion here.   I was looking for ways
to speed up access and updates to our journal table.  I was
reading something interesting in an Oracle book titled 'Using
Oracle 8/8i - special Edition'.

The book claims that for exact match queries, hash indexes
should be used.  Not to index columns that are updated
frequently and not to put indexes on tables that have high DML
activity.

In my case, the journal table is inserted to, updated, and
selected from all day.  And, the columns that are used in most
of the where clauses are indexed, mainly because it is the
primary key or unique key to the table.

How useful are hash indexes?  And, do you agree with the
findings of this book?

Arthur

      and we said...
Hash indexes can be very useful.  One way I describe them is
"the data is the index".  Instead of having a secondary data
structure ( a btree ) that must be read to get an address of
data, the query itself it "read" to get the address of data.
You take a query like:

select * from t where x = 5;

Using a btree we would have to do at least a couple (2-3) IO's
to find the rowid of the row we wanted and then an IO at least
to get that.

Using a hash cluster, we would turn 5 into a rowid in effect and
read the row.  Given a perfect scenario - we could do this in 1
IO (hashing can cause different numbers to hash to the same
value causing chaining and additional IO's).  So, hashing would
lead to less overall IO's to get the data.

This works well for "x = 5" type queries.  Does not work at all
for "x between a and b" or "x like z" or "x > y" and so on.
Only equality works with hashes.

The downside to a hash cluster is you sort of need to be aware
of the maximum number of rows you expect.  So, if your journal
table is constantly growing, it is probably not a good hash
candidate.

As for "do I agree with the findings of this book" -- I have not
read the entire book.  The rule of thumb advice you quote above:

"The book claims that for exact match queries, hash indexes
should be used.  Not to index columns that are updated
frequently and not to put indexes on tables that have high DML
activity."

is in general sound advice.  It MUST be balanced however with
other needs.  Take "Not to index columns that are updated
frequently" is true IFF those columns are not used in a
predicate frequently.  If one of the main queries you run is:

  select * from T where x between a and b;

and T is a 1 million row table
and the number of rows "between a and b" is 10
and you update X frequently

you should have an index on T(x) for the query (to avoid a full
scan) or don't run that query.  Same with the advice to not
index tables that have high DML activity -- almost every table
needs some index at some time.  It is just that in these cases
-- the cost of having the index must be less then the cost of
NOT having it.

Review &
      Followup

      Rating:
      5
  November 21, 2001
Reviewer:  Helena
      Markova  from Bratislava, Slovakia

September 26, 2000 John -- Thanks for the question regarding
      "Indexing a bi-temporal table", version 8.1.6

      You Asked
I have many tables that are bi-temporal structured as follows:
(idcolumn,effdate,thrudate,tstamp,thrutstamp,colval1,...)

When querying this data we typically will do:
  "select colval1 from tablename where
  idcolumn = IDVALUE
  and trunc(sysdate) >= effdate
  and trunc(sysdate) <= thrudate
  and sysdate >= tstamp
  and sysdate <= thrutstamp

I know this type of data is one of the most difficult data to
query & index on.  My question is this a situation where a
function index might help and, if so, how would you implement
it?

TIA
John

      and we said...
These queries are the pits -- this is stuff that is really
truely hard to get performant.  Typically -- it makes sense to
use only 1 index on all 5 columns above starting with IDColumn
and putting the "best" column next and do lots and lots of
scanning.

If there is some MAX "effdate thrudate" range (eg: the different
between the two is never more then 500 days), you can short
circut this via:

effdate between trunc(sysdate)-500 AND trunc(sysdate)

Now, we have that much less data to shift through. You can do
that on any of the columns above.

Another option that would work well with the effdate-thrudate
range would be to maintain, via a trigger perhaps, another table
that has the primary key (or rowid) of the above table and a
date.  You would have a trigger that would in effect put:

  delete from another_table where rid = :new.rowid;
  for i in 0 .. thrudate-effdate loop
     insert into another_table values
     ( :new.rowid, :new.idcolumn, :new.effdate+i);
  end loop;

and then you could query:

select ...
 where rowid in ( select rid from another_table
                    where date_col = trunc(sysdate)
                      and idcolumn = idvalue )
   and sysdate between tstamp and thrustamp
/

for example.  That other table would be an Index Organized table
with a primary key of idcolumn, date_col (and if need be rowid).

September 26, 2000 Gopi Krishna -- Thanks for the question regarding
      "Compiling PL/SQL program units ", version 8.0.5

      You Asked
Hi Tom ,
         I have a problem with compiling Pl/SQL package. I have
a package that consists of a lot of related procedures and
functions. Today when I tried to add a new procedure to the
existing package and tried compiling it , I got the error ,
Program too large. This happens when my package crosses over
3500 lines or so. Is there a solution to this problem ?

thanking you in Advance

Regards

Gopi Krishna Sampath Kumar

      and we said...
The number of lines is not relevant -- it is the complexity of
the code.  In Oracle8.0 and before, the number of nodes
generated in the parse tree (loosely speaking) was about 32k.
In 8i and up it is 2billion or so (effectively no limit).

The only solutions are:

o rewrite the code so the parse tree doesn't get as big.  this
is not practical as you don't know (nor do I) how to code to
make the parse tree smaller..

o break the code up.

September 26, 2000 Stanley -- Thanks for the question regarding
      "DBMS_JOB() + SNAPSHOTS", version 8.0.5

      You Asked
Hi tom,
Sorry - I went blank went typing the qn and typed
"synonym" instead of "snaphot".

1. Presently i have a database that
gets its data from another db using snapshots,
now we want to remove all snapshots and get
data directly, can i achieve this through
DBMS_JOB() package?
By the way does DBMS_JOB() also use
snapshots indirectly or is it just
the process SNP doing the job?

can i do this using:
1. triggers - but this would increase n/w traffic.
2. run db 1 in archivelog and apply the log to db 2.
   (by the way can i automate this?)

sorry for confusing u last time.

thanx again

Stan

      and we said...
1) well, snapshots are really  nothing more then a stored
procedure that is run in the background by dbms_job.  If you
look at user_jobs -- you'll see your snapshot refresh scheduled
in there.  So, dbms_jobs is one of the tools you are using now.

Yes, you can write your own stored procedure and have dbms_job
execute it periodically to get your data.

SNP is just the "job queue process".  It runs jobs in the queue
-- it used to be that the only job out there was a snapshot
(once upon a time ago).

In Oracle8i, you can automate the entire standby database
process - ARCH will forward the logs over the network for you.
In 8.0 you had to script it yourself to move the logs and apply
them.  In 8i, all automated.

September 26, 2000 wallacel -- Thanks for the question regarding
      "detect create view error", version 8.1.6

      You Asked
Tom:

I have a question regarding create view.

For example:

create table a ( a int);
create view aView as select * from a;
drop table a;
alter view aView compile;

it gives me the following message:
Warning:View alter with compile error.

how can i know what kind of error i got?

when i use show error.
it says no errors.

Regards,

      and we said...
scott@ORA8I.WORLD> create table a ( a int);

Table created.

scott@ORA8I.WORLD> create view aView as select * from a;

View created.

scott@ORA8I.WORLD> drop table a;

Table dropped.

scott@ORA8I.WORLD> alter view aView compile;

Warning: View altered with compilation errors.

scott@ORA8I.WORLD> show errors view aview;
Errors for VIEW AVIEW:

LINE/COL ERROR
--------
-----------------------------------------------------------------

0/0      ORA-00942: table or view does not exist

September 26, 2000 Tess -- Thanks for the question regarding "Row
      counts with Ref cursors", version 8.1.6

      You Asked
Hi Tom,

I'm trying to get the count of rows put into the ref cursor before the ref
cursor is passed back to an ADO record set.  I know that If i fetch out of the
ref cursor I can use the cursor%ROWCOUNT.  But this empties the ref cursor and I
can not pass it back.  I tried using a function on one of the fields and
incrementing a global variable.  On the first exec the global variable is zero
and the records returned in the ref cursor totaled 2.  The next exec the global
variable goes to 2 and the records returned in the ref cursor totaled 2.  The
next exec the global variable was 4.  I did not look at the ref cursor cause I
knew it had 2 records.  The next exec the global variable was still 4 I looked
in the ref cursor, 2 records.  Next exec the global variable went up to 6.  It
looks like the global variable only gets incremented when I look at the record
set.  So does that mean that the select is not executed until the ref cursor is
looked at?  I thought that the select was executed at the time the procedure was
invoked and the information was placed into a memory location and the ref cursor
returned the memory address to that location...  So I'm confused about how the
Ref cursor works and how to count tht number of records in it...  Any
suggestions?

Thanks!
Tess Goodwin

      and we said...
You cannot get what we do not know.

Lets say you open a cursor like:

  open X for select * from a_one_billion_row_table;

At the point in time you open that query -- we have absolutely NO IDEA how many
rows it will retrieve.  We do not prebuild the answer somewhere and then start
handing them out.  In most cases, we've just come up with a PLAN to get the rows
-- we haven't gotten them.

SQL%RowCount is a count of the rows affected SO FAR.  As you fetch we would
increment that count.  A ref cursor is no different then any other cursor -- it
is not answered until right after you fetch the very last row from it.

Sorry but what you are after just isn't possible to get.
Review &
      Followup

      Rating: 5
done
      it  November 12, 2002
Reviewer:
      A reader
Hi tom,

 I found the solution.. so please don't spend your time
on that

Thanks,

September 26, 2000 jimmy -- Thanks for the question regarding
      "tables in a database", version oracle 8.0.5

      You Asked
Hi Tom:

  How could I  figure out tables in a tablespace ?
  Who is the owner, how big is this table ?

 thanks and regards

      and we said...
select owner, segment_name, bytes
  from dba_segments
 where segment_type = 'TABLE'
   and tablespace_name = '......'
/

September 26, 2000 Ramkumar -- Thanks for the question regarding
      "EXPORT of Oracle 8.1.6 Spatial Option - MDSYS objects - How?", version
      Oracle 8.1.6 on Solaris

      You Asked
Exp does not export the database objects belonging to the user
MDSYS (oracle spatial user).

How to export the objects of mdsys and other users of spatial
data?  (Oracle Spatial option documentation keeps mum' on this!)

      and we said...
MDSYS's objects, much like SYS's objects, are populated via DDL.
 The spatial definitions are exported (much like the definition
of an index is exported-the index is not) and during an import
-- they will get recreated.

It is the act of running IMP that will do the DDL that will
populate these tables.
September 26,
      2000 wallacel -- Thanks for the
      question regarding "combine two file", version 8.1.6

      You Asked
Tom:

I have a tablespace named test which include two datafile
/temp/test.dbf   and /temp/test1.dbf
is there any way i can move all the content from one file
to another so i can have only one big file and get rid of other
one?

also I saw command how to resize, reallocate datafile,
but i don't know how to drop a datafile.
when i use command
alter database datafile 'xxx.dbf' offline drop,
and then check dba_data_files, the status is still "available"
and in V$datafiles,it show me that "recover"

      and we said...
Once a file is added to a database -- it is going to be part of
that database until you drop the tablespace it was added to.

There is no way to combine two files.  If you really only want 1
datafile you would:

o create a new tablespace with 1 datafile
o alter table T move tablespace <that tablespace>
o alter index I rebuild tablespace <that tablespace>
o drop tablespace old_tablespace (after moving and rebuilding
everything)

You cannot drop a datafile unless you are going to drop the
tablespace.  The offline drop is intended to used right before
you do a "drop tablespace <tablespace that had that file>
including contents".  It is a last ditch "get my database backup
because I accidently erased a datafile and don't have a backup"
option.  You should not use it.  You will now have to DROP the
tablespace you offline dropped the file from or recover it from
backups.
September 27, 2000 LOU -- Thanks for the question regarding
      "PROCEDURE FOR UPDATE", version 8.1.6

      You Asked
Hi tom,

I have a table that need to be update(copy) periodically from
one schema to another. What is the best way to do this?
I am thinking about a procedure.

Lou

      and we said...
I would use a snapshot.

In the primary schema, you would issue:

create snapshot log in T;

In the schema to copy to, you might issue:

create snapshot t_copy
refresh fast
next trunc(sysdate)+1
as
select * from other_schema.t
/

that would create a snapshot that would copy the changes of T every night at
midnight for you.

See the replication guide for more details.
Review &
      Followup

      Rating:
      4
  October 04, 2001
Reviewer:
      Pauline  from NY,U.S.A.
Tom,
I got the request for the issue as below:
We have one DSS database on unix server_1. The CORE schema owns tables
of currencies and exchange_rates.
SQL> desc currencies
 Name                              Null?    Type
 ---------------------------------------------------------------
 CURRENCY_ID                       NOT NULL NUMBER
 CURRENCY_CODE                     NOT NULL VARCHAR2(4)
 CURRENCY_NM                       NOT NULL VARCHAR2(40)
 DELETED_FLG                       NOT NULL VARCHAR2(1)
 LAST_UPDATE_DT                    NOT NULL DATE
 CURRENCY_SYMBOL_NUM               NUMBER

The data sample are shown below:

CURRENCY_ID CURR CURRENCY_NM                              D LAST_UPDATE
CURRENCY_SYMBOL_NUM
----------- ---- ---------------------------------------- - -----------
-------------------
        110 ANG  NETHERLANDS ANTILLEAN GUILDER            N 02-JAN-2001
        111 ATS  AUSTRIAN SCHILLING                       N 02-JAN-2001
        112 AUD  AUSTRALIAN DOLLAR                        N 02-JAN-2001

Most likely currencies table's data is not going to update after created.

SQL> desc exchange_rates
 Name                              Null?    Type
 ----------------------------------------------------------------
 EXCHRATE_ID                       NOT NULL NUMBER
 CURRENCY_ID                       NOT NULL NUMBER
 EXCHANGE_RATE_DT                  NOT NULL DATE
 RATE_PER_USD_NUM                  NUMBER
 RATE_PER_GBP_NUM                  NUMBER
 RATE_PER_EUR_NUM                  NUMBER
 DELETED_FLG                       NOT NULL VARCHAR2(1)
 LAST_UPDATE_DT                    NOT NULL DATE

EXCHRATE_ID is PK in the table and the data sample are shown below:

EXCHRATE_ID CURRENCY_ID EXCHANGE_RA RATE_PER_USD_NUM RATE_PER_GBP_NUM
RATE_PER_EUR_NUM D LAST_UPDATE
----------- ----------- ----------- ---------------- ----------------
---------------- - -----------
   61624177         110 09-JUN-1992            .5548         .3040858
    0 N 30-AUG-2001
   61624178         111 06-JUL-1901         .0788022                0
    0 N 30-AUG-2001
   61624179         111 23-AUG-1907         .0773933                0
    0 N 30-AUG-2001

The exchange_rates.CURRENCY_ID is FK references currencies.CURRENCY_ID.
This table will be inserted or updated by nightly load and pl/sql
program.
Now when CORE.exchange_rates get changed, we need to update another
database another schema AUC's table exchange_rate using CORE.exchange_rates
table's newly information. This database is OLTP database and resides
on unix server_2.

SQL> desc exchange_rate
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EXCHRATE_ID                               NOT NULL NUMBER
 CURRENCY_CODE                                      VARCHAR2(20)
 EXCHANGE_RATE_DT                          NOT NULL DATE
 RATE_PER_USD_NUM                                   NUMBER
 RATE_PER_GBP_NUM                                   NUMBER
 RATE_PER_EUR_NUM                                   NUMBER
 DELETED_FLAG                                       CHAR(1)
 LAST_UPDATE_DATE                                   DATE

The data sample are shown below:

SQL> select EXCHRATE_ID ,CURRENCY_CODE from exchange_rate where rownum<4;

EXCHRATE_ID CURRENCY_CODE
----------- --------------------
   61624177 ANG
   61675772 ATS
   61675800 ATS

Now I am considering which method is better to perform this task.
If use materialized view, I need to create database link and
materialized view joining CORE.exchange_rates and CORE.currencies
(using fast refresh option) on copy site.

create materialized view exchange_rates_mv
TABLESPACE DATA_1
BUILD IMMEDIATE
REFRESH FAST
START WITH SYSDATA
NEXT TRUNC(SYSDATE) + 1
  AS
  SELECT
  E.*,C.CURRENCY_CODE FROM CORE.exchange_rates@remote_sever E,
                           CORE.CURRENCIES@remote_server C
  WHERE E.CURRENCY_ID=C.CURRENCY_ID;

Also create materialized view log on master site CORE.exchange_rates
table using the combination of primary key/rowid.
If so, the application should uses this MVIEW instead of using AUC's
table exchange_rate, right?
But the data modelor already designed the AUC's exchange_rate table
for this application. If he really wants to UPDATE AUC's EXISTING
table exchange_rate,then should I using trigger to perform this task?
As my understanging, materialized view can't update copy site's table
--in this case is AUC's exchange_rate table, right?

Please give help. I have to make the decision and implement it soon.

Thanks in advance.

Pauline

      Rating:
      4
  October 04, 2001
Reviewer:
      Pauline  from NY,U.S.A.
Tom,
I did't put my mail address in previous feedback .
Now I filled in.

Thanks.

September 27, 2000 omprakash -- Thanks for the question regarding
      "Date Calculation", version NAS

      You Asked
How to calculate the number of seconds between 2 given dates?

      and we said...
See

http://osi.oracle.com/~tkyte/
and specifically

http://osi.oracle.com/~tkyte/Misc/DateDiff.html
for more details but basically:

select (date1-date2)*24*60*60 from T;

will do that.
Review & Followup

      Rating: 5
very
      useful  May 12, 2003
Reviewer:
      A reader

September 27, 2000 Omar -- Thanks for the question regarding
      "Deleting from all tables", version 8.1.5

      You Asked
Hi Tom,
 I need to delete all rows from all tables from certain schema
but as you know you need to know the dependencies of the tables
to do so, delete child tables then parents. How could I write
one script to do so.

with respect and greate thanks

      and we said...
I'll take the easy way out -- you could find the recursive
relationship and do all of the deletes in exactly the right
order using user_dependencies but a much much easier method
exists.  Run a script like this:

set heading off
set feedback off
spool tmp.sql
select 'alter table ' || table_name ||
       ' disable constraint ' || constraint_name || ';'
from user_constraints where constraint_type = 'R'
/
select 'truncate table ' || object_name || ';'
  from user_objects where object_type = 'TABLE'
/
select 'alter table ' || table_name ||
       ' enable constraint ' || constraint_name || ';'
from user_constraints where constraint_type = 'R'
/
spool off
set heading on
set feedback on

And then run the resulting tmp.sql.  It'll disable all of the
constraints -- truncate the tables (faster then delete by far)
and then turn on all of the constraints it turned off.
Review &
      Followup

      Rating: 5
excellent
      script  December 15, 2001
Reviewer:  sanjai
       from MI,USA
This is exactly what I was looking for. Thanks a lot Tom.

September 27, 2000 Pratap -- Thanks for the question regarding
      "Executables from Dev 6i forms", version 6i

      You Asked
Hi Tom,
      Thanks for your response. Now I have a small query. Is it
possible to make a deployble executable from developer
forms/reports. If yes then please tell how. For client server
installation of our application which is in developer it it
necessary to install D2K in the client machines.

      Thanks in advance.

       Pratap

      and we said...
Forms can only run .fmx files.  It cannot generate a .exe or
.dll for deployment.  If deploying / installing software on the
clients is a concern (it should be in my opinion) you would use
developer server so you have to install on exactly 1 machine and
no others.
September 27, 2000
      N -- Thanks for the question regarding
      "Restricting CPU/Memory usage by User", version 8i (Rel 2)

      You Asked
Hi Tom,
Firstly, thanks for your help. Is it possible to limit certain
users to only access certain cpu/memory/other parameters etc.

* Can oracle limit particular usernames to a certain percentage
of the CPU at most
* Can oracle limit particular usernames to a certain percentage
of the Memory at most

Just as it is possible in unix to limit particular users by
any/every of the information listed by ulimit. Is there anything
possible in Oracle that allows you to do this.

What are techniques used to achieve this. Please advise.

Thanks in advance.

      and we said...
Yes with profiles you can do this, see

http://technet.oracle.com/doc/oracle8i_816/server.816/a76989/ch4f20.htm#36190
also, check our resource management as another alternative:

http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/dbresmgr.htm#10731
in Oracle8i.

September 27, 2000 Frank -- Thanks for the question regarding
      "Delete Columns in a Table", version 8.0.5 / 8.1.6

      You Asked
Hi Tom,

I know that it is (or was?) not possible to delete/drop columns
from a table. Is there a chance when using Oracle 8i? Or do you
know any nice script doing all the stuff for me? There are some
constraints on my table so I have to do more than only a CREATE
AS and RENAME.

Thanks for your help,
Frank

      and we said...
See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:842827107711
for my recommended way of doing ths in 8.0 and before.

In Oracle8i, release 8.1, you can alter table T drop column X;
or alter table T set unused column X;.  The first physically
removes the column ( rewrites the table ).  the second "flag
deletes" it much like my suggested method above does...

September 27, 2000 Shaya -- Thanks for the question regarding "OAS
      Security", version 4.0.8

      You Asked
Hi Tom.
I Have OAS 4.0.8 running on Windows 2000.
My Question : What is the Best way to secure my pages on local
intranet.
Note:
I have one database user (schema) having some package that
generate html-form used for data entry of information (I want to
protect these pages).
Another database user having some package that generates
html-pages used for browsing information (not protected).

Please provide me with steps to establish the security.

Thanks in advance.

      and we said...
Depends on your needs.

I myself prefer to do it this way:

o create database users for each of my end users.
o grant execute on "special packages" to roles.
o grant these roles to the correct people.
o create a DAD and choose to NOT store the userid/password with
the DAD.  The end user will now be prompted for their
username/password.  We will use this to login to the database.
If they have the ability to EXECUTE the package via a grant or
role -- it will run (else not).

o create another DAD that stores the username/password of the
second user you refer to above.  anyone with a browser will be
able to run these URLS.
September 27,
      2000 Shruti -- Thanks for the question
      regarding "Owa_sylk utility", version 4.0.8.1

      You Asked
Hi Tom,

I am trying to add a heading  to this utility to Just print date

and Some global Heading. How do I do that?

Shruti
For example On top of the following query print out
I want the heading:

Emplyoee summary sheet for
salary> 2000

Date:

a_util.mime_header( 'application/excel' );
       3      owa_sylk.show(
       4          p_query => 'select empno id, ename employee,
       5                             sal Salary, comm commission
' ||
       6                     'from scott.emp ' ||
       7                     'where job = :JOB ' ||
       8                     'and sal > :SAL',
       9          p_parm_names =>
      10                 owa_sylk.owaSylkArray( 'JOB', 'SAL'),
      11          p_parm_values =>
      12                   owa_sylk.owaSylkArray( 'MANAGER',
'2000'
     ),
      13         p_sum_column =>
      14                   owa_sylk.owaSylkArray( 'N', 'N', 'Y',

     'Y'),
      15          p_show_grid => 'NO' );
      16  end;
      17  /

      and we said...
Thanks to Chris Beck -- he added this feature for you.  This
adds a user_heading parameter:

create or replace
package owa_sylk as
--
  type owaSylkArray is table of varchar2(2000);
--
  procedure show(
      p_query         in varchar2,
      p_parm_names    in owaSylkArray default owaSylkArray(),
      p_parm_values   in owaSylkArray default owaSylkArray(),
      p_sum_column    in owaSylkArray default owaSylkArray(),
      p_max_rows      in number     default 10000,
      p_show_null_as  in varchar2   default null,
      p_show_grid     in varchar2   default 'YES',
      p_show_col_headers in varchar2 default 'YES',
      p_font_name     in varchar2   default 'Courier New',
      p_widths        in owaSylkArray default owaSylkArray(),
      p_titles        in owaSylkArray default owaSylkArray(),
      p_strip_html    in varchar2   default 'YES',
      p_user_heading  in varchar2   default null );
--
  procedure show(
      p_cursor        in integer,
      p_sum_column    in owaSylkArray  default owaSylkArray(),
      p_max_rows      in number     default 10000,
      p_show_null_as  in varchar2   default null,
      p_show_grid     in varchar2   default 'YES',
      p_show_col_headers in varchar2 default 'YES',
      p_font_name     in varchar2   default 'Courier New',
      p_widths        in owaSylkArray default owaSylkArray(),
      p_titles        in owaSylkArray default owaSylkArray(),
      p_strip_html    in varchar2   default 'YES',
      p_user_heading  in varchar2   default null );
--
end owa_sylk;
/

create or replace
package body owa_sylk as
--
  g_cvalue  varchar2(32767);
  g_desc_t dbms_sql.desc_tab;
  g_lengths owa.vc_arr;
  g_sums owa.vc_arr;

  g_user_heading number := 0;
--
--

  procedure p( p_str in varchar2 )
  is
  begin
    htp.p( p_str );
  exception
    when others then null;
  end;

  function build_cursor(
      q in varchar2,
      n in owaSylkArray,
      v in owaSylkArray ) return integer is
    c integer := dbms_sql.open_cursor;
    i number := 1;
  begin
    dbms_sql.parse (c, q, dbms_sql.native);
    loop
      dbms_sql.bind_variable( c, n(i), v(i) );
      i := i + 1;
    end loop;
    return c;
  exception
    when others then
      return c;
  end build_cursor;
--
--
  function str_html ( line in varchar2 ) return varchar2 is
    x       varchar2(32767) := null;
    in_html boolean         := FALSE;
    s       varchar2(1);
  begin
    if line is null then
      return line;
    end if;
    for i in 1 .. length( line ) loop
      s := substr( line, i, 1 );
      if in_html then
        if s = '>' then
          in_html := FALSE;
        end if;
      else
        if s = '<' then
          in_html := TRUE;
        end if;
      end if;
      if not in_html and s != '>' then
        x := x || s;
      end if;
    end loop;
    return x;
  end str_html;
--
  function ite( b boolean,
                t varchar2,
                f varchar2 ) return varchar2 is
  begin
    if b then
      return t;
    else
      return f;
    end if;
  end ite;
--
  procedure print_comment( p_comment varchar2 ) is
  begin
    return;
    p( ';' || chr(10) || '; ' || p_comment || chr(10) || ';' );
  end print_comment;
--
  procedure print_heading( font in varchar2,
                           grid in varchar2,
                           col_heading in varchar2,
                           titles in owaSylkArray,
                           htext varchar2 default null )
  is
    l_title varchar2(2000);
  begin
    p( 'ID;ORACLE' );
    print_comment( 'Fonts' );
    p( 'P;F' || font || ';M200' );
    p( 'P;F' || font || ';M200;SB' );
    p( 'P;F' || font || ';M200;SUB' );
    --
    print_comment( 'Global Formatting' );
    p( 'F;C1;FG0R;SM1' ||
           ite( upper(grid)='YES', '', ';G' ) ||
           ite( upper(col_heading)='YES', '', ';H' )  );
    for i in 1 .. g_desc_t.count loop
      p( 'F;C' || to_char(i+1) || ';FG0R;SM0' );
    end loop;
    --
    if htext is not null then
      print_comment( 'User Heading' );
      g_user_heading := 3;
      p( 'F;R1;FG0L;SM0' );
      p( 'C;Y1;X1;K"' || htext || '"' );
    end if;
    --
    print_comment( 'Title Row' );
    p( 'F;R' || to_char(1+g_user_heading) || ';FG0C;SM2' );
    for i in 1 .. g_desc_t.count loop
      g_lengths(i) := g_desc_t(i).col_name_len;
      g_sums(i) := 0;
      begin
        l_title := titles(i);
      exception
        when others then
          l_title := g_desc_t(i).col_name;
      end;
      if i = 1 then
        p( 'C;Y' || to_char(1+g_user_heading) || ';X2;K"' ||
l_title || '"' );
      else
        p( 'C;X' || to_char(i+1) || ';K"' || l_title || '"' );
      end if;
    end loop;
  end print_heading;
--
  function print_rows(
      c            in integer,
      max_rows     in number,
      sum_columns  in owaSylkArray,
      show_null_as in varchar2,
      strip_html   in varchar2 ) return number is
    row_cnt number          := 0;
    line    varchar2(32767) := null;
    n       number;
  begin
    loop
      exit when ( row_cnt >= max_rows or
                  dbms_sql.fetch_rows( c ) <= 0 );
      row_cnt := row_cnt + 1;
      print_comment( 'Row ' || row_cnt );
      --
      p( 'C;Y' || to_char(row_cnt+1+g_user_heading) );

      for i in 1 .. g_desc_t.count loop
        dbms_sql.column_value( c, i, g_cvalue );
        g_cvalue := translate( g_cvalue,
                            chr(10)||chr(9)||';', '   ' );
        g_cvalue := ite( upper( strip_html ) = 'YES',
                             str_html( g_cvalue ),
                             g_cvalue );
        g_lengths(i) := greatest( nvl(length(g_cvalue),
                                  nvl(length(show_null_as),0)),
                                  g_lengths(i) );
        line := 'C;X' || to_char(i+1);
        line := line || ';K';
        begin
          n := to_number( g_cvalue );
          if upper( sum_columns(i)) = 'Y' then
            g_sums(i) := g_sums(i) + nvl(n,0);
          end if;
        exception
          when others then
            n := null;
        end;
        line := line ||
                 ite( n is null,
                      ite( g_cvalue is null,
                               '"'||show_null_as||
                                  '"', '"'||g_cvalue||'"' ),
                             n );
        p( line );
      end loop;
      --
    end loop;
    return row_cnt;
  end print_rows;
--
  procedure print_sums(
      sum_columns  in owaSylkArray,
      row_cnt      in number ) is
  begin
    if sum_columns.count = 0 then
      return;
    end if;
    --
    print_comment( 'Totals Row' );
    p( 'C;Y' || to_char(row_cnt + 4 + g_user_heading) );
    p( 'C;X1;K"Totals:"' );
    --
    for i in 1 .. g_desc_t.count loop
      begin
        if upper(sum_columns(i)) = 'Y' then
          p( 'C;X' || to_char(i+1) || ';ESUM(R' ||
to_char(2+g_user_heading) || 'C:R' ||
                  to_char(row_cnt+2+g_user_heading) || 'C)' );
        end if;
      exception
        when others then
          null;
      end;
    end loop;
  end print_sums;
--
  procedure print_widths( widths owaSylkArray ) is
  begin
    print_comment( 'Format Column Widths' );
    p( 'F;W1 1 7' );
    for i in 1 .. g_desc_t.count loop
      begin
        p( 'F;W' || to_char(i+1) || ' ' ||
            to_char(i+1) || ' ' ||
            to_char(to_number(widths(i))) );
      exception
        when others then
          p( 'F;W' || to_char(i+1) || ' ' ||
               to_char(i+1) || ' ' ||
               greatest( g_lengths(i), length( g_sums(i) )));
      end;
    end loop;
    p( 'E' );
  end print_widths;
--
  procedure show(
      p_cursor        in integer,
      p_sum_column    in owaSylkArray default owaSylkArray(),
      p_max_rows      in number     default 10000,
      p_show_null_as  in varchar2   default null,
      p_show_grid     in varchar2   default 'YES',
      p_show_col_headers in varchar2 default 'YES',
      p_font_name     in varchar2   default 'Courier New',
      p_widths        in owaSylkArray default owaSylkArray(),
      p_titles        in owaSylkArray default owaSylkArray(),
      p_strip_html    in varchar2   default 'YES',
      p_user_heading  in varchar2   default null ) is
  --
    l_row_cnt number;
    l_col_cnt number;
    l_status  number;
  begin
    dbms_sql.describe_columns( p_cursor, l_col_cnt, g_desc_t );
    --
    for i in 1 .. g_desc_t.count loop
      dbms_sql.define_column( p_cursor, i, g_cvalue, 32765);
    end loop;
    --
    print_heading( p_font_name,
                   p_show_grid,
                   p_show_col_headers,
                   p_titles,
                   p_user_heading );
    l_status := dbms_sql.execute( p_cursor );
    l_row_cnt := print_rows(
                   p_cursor,
                   p_max_rows,
                   p_sum_column,
                   p_show_null_as,
                   p_strip_html );
    print_sums( p_sum_column, l_row_cnt );
    print_widths( p_widths );
  end show;
--
  procedure show(
      p_query         in varchar2,
      p_parm_names    in owaSylkArray default owaSylkArray(),
      p_parm_values   in owaSylkArray default owaSylkArray(),
      p_sum_column    in owaSylkArray default owaSylkArray(),
      p_max_rows      in number     default 10000,
      p_show_null_as  in varchar2   default null,
      p_show_grid     in varchar2   default 'YES',
      p_show_col_headers in varchar2 default 'YES',
      p_font_name     in varchar2   default 'Courier New',
      p_widths        in owaSylkArray default owaSylkArray(),
      p_titles        in owaSylkArray default owaSylkArray(),
      p_strip_html    in varchar2   default 'YES',
      p_user_heading  in varchar2   default null ) is
  begin
    show( p_cursor => build_cursor( p_query,
                                    p_parm_names,
                                    p_parm_values ),
          p_sum_column => p_sum_column,
          p_max_rows => p_max_rows,
          p_show_null_as => p_show_null_as,
          p_show_grid => p_show_grid,
          p_show_col_headers => p_show_col_headers,
          p_font_name => p_font_name,
          p_widths => p_widths,
          p_titles => p_titles,
          p_strip_html => p_strip_html,
          p_user_heading => p_user_heading );
  end show;
--
end owa_sylk;
/

September 28, 2000 Saibabu -- Thanks for the question regarding
      "Basics of Orapwd utility", version 8.1.5

      You Asked
Hi Tom,
     I have not found the environment variables to be set for
password file location and file name in documentation.Please
show one example of Unix environmental variables of this
utility.
     While we connect to the sqlplus session intitially,to
startup the database ,as sysdba how does it know that this
password file is for this database only.We have 6 database on
one
unix box,we want 3 databases to share one password file and
other 3 to another password file.How to do this.
 Thanks in advance
   Saibabu

      and we said...
On some platforms -- tt is ORA_<SID>_PWFILE where <SID> will
just be your SID.  On many (eg solaris), there is no such
variable and the name must be

orapw<sid>        on unix
orapw<sid>.ora    on NT

On NT, you can set the registry key ORA_<SID>_PWFILE to point to
a shared one.  On Unix, symbolic links would suffice (make sure
all instances can read/write it).

I would advise against sharing the password file.  It is not
necessary and if you do, it can only contain SYS and INTERNAL.
I would have each database use its own.  I would use SYSDBA and
SYSOPER privs and grant them to my dba's so that each DBA logs
in their credentials.  In that fashion, you have better control,
better accountability and lose nothing.
September 28, 2000 wallacel -- Thanks for the question regarding
      "v$session", version 8.1.6

      You Asked
Tom:

when i use
select username,sid,serial# from v$session;

i got something like this:

USERNAME                              SID    SERIAL#
------------------------------ ---------- ----------
                                        1          1
                                        2          1
                                        3          1
                                        4          1
                                        5          1
                                        6          1
                                        7      37345
jase                                    8       6857
jase                                    9      64195
                                       11          1
jase                                   16      55249

USERNAME                              SID    SERIAL#
------------------------------ ---------- ----------
jase                                   17      19182
jase                                   18       3698
PTUSER                                 20      11737
SYSTEM                                 22      42137
jase                                   23        918
jase                                   25       1121
jase                                   27      43079
jase                                   32       3120
                                       33      43673
jase                                   34       6014
                                       35      37569

USERNAME                              SID    SERIAL#
------------------------------ ---------- ----------
                                       36      61371

I can understand those line with name on it, but some of
lines have username as NULL , what does that mean?

      and we said...
They are Oracle back end processes.  Try this query:

ops$tkyte@DEV816> l
  1* select username, sid, serial#, program from v$session
ops$tkyte@DEV816> /

USERNAME  SID SERIAL# PROGRAM
--------- --- ------- ------------------------------
            1       1 oracle@aria-dev (PMON)
            2       1 oracle@aria-dev (DBW0)
            3       1 oracle@aria-dev (LGWR)
            4       1 oracle@aria-dev (CKPT)
            5       1 oracle@aria-dev (SMON)
            6       1 oracle@aria-dev (RECO)
WEBMAIL     9     464 sqlplus@aria-dev (TNS V1-V3)
OPS$TKYTE  16     536 sqlplus@aria-dev (TNS V1-V3)
WEBMAIL    18     384 sqlplus@aria-dev (TNS V1-V3)

9 rows selected.

to see what they are.
September 28,
      2000 raghava -- Thanks for the question
      regarding "triggers", version 8.0.6

      You Asked
hi! tom.
whenever a dml command acts on my base table
a trigger fires and data is pushed into a
temp table.the dml action may b manual or
by a batch process. my problem is ,i have another monitering
table
into which timestamp of dml action is recorded and total
no of records transfered to the temp table.can u help me
to pop up the required timestamp and no of recs
into my monitering table.
bye.

      and we said...
You can try something like the following:

ops$tkyte@DEV816> create table monitor_table
  2  ( session_id int,
  3    timestamp date,
  4    seqno int,
  5    cnt int );

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create table t ( x int );

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> create or replace package state_pkg
  2  as
  3          my_timestamp date;
  4          my_seqno     int;
  5  end;
  6  /

Package created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create or replace trigger tot_count_trigger_1
  2  before insert on T
  3  begin
  4       state_pkg.my_timestamp := sysdate;
  5       state_pkg.my_seqno := dbms_utility.get_time;
  6  end;
  7  /

Trigger created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create or replace trigger tot_count_trigger2
  2  after insert on T for each row
  3  begin
  4    update monitor_table
  5       set cnt = cnt+1
  6     where session_id = userenv('sessionid')
  7       and seqno      = state_pkg.my_seqno
  8       and timestamp  = state_pkg.my_timestamp;
  9
 10    if ( sql%rowcount = 0 ) then
 11       insert into monitor_table
 12       ( session_id, timestamp, seqno, cnt )
 13       values
 14       ( userenv('sessionid'), state_pkg.my_timestamp,
 15         state_pkg.my_seqno, 1 );
 16    end if;
 17  end;
 18  /

Trigger created.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t values ( 1 );

1 row created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> select * from monitor_table;

SESSION_ID TIMESTAMP                            SEQNO CNT
---------- -------------------- --------------------- ---
     14263 28-sep-2000 08:29:26           -1769831134   1

ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t select rownum from all_users;

79 rows created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> select * from monitor_table;

SESSION_ID TIMESTAMP                            SEQNO CNT
---------- -------------------- --------------------- ---
     14263 28-sep-2000 08:29:26           -1769831134   1
     14263 28-sep-2000 08:29:26           -1769831132  79

ops$tkyte@DEV816>
September 28,
      2000 zhu -- Thanks for the question
      regarding "How to use a variable tablename in update clause .", version
      8.1.5

      You Asked
When I want use a bind variable in a update %tablename_variable%
clause ,I have a trouble.
For example :
     CREATE PROCEDURE update_rows (
   table_name IN VARCHAR2,
   set_value IN VARCHAR2,
   condition IN VARCHAR2 DEFAULT NULL) AS
   set_clause   VARCHAR2(100) := ' set ' || set_value,
   where_clause VARCHAR2(100) := ' WHERE ' || condition;
BEGIN
   IF condition IS NULL THEN where_clause := NULL; END IF;
   EXECUTE IMMEDIATE 'Update' || table_name ||set_clause||
where_clause;
END;

  Or the tablename_variable from a table.column user cousor
cur.tablename . Please help me . Thanks .

      and we said...
You need a space in 'Update' -- it needs to be 'Update '.

This is a bad practice what you are doing above.  It makes NO
use of bind variables and is very non-performant.  I would
strongly recommend AGAINST such an approach.  It is a very bad
practice.  It would be infinitely better to use static SQL that
can make use of bind variables or to use dynamic sql that does.

You should code this more like this:

ops$tkyte@DEV816> create or replace
  2  procedure execute_immediate
  3  ( p_sql in varchar2,
  4    p_name1 in varchar2 := NULL, p_val1 in varchar2,
  5    p_name2 in varchar2 := NULL, p_val2 in varchar2,
  6    p_name3 in varchar2 := NULL, p_val3 in varchar2,
  7    p_name4 in varchar2 := NULL, p_val4 in varchar2
  8  )
  9  is
 10      cursor_name     pls_integer := dbms_sql.open_cursor;
 11      ignore          pls_integer;
 12
 13      procedure bind( n in varchar2, v in varchar2 )
 14      is begin if ( n is not null ) then
 15            dbms_sql.bind_variable( cursor_name, n, v, 255 );
 16         end if;
 17      end;
 18  BEGIN
 19      dbms_sql.parse(cursor_name, p_sql, dbms_sql.native);
 20      bind( p_name1, p_val1 );
 21      bind( p_name2, p_val2 );
 22      bind( p_name3, p_val3 );
 23      bind( p_name4, p_val4 );
 24      ignore := dbms_sql.execute(cursor_name);
 25      dbms_sql.close_cursor(cursor_name);
 26  END;
 27  /

Procedure created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create or replace
  2  procedure update_rows
  3  ( p_tname      in varchar2,
  4    p_set_clause in varchar2,
  5    p_where      in varchar2 := NULL,
  6    p_n1 in varchar2 := NULL, p_v1 in varchar2 := NULL,
  7    p_n2 in varchar2 := NULL, p_v2 in varchar2 := NULL,
  8    p_n3 in varchar2 := NULL, p_v3 in varchar2 := NULL,
  9    p_n4 in varchar2 := NULL, p_v4 in varchar2 := NULL
 10  )
 11  as
 12  begin
 13      execute_immediate( 'update ' || p_tname ||
 14                         ' set ' || p_set_clause ||
 15                         ' ' || p_where,
 16                          p_n1, p_v1,
 17                          p_n2, p_v2,
 18                          p_n3, p_v3,
 19                          p_n4, p_v4 );
 20  end;
 21  /

Procedure created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> drop table t;

Table dropped.

ops$tkyte@DEV816> create table t
  2  ( x int, y int, z int, a int, b int, c int );

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t values ( 1,1,1,1,1,1 );

1 row created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> begin
  2      update_rows( 't',
  3                   'x = :x, y = :y, z = :z',
  4                   'where c = :c',
  5                   ':x', 100,
  6                   ':y', 200,
  7                   ':z', 300,
  8                   ':c', 1 );
  9  end;
 10  /

PL/SQL procedure successfully completed.

ops$tkyte@DEV816> select * from t;

   X    Y    Z    A    B    C
---- ---- ---- ---- ---- ----
 100  200  300    1    1    1

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> begin
  2      update_rows( 't',
  3                   'a = :a',
  4                   'where c = :c',
  5                   ':a', 50,
  6                   ':c', 1 );
  7  end;
  8  /

PL/SQL procedure successfully completed.

ops$tkyte@DEV816> select * from t;

   X    Y    Z    A    B    C
---- ---- ---- ---- ---- ----
 100  200  300   50    1    1
Review &
      Followup

      Rating:
      4
Options  September 28, 2001
Reviewer:
      Andy Rutherford  from Malaysia
It was nice to see a variety of options for UPDATE.  I put one of them to use
right away!

September 28, 2000 Priyanka -- Thanks for the question regarding
      "CRASH RECOVERY IN ORACLE8I PARALLEL SERVER", version oracle8i

      You Asked
Hello Tom

If you could please tell me what happens to the user connections
that are currently connected to a node that crashes in an Oracle
Parallel server.

Kindest Regards
Priyanka

      and we said...
It depends.  You can set them up so that if possible they will
fail over to another node.  Otherwise, their outstanding work is
rolledback and they must reconnect to the database.

See

http://technet.oracle.com/doc/oracle8i_816/paraserv.816/a76968/pshavdtl.htm#9370
for details.

September 28, 2000 Adam -- Thanks for the question regarding
      "Display 'A' from Sql", version Sql 8.0.5

      You Asked
I want to display a word in single quotes ( ' )

example 'A'

Select ' 'A' ' From Dual does not give me this.

How do i achieve this.

Thanks
Adam

      and we said...
select '''A''' from dual;

in a character string constant -- two quotes = one.
September 28, 2000 JAGJIT -- Thanks for the question regarding "Cron
      Jobs in Windows NT envrioment", version 8.1.6

      You Asked
Database Oracle 8.1.6        Operating System    Windows NT

I have to schedule some cron jobs on windows NT. I have all the
code What I want is the equivalent of Unix for Windows NT
enviroment.

# This job will run Monday to Friday at 8.00 am
0 8 * * 1-5 $ORA_DBA/scripts/analyze.sql

# This job will run on  Friday at 11.30 pm
30 23  * * 5 $ORA_DBA/scripts/db_export.sql

In the second sql script , I want to concetate the export file
with the date on which the export is taken

suppose my export file is full_prod.dmp

I want to make it full_prod_09282000.dmp

suppose my log file is full_prod.log

I want to make it full_prod_09282000.log

How to schedule the jobs in Windows NT ? . I am a Unix person
and I can do the above the unix.

How can we send e-mail on Windows NT server ?
What are the services which need to be running on Windows NT to
do above ?

      and we said...
NT has a utility "at" that might be useful.

Truth be told, I like unix myself.

On NT -- i would make as much as possible be a stored procedure
(eg: your analyze.sql can most likely be a stored procedure that
uses execute immediate 'analyze table t compute statistics'; to
do the job.  Then, I would use DBMS_JOB to submit the job and
have it run whenever.  I would not use the OS.

For the exports -- OEM would be one way to schedule that.  That
is what we would use (enterprise manager and its job
facilities).  Beyond that, you would really have to ask an NT
person what they would do.

For the file naming -- if you find you can use the AT command
(type

c:\> at /?

to get an overview) you can use SQLPlus to help you out.  See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:612348047
for details.

Review &
      Followup

      Rating: 5
Download my
      sample  July 11, 2002
Reviewer:  Sikandar Hayat
      Awan  from Pindi Bhattian - Pakistan
Hi JAGJIT,
Here is a sample for naming exported files,

http://ourworld.compuserve.com/homepages/peter_koletzke/tip.htm#expname
I hope the above will help you.

      Rating: 5
Download my
      sample for NT  July 11, 2002
Reviewer:  Sikandar
      Hayat Awan  from Pindi Bhattian - Pakistan
Hi JAGJIT,
Here is a sample for naming exported files,

http://ourworld.compuserve.com/homepages/peter_koletzke/tip.htm#expname
I hope the above will help you.

September 28, 2000 Andrew -- Thanks for the question regarding
      "Performance", version 8.0.5.2.1

      You Asked
Is there any way of improving SQL retrieval performance if you
load a table with pre-sorted data, with respect to indexing.

We are moving towards Oracle 8.1.6 in the near future.

      and we said...
Well, you can improve the performance of an INDEX build if the
data is loaded pre-sorted using the NOSORT option on the index
create.

At run time -- unless you frequently do index range scans+table
access by rowids on this data -- the fact that the table in the
physical table happens to be in order of the index is not very
meaningful.  If you do index range scan+table access by rowid,
then you will achieve the optimal cached buffer usage as you
will tend to use lots of the rows on a given block and then go
onto the next block, instead of lots of scattered IOs getting 1
row / block.
September 28, 2000
      Andrew -- Thanks for the question regarding
      "Links in a chase chain", version 8.0.6.0.0

      You Asked
I know how to identify rows that are chained and I know how to
determine how many rows are chained. I would like to be able to
see how many links there are in a chase chain. Is this possible?
-- I do not believe it is, but ???  You see, I have a table with
about 10M rows and about 40% are chianed. I have increased
pctfree and seen an improvement in performance but not an
expected reduction in percent of chained rows. This tells me
that where rows used to eventually end up with several links
they are now making fewer. I still do not know, however, how
much progress I have made in reducing chase chains because I
cannot see how long the chase chains are.

      and we said...
Here is one possible way -- if we snapshot our session stats and
then run a query that gets the 1'st and last column of the table
in the select list and full scans the table -- we can inspect
the table fetch continued row stat and see what it says.

Since you know how many rows are chained (from analyze table
list chained rows), you can see the average number of blocks it
is chained on by using the table fetch continued row count
(TFCR) resulting from the full scan.  If you find you have
5,000,000 rows chained and your TFCR count is 5,000,000 -- you
have an average of 1 block, if it is 10,000,000 -- you have an
average of 2 blocks and so on per row chained.

Here is an example.  First time -- I made each row take 3 blocks
(8k block size). Second time -- 2 blocks.  That is reflected in
the TFCR counts:

ops$tkyte@DEV816> drop table t;
Table dropped.

ops$tkyte@DEV816> create table t ( x char(2000) default 'x',
  2                   y char(2000) default 'y',
  3                   z char(2000) default 'z',
  4                   a char(2000) default 'a',
  5                   b char(2000) default 'b',
  6                   c char(2000) default 'c',
  7                   d char(2000) default 'd',
  8                   e char(2000) default 'e',
  9                   f char(2000) default 'f',
 10                   g char(2000) default 'g'
 11                  )
 12  tablespace system
 13  storage (initial 64k next 64k pctincrease 0)
 14  ;

Table created.

ops$tkyte@DEV816> insert into t ( x )
  2  select 'x' from all_users;
79 rows created.

ops$tkyte@DEV816> commit;
Commit complete.

ops$tkyte@DEV816> drop table tmp;
Table dropped.

ops$tkyte@DEV816> create table tmp
  2  as
  3  select a.name, b.value
  4    from v$statname a, v$mystat b
  5   where a.statistic#=b.statistic#
  6     and name like '%table%'
  7  /

Table created.

ops$tkyte@DEV816> set termout off
 you could not see this part:
spool /dev/null
select substr(x,1,1)||substr(g,1,1)
  from t
/
spool off
set termout on

we used that to get the 1st and last column of each row and
spooled to /dev/null.  setting termout in the script will
prevent on screen display of 10million rows as well

ops$tkyte@DEV816> select t1.name, t2.value-t1.value
  2    from tmp t1,
  3         ( select a.name, b.value
  4             from v$statname a, v$mystat b
  5            where a.statistic#=b.statistic#
  6              and name like '%table%' ) t2
  7   where t1.name = t2.name
  8  /

NAME                           T2.VALUE-T1.VALUE
------------------------------ -----------------
DBWR transaction table writes                  0
table fetch by rowid                           5
table fetch continued row                    158
table scan blocks gotten                     239
table scan rows gotten                        79
table scans (cache partitions)                 0
table scans (direct read)                      0
table scans (long tables)                      1
table scans (rowid ranges)                     0
table scans (short tables)                     0
transaction tables consistent                  0
read rollbacks

transaction tables consistent                  0
reads - undo records applied

12 rows selected.

Note that 158 = 2x79.  Each row took 3 blocks to read fully.

ops$tkyte@DEV816> drop table t;
Table dropped.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create table t ( x char(2000) default 'x',
  2                   y char(2000) default 'y',
  3                   z char(2000) default 'z',
  4                   g char(2000) default 'g'
  5                  )
  6  tablespace system
  7  storage (initial 64k next 64k pctincrease 0)
  8  ;

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t ( x )
  2  select 'x' from all_users;

79 rows created.

ops$tkyte@DEV816> commit;

Commit complete.

ops$tkyte@DEV816>
ops$tkyte@DEV816> drop table tmp;

Table dropped.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create table tmp
  2  as
  3  select a.name, b.value
  4    from v$statname a, v$mystat b
  5   where a.statistic#=b.statistic#
  6     and name like '%table%'
  7  /

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> set termout off
 you could not see this part:
spool /dev/null
select substr(x,1,1)||substr(g,1,1)
  from t
/
spool off
set termout on

we used that to get the 1st and last column of each row and
spooled to /dev/null.  setting termout in the script will
prevent on screen display of 10million rows as well

ops$tkyte@DEV816>
ops$tkyte@DEV816> select t1.name, t2.value-t1.value
  2    from tmp t1,
  3         ( select a.name, b.value
  4             from v$statname a, v$mystat b
  5            where a.statistic#=b.statistic#
  6              and name like '%table%' ) t2
  7   where t1.name = t2.name
  8  /

NAME                           T2.VALUE-T1.VALUE
------------------------------ -----------------
DBWR transaction table writes                  0
table fetch by rowid                           5
table fetch continued row                     79
table scan blocks gotten                     159
table scan rows gotten                        79
table scans (cache partitions)                 0
table scans (direct read)                      0
table scans (long tables)                      1
table scans (rowid ranges)                     0
table scans (short tables)                     0
transaction tables consistent                  0
read rollbacks

transaction tables consistent                  0
reads - undo records applied

12 rows selected.

Note that 79 = 1x79 -- it took 2 blocks to read each row
fully

September 28, 2000 steve -- Thanks for the question regarding "pro*c
      samples on redhat 6.1 won't compile", version 8.1.6.

      You Asked
I have 8.1.6 installed on redhat 6.1.

Hi Tom,

If I try make samples using the supplied makefile
I get errors saying that the precompiler cannot
find stdarg.h and stddef.h (for example). (These
are pulled in by stdio.h.)

If I use cc standalone, it seems to resolve everything
ok. I found stdarg.h in /usr/lib/bcc/include although
I don't need cc -I /usr/lib/bcc/include to compile. (?)
I can't find any DEFINEs that proc may be using to change
the process of reading the header files.

I've tried include=/usr/lib/bcc/include as an argument to
proc which resolves the cannot find header error, but results
in it complaining about syntax errors in libio.h etc. It
really doesn't like that.

Summary:
I don't understand why I can't even build the samples
using the sample makefile?

Thanks,
Steve

      and we said...
I see this issue recorded in the problem database as problem
#892910.  It is caused by the fact that the headers are all over
the place depending on the version of redhat (or linux in
general).  Mine was in:

/usr/lib/gcc-lib/i386-redhat-linux/egcs-2.91.66/include/

not, /usr/lib/bcc/include.  Their cc (or gcc) works fine since
when it is installed, the paths to the headers are "burned into"
the binaries.

My somewhat simple solution was to add

PROCFLAGS=INCLUDE='(/usr/include,/usr/lib/gcc-lib/i386-redhat-lin
ux/egcs-2.91.66/include/)'

as the last line in demo_proc.mk.  Then, they compiled right
away.

Sorry for the inconvienence.

September 29, 2000 Jaspreet -- Thanks for the question regarding
      "chat using oracle", version version 8.1.6

      You Asked
hi!
i am currently working with a module, that is chatting.
i have a website, there is a button whose label is chat.
when a customer presses it, it should show a chat window, and
the list of agents that are online.
the customer selects an agent and a window opens in the agents
screen.
the purpose is, if a customer is having a problem with our
product he can directly talk(or chat) to the concerned
person(agent), who can sort out his problem online.

basically, we are into CRM.
this module is under our new product that is eCRM
so we need chatting done.

i am working in forms 6i and oracle 8i.

i would be grateful to u if u could help me out.

JASPREET

      and we said...
I would suggest looking into one of our partners for this sort
of software.  See

http://www.sideware.com/
I've evaluated their Dr. Bean software and it does what you
describe above and uses the Oracle8i database as well.
September 29, 2000 Balasubramanian -- Thanks for the question
      regarding "Migrating the database", version 7.3.4

      You Asked
Hi Tom,

Thanks for your reply for my previous question.

I have to migrate the database from oracle 7.3.4 from
oracle 8.0.

In this case, can i do migrate the database this way

1. Take the cold backup of datafiles, redo logfiles and
   control files of oracle 7.3.4

2. Create the oracle 8 database data dictionary
   i.e system tablespace (only system data file)

3. Startup the database in no mount stage.

4. Using backup & restore concept, recreate the control file
   of the new oracle 8 database using the old data files and
redo    log files.

Becos. it will be faster than Export/Import

Can you please clarify my approach or idea of doing this way.

I guess there will be some problems.

I am sure you will reply me.

Thanks & Regds
Bala

      and we said...
Please read the migration guide:

http://technet.oracle.com/doc/server.804/a58243/toc.htm
from cover to cover.  It goes over ever step you need to take,
every method you can use.

You do not do it in the above fashion.  You will use the
migration utility.  I urge you to read that document fully
before attempting to do anything.
September 29, 2000 sujata -- Thanks for the question regarding
      "tables its usage", version 7.x

      You Asked
Dear Thomas

how can i get the report like below on tables and its usage.

TablespaceName   UserName   TableName  Allocated    Used
                                    K/M           %
Remaining space
(K/M) or %

in fact i have used dba_tables, i couldn't get the output. could
you help me in getting the solution for the above report.

with regards
sujata

      and we said...
Well, if you ANALYZE the tables (do not just do that unless you
understand the changes to the optimizer that will happen!), this
information can be gotten from DBA_TABLES.  It'll tell you
blocks and empty_blocks.

Perhaps a better way is to use the utilities I make use of in my
show_space script and use PLSQL to generate your report.
Show_Space presents information like this:

ops$tkyte@ORA734.US.ORACLE.COM> create table emp as select *
from scott.emp;

Table created.

ops$tkyte@ORA734.US.ORACLE.COM> create table dept as select *
from scott.dept;

Table created.

ops$tkyte@ORA734.US.ORACLE.COM>
ops$tkyte@ORA734.US.ORACLE.COM> exec show_space( 'EMP' )
Free Blocks.............................0
Total Blocks............................2
Total Bytes.............................16384
Unused Blocks...........................1
Unused Bytes............................8192
Last Used Ext FileId....................1
Last Used Ext BlockId...................3991
Last Used Block.........................1

PL/SQL procedure successfully completed.

ops$tkyte@ORA734.US.ORACLE.COM> exec show_space( 'DEPT' )
Free Blocks.............................0
Total Blocks............................2
Total Bytes.............................16384
Unused Blocks...........................0
Unused Bytes............................0
Last Used Ext FileId....................1
Last Used Ext BlockId...................3993
Last Used Block.........................2

PL/SQL procedure successfully completed.

Shows the total blocks, unused blocks (never used), blocks on
the freelist and so on.  You can see that at:

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
...

September 29, 2000 akthar -- Thanks for the question regarding "How
      can I schedule(JOB) sqlplus Statement ", version 8.1.5

      You Asked
HI Tom,

I want to include my export sql script in Job so that I can
schedule it at regular interval. Below given is my sql script

column today new_val dt
select to_char( sysdate, 'ddmmyyyy' ) today from dual;
host exp username/password@xxx owner=username file=exp_prod.dmp
record ='y' rows='y' grants ='y' indexes='y' constraints='y'

How can do that , pls help me . I dont want to use Os schedulers
like NT-Scheduler or Cron in unix environment.

Or anyother Database level ways that I can schedule it.

thanks in advance.

      and we said...
We would use Oracle Enterprise Manager to schedule that job.
See

http://www.oracle.com/ip/deploy/database/system_mgmt/index.html?content.html
for more info.
Review & Followup

      Rating: 2
More on
      Enterprise Manger Job  February 21, 2002
Reviewer:
      Michael Chang  from CA, USA
Is it possible to fire up a second job base on the result of first job.
For example, I would like to run Veratas Netbackup to tape base on the
completion of Oracle backup to disk.

September 29, 2000 Lorenzo -- Thanks for the question regarding
      "Arrays in Oracle 8.0.5 / Mutating table error", version Oracle8
      Enterprise Edition 8.0.5.0.0

      You Asked
Tom:

Two questions:

1.-
  Can I declare an array or table in a pl/sql procedure in a way I can open a
ref cursor variable on it later?

I am not sure if our version of PL/SQL (8.0.5.0.0) supports such kind of
constructs.

If is no direct way, there are any useful workaround?

2.-
We get a mutating table error when selecting on a table from a row trigger on
the same table. That is well documented, and we get what we deserve, but:

First of all, if we define the trigger as before insert, we can do the select
without complaints from the server, but if the select if in any other trigger
(vg. before update) we get the mutating error. Do you know why?

On the same subject, I have heard that in some version of Oracle (8.1.5??? or in
any case higher than ours) there is a 'entitiy' called 'autonomous trigger' that
can do the job. Is that true or the one that said it to me was kidding? And, if
its true, can we emulate that functionallity in 8.0.5 ?

3.-
If the answer to question 1 is 'yes' and we can have tables or arrays I think we
can solve the problem in question 2 following the guidelines you give in a paper
about mutating table error, but in the case the operation we need to do on the
table is only select, is any easier way? (answer do not needed if the answer to
question two was positive enough.. :-)... )

Thank you, Tom.

   Lorenzo.

      and we said...
1) see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:139812348065
it demonstrates a method using Oracle8 object types (easy) and Oracle (any
version) PLSQL table types (little harder but doable)...

2) I assume you mean BEFORE INSERT|UPDATE FOR EACH ROW, not just BEFORE
INSERT|UPDATE (both will succeed in a BEFORE trigger, it is only the for each
row triggers that get mutating tables).

A SINGLE row insert is "special".  If you use "insert into t values ( .... )"
then the database KNOWS that the before insert for each row trigger is
EFFECTIVELY the same as the BEFORE INSERT trigger -- there is only 1 row that
can possibly be inserted -- hence the row trigger in this case is the same as a
before trigger.  Consider this:

ops$tkyte@DEV816> create table t ( x int );
Table created.

ops$tkyte@DEV816> create or replace trigger t_trigger
  2  before insert on t for each row
  3  begin
  4      for x in ( select * from t ) loop null; end loop;
  5  end;
  6  /
Trigger created.

ops$tkyte@DEV816> insert into t values ( 1 );
1 row created.

ops$tkyte@DEV816> insert into t values ( 2 );
1 row created.

ops$tkyte@DEV816> insert into t select 1 from dual;
insert into t select 1 from dual
            *
ERROR at line 1:
ORA-04091: table OPS$TKYTE.T is mutating, trigger/function may not see it
ORA-06512: at "OPS$TKYTE.T_TRIGGER", line 2
ORA-04088: error during execution of trigger 'OPS$TKYTE.T_TRIGGER'

So, since the database cannot tell if the select will return 0, 1 or more rows
-- we get the mutating table.  ONLY when we use VALUES can it make this
optimization for us.  An UPDATE can always affect >1 row so it never has a
"special" case.

Review &
      Followup

      Rating:
      3
  April 17, 2002
Reviewer:
      A reader

      Rating: 5
What about
      "After insert for each row"  July 24, 2002

Reviewer:  Santosh  from India
Then "After insert for each row" also should be a special case of "After Insert
Statement level" and table should not mutate if you try to read it. But it is
not happening...

September 29, 2000 Andy -- Thanks for the question regarding
      "Character sets", version 8.1.6

      You Asked
What needs to be done in order to store and retrieve
non-American/English characters in a column? i.e.: è,Ñ,ñ etc...

I've managed to store via CHR(164) function, but, when
retrieving via SQL*Plus, all I see is blank space. Via MSAccess,
I see the  (ascii 127) character.

Any information/links would be appreciated.

Thanks

      and we said...
See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:327817160881
for more info but basically:

o your database must be created or altered to support a
character set that supports 8bit data (eg: the default character
set on Unix is usascii7, a 7bit character set)

o your CLIENT must have an NLS_LANG setting to a character set
that supports 8 bit data as well.

Then, all should be OK.  On NT, your default NLS_LANG is 8bit
but it sounds like your database might be on Unix with 7bit.

With 8i you can change the character set after the fact from a
7bit to some 8bit character sets.  The above link will point you
to the documentation on that (chapter 3)
September 29, 2000 Navdeep -- Thanks for the question regarding
      "Determining the row locked ina table ", version Oracle8 Enterprise
      Edition Release 8.0.5.1.0

      You Asked
Tom,

I want to be able to figure out as to which rows in a table are
locked. I can get to know which table is locked in a database
using a join between dba_objects and v$locked_object. But How do
i get to the row level in that table.

Thanks
Navdeep

      and we said...
We do not keep a list of row locks anywhere.

We store the lock as an attribute of the data itself.  The only
way to find out if row "X" is locked is to attempt to lock it
yourself (via select ... from t where ... FOR UPDATE NOWAIT).
September 29, 2000 Kevin -- Thanks for the question regarding
      "Executing a Procedure from PL/SQL Dynamically", version 8.1.5.0.0

      You Asked
Sorry Tom you must be fed up reading questions about how to run
procedures and functions dynamically so, here's another one :)

Quite simply I have a list of Procedures contained within a
table and I have a main Procedure that uses this table as a
lookup, selects one of the Procedure name from the list i.e.
'WP210' and performs a few checks on it which I won't bore you
with.

What I then want to be able to do is to simply execute this
procedure from the current one, that's all!

I've tried building up a dynamic SQL statement (which I have
used successfully before but never in this scenario) and my
session keeps bombing with an  ORA-03113: End of File on
Communication Channel.

Here's the code I have at the moment. Any help would be much
appreciated.

IF lb_pre_ok = 'Y' THEN

   -- Open the cursor
   --
   li_sql_curs := DBMS_SQL.OPEN_CURSOR;

   -- Define the WP name in a variable
   --
   lv_curr_wp := 'WP' || TO_CHAR( lr_restart_rec.wp_id ) ||
'000.main';

   -- Assign the necessary commands to the SQL_TEXT variable
   --
   lv_sql_text := 'BEGIN ' ||
                     ' :lv_run_wp ; ' ||
                  'END;';

   DBMS_SQL.BIND_VARIABLE( li_sql_curs, ':lv_run_wp', lv_curr_wp
);

   -- Parse the statement
   --
   DBMS_SQL.PARSE( li_sql_curs, lv_curr_wp, DBMS_SQL.NATIVE );

   -- Now execute the WP
   --
   lv_rowcount_num := DBMS_SQL.EXECUTE( li_sql_curs );

   DBMS_SQL.CLOSE_CURSOR( li_sql_curs );

END IF; -- Check pre_id

Cheers.
Kev.

      and we said...
You cannot bind identifiers.  You can only bind where you could
put a character string constant.  For example, given:

select * from emp where ename = :x

I know I can use a bind variable there because I can code:

select * from emp where ename = 'KING'

Now, if I was given:

select * from :x;

I know I cannot bind there becuase I CANNOT code:

select * from 'EMP';

that does not work.

In your case, the solution is actually very easy, In 8.1.5 just
code:

begin
   execute immediate 'begin ' || lv_run_wp || '; end;';
end;

that is it -- one line of code is all you need.
Review &
      Followup

      Rating: 5
many
      thanks  September 23, 2001
Reviewer:  Ines
      Weinzierl  from Germany
I´ve tried so many things to start an Procedure dynamically from pl/sql (from
select ... from dual to whatever) - and the solution is so easy. :-)))

September 29, 2000 Daryl -- Thanks for the question regarding "Char
      to Varchar2 Conversion", version 8.0.5.2

      You Asked
I am attempting to convert fields in my database from char to
varchar2. What is the easiest and safest way to accomplish this
without losing any data and eliminating the "padded" spaces
created with the char datatype? Thanks!

Daryl Green

      and we said...
You'll need an ALTER and an UPDATE to do that, for example:

ops$tkyte@ORA8I.WORLD> alter table t modify ename varchar2(20);

Table altered.

ops$tkyte@ORA8I.WORLD> update t set ename = rtrim(ename);

14 rows updated.

ops$tkyte@ORA8I.WORLD>

September 29, 2000 ted -- Thanks for the question regarding "q:
      sqlloader and clob question", version 8.1.5

      You Asked
thomas:

1. how do you get around 4000 bytes limitation on input data
using sqlloader ?
2. with clob datatype, can I use instr function to find out the
character pattern ?
thnx in advacne as always
ted chyn

      and we said...
1) there is no 4000 byte limit. The default is 255 bytes but you
can easily override that via:

...
fieldN   char(10000),
...

for example.

2) with clobs, you can use

dbms_lob.instr( clob_column, 'pattern')

yes.


Subject | Article | Last Updated (East coast time)
To do an export . | article only | Sep 30, 2000 09:30 am
Perfomance Tunning in Oracle | article only | Sep 30, 2000 09:34 am
Mutating Tables And Triggers | article only | Sep 30, 2000 09:49 am
Regarding triggers. | article only | Sep 30, 2000 10:01 am
Archive logs on raw partitions | article only | Sep 30, 2000 01:06 pm
Time difference between an export to /dev/null and to real dump file. | article only | Sep 30, 2000 02:36 pm
Will Exporting from another machine take more time than on the same machine | article only | Sep 30, 2000 02:40 pm
Computing total hours | article only | Oct 01, 2000 10:13 am
Developer 6 -- connecting to personal Oracle | article only | Oct 01, 2000 10:37 am
Size of redo log files, datafiles | article only | Oct 01, 2000 01:49 pm
Passing parameters | article only | Oct 01, 2000 02:07 pm
Oracle parallel server | article only | Oct 02, 2000 10:17 am
Setting up Database | article only | Oct 06, 2000 02:29 pm
Table Names in Oracle Stored Procedures | article only | Oct 06, 2000 02:56 pm
SEQUENCES IN TRIGGERS | article only | Oct 06, 2000 03:03 pm
invalid sys objects after Oracle Install | article only | Oct 06, 2000 03:06 pm
oracle version | article only | Oct 06, 2000 03:13 pm
temp tablespace | article only | Oct 06, 2000 05:49 pm
Command Host unable to open document file | article only | Oct 06, 2000 06:00 pm
Using exp/imp to detect corruption | article only | Oct 06, 2000 06:09 pm
Problem in taking export of 8.1.5 database from 8.1.6 client | article only | Oct 06, 2000 07:57 pm
row(s) 1 - 21 of 21
September 30, 2000 Sham -- Thanks for the question regarding "To do an export .", version Oracle 8.0.6.0
You Asked
Hi Tom

I am a junior DBA ( and new in this company ) and have been
assigned to do a database installation  setup on a new machine .
I need help to do this : -

1.How do i do an export on "NON SYSADM" object ?
How do i go about getting the list of non-sysadm objects ?

2.Create a database with structure only ?
Is below the correct way of doing an export for this from the
production database .......

file = /usr/users/oracle/exp_TEST.dmp
log = /usr/users/oracle/exp_TEST.log
buffer = 102400000
full=Y
rows=N
compress = n
direct = y
consistent = y

I hope you are able to help me on this and i really appreciate
your help .

Thank You
Sham
and we said...
1) I do not know what you mean by "non sysadm" object.  If you
mean non sys objects -- you are OK as SYS objects are *never*
exported in any circumstance.  If you mean non-system objects --
then you'll do an export by "owner=username" or
tables=(t1,t2,t3...)

2) Those parameters will work although direct=y and consistent=y
are necessary as
  o you will not be reading the tables so direct=y will not be
    used
  o you will not be reading the tables so consistent=y is
    not necessary.
September 30, 2000 Vladimir -- Thanks for the question regarding "Perfomance Tunning in Oracle", version 8i
You Asked
Hi Tom
I would like if you can help me:
1.What kind of tools are available for Performance Tuning in
Oracle?
2.When you have an "In Clause" inside of a "where clause" is it
faster to "in" or "not in"?

thanks Tom
and we said...
1) OEM (Oracle Enterprise Manager) has the Performance Pack.
See
http://www.oracle.com/ip/deploy/database/8i/index.html?tuning.html
for more info.

2) in general, IN would be (probably, maybe, your mileage may
vary)....

It is not a very fair comparision as IN cannot be written as NOT
IN and NOT IN cannot be written as IN.   They are apples and
oranges and cannot be compared -- they are not interchangeable.

IN would probably be faster because:

  where x in ( 1, 2, 3 )

can easily use an index to find x = 1, 2, or 3 and combine the
results.  Whereas:

  where x not in ( 1, 2, 3 )

cannot use an index (the domain of values of X is totally
unknow, we would have to full scan)....

However, if the predicate was:

 where x in ( 1, 2, 3 ) and y = 5;

vs

  where x not in ( 1, 2, 3 ) and y = 5;

and y was indexed -- it would not make a difference....
September 30, 2000 RaviShekhar -- Thanks for the question regarding "Mutating Tables And Triggers", version 8.1.5
You Asked
Dear Mr. Tom,

I want to know

1.  what is meant by Mutating Tables And Triggers?
2.  Can we create them or they are system made?
3.  If we can create them then how to create and where to use
them?

Thanks,

RaviShekhar
and we said...
From the application developers guide:

Mutating Tables: A mutating table is a table that is currently
being modified by an UPDATE, DELETE, or INSERT statement, or it
is a table that might need to be updated by the effects of a
declarative DELETE CASCADE referential integrity constraint. The
restrictions on such a table apply only to the session that
issued the statement in progress.

You cannot create a mutating table -- rather it is an error
condition.  You want to avoid them (as they are quite useless
states to be in).

See the application developers guide, section on using triggers,
for more info.
September 30, 2000 Farhad -- Thanks for the question regarding "Regarding triggers.", version 8.1.6
You Asked
Hi Tom,
    Thanx for ur prompt reply on Collections. Well, now can u
please tell me that suppose if in a trigger I have specified a
when clause in my trigger(row level) and suppose if my when
clause condition doesnot staisfy, so in that case will my
trigger still fire or fail?
        One more question is that How to convert my form in
Developer6 into web based form?

Q.  If I want to generate randon number in Oracle* through
sequences then in that case how to go about it? What is the use
of noorder clause in sequences?

       Hoping for your prompt reply.

 Thanx,
 Farhad.
and we said...
The trigger will not fire.  that is the purpose of the WHEN
clause on the trigger -- to make it so it only fires when it
needs to.

You do not have to do anything to convert your form to web based
forms -- you only need to get the developer server.  The same
fmx files you use in client server mode work on the web.  see
http://www.oracle.com/tools/forms/
for more info.

You cannot generate a random number via a sequence. See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:831827028200
for some methods to do that.

The use of the noorder clause simply means that sequence
requests are handled in a non serial fashion.  You get a
sequence number but it might not be "in order".  Sequences are
simply a method of generating a surrogate key but they imply no
ordering and do not promise to not generate gaps.
September 30, 2000 Jayaraman -- Thanks for the question regarding "Archive logs on raw partitions", version 8.1.6
You Asked
Hi Tom
We are setting up OPS on IBM RS/6000. The config. is 2 IBM
RS/6000 nodes and an ESS for storage.Is it all right to have
archive logs on the raw partitions on the ESS, as whatever
little material on OPS that we can find only talks about archive
logs on mounted file systems? But as the first instance that
comes up must have access to all the redo logs and archive logs,
how do we achieve it as in a cluster config. only the node on
which the file system is mounted can access it.Is it also
possible to specify log_archive_duplex_dest to a device like a
tape library? Kindly bear with us as we may pose some more
questions to you very soon regarding this. Thanks in advance.
Regards,
Ashok
and we said...
The first instance that comes up needs access to online redo --
we NEVER need archive logs for instance recovery -- they are
only ever used for media recovery.

Archive logs must be and can only be on cooked (not raw) file
systems.

It would be very impossible to have archive on raw as the names
of the archive must be dynamic and we generate "files" of redo
-- not partitions of it (like we do with online redo).
September 30, 2000 Ravi -- Thanks for the question regarding "Time difference between an export to /dev/null and to real dump file.", version 8.0.4.4
You Asked
Dear Tom,

Q1: I would like to find the size of export dump without the
creation of dump file using dd, mknod and /dev/null. When it
writes to the /dev/null, I hope there is no I/O involved. My
question is, For a Mid size database (eg: 50G), what would be
the time difference for the completion of export and the real
export to the dump file. Will they both take same time or the
/dev/null approach might take less time.

Thanks for the invaluable support through the net.

Regards
Ravi
and we said...
They will take virtually the same amount of time unless your
disks are really slow.  Much of exports time is spent getting
things like views and such (very little IO on those to the dmp
file).

It'll take almost as much time to size the dmp file as to
actually create it.

I used

$ mknod exp.pipe p
$ wc < exp.pipe > exp.size &
$ exp .... file=exp.pipe

Unless there is some seriously large contention for the disk --
I would just do the export -- it takes almost as much time to do
it to "nothing" as to do it.
September 30, 2000 Ravi -- Thanks for the question regarding "Will Exporting from another machine take more time than on the same machine", version 805
You Asked
Dear Tom,

Our production database 805 runs in Solaris 2.5. We are not able
to export on that machine, because our export file exceeds 2.0G.
 We will upgrade the Solaris to 2.6 later. But on Monday, we are
planning to build a test database on another machine with export
and import only, due to some constraints(not with cold and
hotbackup).

We are planning to orginate the export from the test machine(OS
:  Solaris 2.6 and oracle same version). Both the test machine
and the production machine are located closely in the same room
in a network.

Will orginating the export from another server, increase
considerable time in completion of export than exporting from
the same machine where the db runs. The size of the completed
export would be around 6G before compression. Should I need to
set the env. variable TWO_TASK and will it increase performance.

Thanks for the answers.

Regards
Ravi
and we said...
You can exp more then 2gig.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:32412348052
for how.  I do it all of the time (2 times a week in fact).
 the release of solaris is not relevant -- export won't write to
a file that is >2 gig if that file supports seeking.  To work
around that, we write to a pipe.

You will want to export on the machine with the database and
then transfer the files to the other instance.
October 01, 2000 zam -- Thanks for the question regarding "Computing total hours", version oracle8
You Asked
Hi

I have one problem and I need u r help to solve it.

I want to create one table for keeping the information of
timestamp for employee
i.e

empno    att_date    time_in        time_out     total_hr
----------------------------------------------------------------
101    01-jan-2000    08:00:00    14:00:00    total_hr
102    01-jan-2000    08:30:00    15:00:00    total_hr
…….
……
……

So I want to know that what should be the data type of time_in
,time_out,and how to get the total_hr value

I want to insert all the values from the form.  I am using
oracle8 and forms 6

If u did not get my doubt so please write me I will repeat it
againg.

Thank u very much

You're sincerely
ZAM
and we said...
Well, in the above, time_in and time_out would be of type DATE,
total_hr would be of type NUMBER and one of:

time_in
time_out
total_hr

would be a derived field (not a real field, not physically in
the table).

I would probably have the table contain time_in and time_out and
create a view of the table that selected:

..., time_in, time_out, (time_out-time_in)*24 total_hr, ....

The user should not supply total_hr -- but only the time in and
time out, total hours is a simple function of that data....
October 01, 2000 mohan -- Thanks for the question regarding "Developer 6 -- connecting to personal Oracle", version 6
You Asked
Sir,
Can you please tell me how to connect Forms ver6 to Personal
Oracle 8.0.4 on Windows 98

Regards,

mohan
and we said...
You would have Forms 6 installed into its own Oracle Home I
presume.  In that case, you need to configure the tnsnames.ora
file in the forms6 Oracle home and setup the listener.ora file
in the 8.0.4 database oracle home and run the sqlnet listener so
that forms can use Net8 to connect to the database.

So, a listener.ora might look like:

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS_LIST =
        (ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC0))
      )
     (ADDRESS_LIST =
        (ADDRESS=(PROTOCOL=TCP)(HOST=tkyte-del)(PORT=1521))
      )
    )
   )

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = PLSExtProc)
      (ORACLE_HOME = c:\Oracle)
      (PROGRAM = extproc)
    )
    (SID_DESC =
      (GLOBAL_DBNAME = tkyte816)
      (ORACLE_HOME = c:\Oracle)
      (SID_NAME = tkyte816)
    )
  )

Where you of course will replace the hostnames and such with
your info.

the tnsnames.ora entry might look like:

tkyte-del.us.oracle.com =
  (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = tkyte-del)(PORT=1521))
          (CONNECT_DATA = (SID = tkyte816))
            )

where again, the hostname and sid will be different (it will
reflect YOUR configuration).

Once the Net8 listener is running -- you should be able to
connet using:

user/pass@tkyte-del.us.oracle.com

(of course you can change the name tkyte-del.us.oracle.com to
whatever you want)
Review & Followup
Rating: 3
Is there a short-cut in starting oracle listener,database at the same time? December 19, 2001
Reviewer: Godwin from Ghana
Hi Tom,
 This time i find it difficult to get you hence to search for similar questions
in your archives and where there is match i have to ask for clarrification.
Please bear with me.

 My problem is that am using oracle8i release 8.1.5.0.0 with dev 6 on windows98
os platform.
After the installation on one PC, i am told to perform the ff operations
everytime before the database can work:
steps:
1.Ensure that the Personal Oracle database is not running. if it is running shut
it down.
2. start the oracle listener.
3. start the client utility(ie sqlplus8,form builder ..)

Tom, this not like the version7 where by if you start the sqlplus then the
listener and the personal oracle database also start at the same time.
Is there not a way out of having to face this tedious routine?
Q2. On the other PC however,if i start the database the erro ORA-205 Aappears
that the database is mounted hence the operation fails.How do i overcome this
problem?

Rating: 3
Is there a short-cut in starting oracle listener,database at the same time? December 19, 2001
Reviewer: Godwin from Ghana
Hi Tom,
 This time i find it difficult to get you hence to search for similar questions
in your archives and where there is match i have to ask for clarrification.
Please bear with me.

 My problem is that am using oracle8i release 8.1.5.0.0 with dev 6 on windows98
os platform.
After the installation on one PC, i am told to perform the ff operations
everytime before the database can work:
steps:
1.Ensure that the Personal Oracle database is not running. if it is running shut
it down.
2. start the oracle listener.
3. start the client utility(ie sqlplus8,form builder ..)

Tom, this not like the version7 where by if you start the sqlplus then the
listener and the personal oracle database also start at the same time.
Is there not a way out of having to face this tedious routine?
Q2. On the other PC however,if i start the database the erro ORA-205 Aappears
that the database can not be mounted hence the operation fails.How do i overcome
this problem?

October 01, 2000 Vijay -- Thanks for the question regarding "Size of redo log files, datafiles", version 8.1.6
You Asked
1. How do I find out how much space is filled in online-redo log
files.

2. How do I find out how much space is filled in the current
datafiles.

3. What are the important X$tables.
and we said...
#1) I am not aware of any method to tell where you are pointing
currently inside of an online redo log file.  Since we use them
n a circular fashion -- they never really "get full".  You can
review your alert.log file to see how frequently they switch but
the concept of "filled" doesn't really apply to online redo.

#2) A query such as:

ops$tkyte@DEV816> select substr( a.file_name,
  2                   instr(a.file_name,'/',-1)) file_name,
  3         round(bytes/1024/1024) mBytes,
  4         round(nvl(b.free,0)/1024/1024) Free,
  5         round( (a.bytes-nvl(b.free,0))/1024/1024) used
  6  from dba_data_files a,
  7      (select sum(bytes) free, file_id
  8         from dba_free_space
  9        group by file_id ) b
 10  where a.file_id = b.file_id(+)
 11  /

FILE_NAME                MBYTES       FREE       USED
-------------------- ---------- ---------- ----------
/system01.dbf               452          6        446
/rbs_ts_01.dbf               55          0         55
/rbs_ts_02.dbf             1135          0       1135
/rbs_ts_03.dbf               91          0         91
/rbs_ts_04.dbf               92          0         92
/rbs_ts_05.dbf               42          0         42
/users.dbf                  471          0        471
/scats_data.dbf              10         10          1
/scheduler_data.dbf         184        183          2
/scheduler_idx.dbf           17         16          1
/flows_data.dbf             109          0        109
/flows_idx.dbf               10         10          1
/portal_data.dbf            492          0        492
/drsys.dbf                 2000          0       2000
/pkt_data.dbf               123          0        123
/pkt_idx.dbf                118          0        118

16 rows selected.

will do that.

#3) in my opion -- there aren't any.  I use the v$ tables.  x$
tables, being wholly undocumented and changeable from dot
release to dot release, are only useful in rare circumstances --
if ever.  The V$ views, built mostly on top of the X$ tables --
are what you want to master.
October 01, 2000 -- Thanks for the question regarding "Passing parameters", version 2000
You Asked
How do I passing parameters to Form
and we said...
on the command line, via:

name=value

You have to build a parameter item in your form in order to be
able to accept one.  This is done in the development environment
by selecting parameters item and clicking "+" to add one.  Give
it a name and or type in the property sheet.
October 02, 2000 sundar -- Thanks for the question regarding "Oracle parallel server", version 8i
You Asked
Hi Tom,
Thanks for ur reply reg Hash partitioning.I need another help
from u.I am going to implement OPS in IBM RS6000 with version
816.Since its a high availability database we are planning to go
online backup.Here we are going to go for RAW file systems and
the problem we had is where we can store archivals.My doubt is
1)whether we can store arichivals in RAW FILE systems.
2)if we store whether it will affect our performance.
3)In case ,if recovery ,whether we can  recover if we store in
RAW file systems
4) Oracle suggesstions to store archives in NFS of two instances

   in OPS.if we store in NFS whether it will degrade our
performance.Kindly help us how we can store arichivals in OPS
with RAW file systems
and we said...
You cannot store archive in RAW.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:869627443171
for details.

Archive cannot every be on raw.  Archive is a series of
dynamically created files.  If archive could be (and it cannot)
be stored on raw -- you would need an "infinite" number of raw
partitions....

We recommend that archive redo is archived OFF of the machine at
some point (recent point -- after the archive is generated) to
ensure you can recover.  If the machine blows up with the only
copy of archive -- you'll lose data.
October 06, 2000 mario -- Thanks for the question regarding "Setting up Database", version 8.1.6
You Asked
Is there any literature to manually create a database on NT4.0

Many thanks

Mario
and we said...
See
http://technet.oracle.com/doc/oracle8i_816/nt.816/a73008/ch5.htm#1004964
Which is the NT Admin Guide.
October 06, 2000 Seetharaman -- Thanks for the question regarding "Table Names in Oracle Stored Procedures", version Oracle 8
You Asked
Hi Tom,

  Greetings!...

  Is there any tool available for us to reverse engineer the stored Procedures,
Functions in the database ?...

  It should exactly return me all the tables, views or synonyms used in the sps
or functions if I pass the sp or function name into the package...

  Pls lemme know at the earliest... and have a fun filling weekend.

Thanks in advance

regards

Seetharaman Srinivasan
and we said...
See the view USER_DEPENDENCIES (or all_ or dba_).

This view shows everything that a object references as well as everything that
references an object.
October 06, 2000 KATEY -- Thanks for the question regarding "SEQUENCES IN TRIGGERS", version 7.3.4
You Asked
I am trying to allocate a column the next number from a
sequence,
by using a database triggers as follows.

create or replace trigger k
before insert on history
for each row
begin
 declare
     seq_exam varchar2(7);
    begin
        seq_exam := 'R'||k_exam_id.nextval;
    end;
end;

where k_exam_id is a sequence already created.

I get the following error
--------
-----------------------------------------------------------------

5/9      PL/SQL: Statement ignored

5/36     PLS-00357: Table,View Or Sequence reference
'K_EXAM_ID.NEXTVAL'
         not allowed in this context
and we said...
begin
  select 'R' || k_exam_id.nextval INTO seq_exam from dual;
end;

You must SELECT a sequence -- not assign it.
October 06, 2000 Kelli -- Thanks for the question regarding "invalid sys objects after Oracle Install", version 8.1.6
You Asked
Last night our ISP installed Oracle and created our database
instance for us.  When we logged on this morning, we noticed
that there were about 41 invalid objects owned by sys.
Basically seemed to be procedures and packages, like dbms_alert,
etc.  I compiled them all with no problem.  Why would we run
into a situation like this after an install?  Is this something
we should be concerned about.  Is there any reason we should be
concerned that this was a bad install?

Thanks
and we said...
No, it is not a bad install and it is perfectly normal and those
packages would revalidate themselves the first time they were
used.

After an install or upgrade -- many things will be invalid in
the database.  This is normal and to be expected.  The status of
invalid simply means that "something they referenced was changed
and they need to be recompiled before they are executed again".

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:774025935172
for a further discussion on this topic.
October 06, 2000 GAURANG -- Thanks for the question regarding "oracle version", version 8.1.5
You Asked
hi tom,
is there anyway to get oracle version like oracle7 or
oracle8. in v$version it is difficult.
I want ony one word 'ORACLE8' OR 'ORACLE7'.

Thanks
and we said...
select substr(banner,1,7)
  from v$version
 where banner like 'Oracle%';

returns Oracle7 or Oracle8 in releases 7.1 through 8.1 at least.
October 06, 2000 wallacel -- Thanks for the question regarding "temp tablespace", version 8.1.6
You Asked
Tom:

if i select count(0) from v$transaction and got 0,
does that mean all content in temp tablespace is empty?
mine is not empty, why?

can i drop temp tablespace at any time during db is up?

Regards,
and we said...
I do not understand your attempt to connect a count of
transactions with the use of temp space.  Temp space is used by
many things -- including sorts done by selects.

See v$sort_usage.

Temp space is allocated once and then retained and managed by
the system -- to avoid dynamic space management.  Once allocated
-- it will appear "used" but v$sort_usage will tell you what is
really used and what is not.  It is normal and expected for temp
to appear "full".  It is not full, just allocated and ready for
use.

You can drop temp anytime you want.  People who have their temp
tablespace pointing there will fail when they need to sort.
October 06, 2000 Lorenzo -- Thanks for the question regarding "Command Host unable to open document file", version Forms(32 bit) version 5.0.6.8.0
You Asked
Tom:

We were trying the opening of documents from a form with the command:
host(<string>);
beign <string> a string with the full name of the document (p.ej.
'c:\siesta\el_arte_de_dormir.doc')
It works on the MS-DOS shell if we start the sell from the 'Start' Menu of
windows (Windows NT 4.0, by the way). The command we issue is
prompt><string>
(ej. prompt>c:\siesta\el_arte_de_dormir.doc )
and the doc. opens

But if we launch it from forms it says that does not understand the command.

Then we tried with the command start, issuing in our form:
host('start' || <string>);
beign <string> a string with the full name of the document (p.ej. host('start
c:\siesta\el_arte_de_dormir.doc')

And, the same, forms open a DOS window that complains, quickly dissappears and
the document does not get opened. If we open the DOS window from Start menu of
Windows and issue the command it works OK.

As last resource, we created a MS-DOS batch program (*.bat) that accepted the
document name as parameter. The batch only issued 'start <string>' (being
<string> the doc name). And with a little plumbing to handle the case in which
the parameter passed had blanks inside (like filename 'This documento.doc') it
worked OK FROM FORMS with the instruction:

host('batch_file_Name ' || <string>);

As we did not like that, we pulled other resources and after no little research
we could download a package and a dll from Oracle with the function
START_DOCUMENT (or sth. like that) that worked OK.

But working that way has the drawback that in the instalation of the deliverable
we must copy the dll in the directory [oracle]\bin. We also do not like that, as
our customer has strict security measures in client PCs and we should try not to
write in that directory, as usually is protected.

So, one solution implies a call to a batch program, which name should not be
fully qualified (because the application is supposed to be able to be installed
in any directory), and we should get into the annoyance of having a registry
variable for that. Other way may be to construct at runtime the file in a known
location, but it does not sound very well to me (messy or 'chapucero' as we say
in Spain)

The other implies to install a downloaded dll into a possibly protected
directory, so the installation get complicated (and although the dll is
downloaded from Oracle, we should get it officially from the Oracle support of
our customer, which is going to be another pain in the neck).

After so long preliminars the questions are:

1.- Is there any way to use the host command to launch the file without all
those problems?

2.-Why do you think calling directly 'start' from the form (with 'host') did not
work and calling 'start' through an intermediate
batch program worked?

Thank you.
and we said...
Try this command:

host( 'cmd /c "C:\Doc\Thomas Kyte\Desktop\todo.txt"',
       NO_SCREEN );

The command processor goes through all kinds of hoops to start a program --
looking at the extension.  We simply call "exec()" and if the OS won't run it -
it won't run it.  cmd.exe looks "harder" to find something to run and uses the
associations of the extension to a program to build a real command to run.
Review & Followup
Rating: 5
Huss September 25, 2003
Reviewer: hussein from Egypt
thankx tom
 it helps me alot :)

Rating: 5
How to run dos command under host December 31, 2003
Reviewer: abdoul rahaman from Saudi Arabia
Really uncle tom is amazing man

October 06, 2000 Randy -- Thanks for the question regarding "Using exp/imp to detect corruption", version 8.1.5
You Asked
You mentioned in a previous answer that you do a full database
export and using imp show=y to scan tables for corruption.  I
understand the need for a full db export to validate the SYSTEM
ts, but is it necessary to just do a single schema, that
contains only a handful of tables?

I would like to only export/import this tiny schema to check its
tables, w/o having to export the entire db.  Will this method
work this way for detecting corruption?

Thanks.
and we said...
It will detect any table level issues with all of the tables in
that schema and it will find any logical or physical corruption
in the section of the data dictionary it will be touching (not
the whole thing).

So, it'll tell you that your application tables are good and the
section of the data dictionary it hit is OK.

The import step is to test the integrity of the export file --
you need only do that if you intend on using the dmp file as a
backup of sorts for anything (occasional "dropped" table and
such)...
October 06, 2000 Rajinikanth -- Thanks for the question regarding "Problem in taking export of 8.1.5 database from 8.1.6 client ", version 8.1.6
You Asked
RDBMS Version: Oracle 8.1.5
Operating System and Version: Solaris 7
Error Number (if applicable): EXP-00037
Product (i.e. SQL*Loader, Import, etc.): export
Product Version: 8.1.6

I am trying to take export of Oracle 8.1.5 database from the
remote machine using oracle 8.1.6 client. It just fails with the
following error message

exp userid/passwd file=h.dmp full=n owner=userid

Export: Release 8.1.6.0.0 - Production on Thu Oct 5 18:53:50
2000

(c) Copyright 1999 Oracle Corporation. All rights reserved.

Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 -
Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production
EXP-00037: Export views not compatible with database version
EXP-00000: Export terminated unsuccessfully.

In oracle newsgroups i was told to copy the exp file from 8.1.5.
So i copied the exp file of 8.1.5 to 8.1.6 client and named it
as exp815.

When i run exp815 in 8.1.6 client i got the following error
message.

$ exp815 -?
ld.so.1: exp815: fatal: libucb.so.1: open failed: No such file
or directory
Killed

Please point me where i am making a mistake and how to run
export against my 8.1.5 database from 8.1.6 client without
installing a seperate 8.1.5 client software.

Thanks and Regards
Rajini
and we said...
You must run the 8.1.5 export tool against the 8.1.5 database --
not the 8.1.6. The 8.1.6 imp tool can read that dmp file but it
cannot be used to produce it.

You need a full 8.1.5 client install to run the 8.1.5 client
tool.  You cannot just copy a single binary (everything is
dynamically linked).  8.1.6 and 8.1.5 are very different binary
releases and are not compatible with each other at the library
level.


Subject | Article | Last Updated (East coast time)
DB Security and Roles | article only | Oct 07, 2000 09:31 am
databse buffer cache | article only | Oct 07, 2000 09:42 am
Need to if any record exist | article only | Oct 07, 2000 09:45 am
Developing Web Application | article only | Oct 07, 2000 09:47 am
Several queries! | article only | Oct 07, 2000 10:17 am
Block Size of database | article only | Oct 07, 2000 10:18 am
Re:Developing Web Application | article only | Oct 07, 2000 10:21 am
Developing Multilingual Application | article only | Oct 08, 2000 09:22 am
choice of jsp engine | article only | Oct 08, 2000 09:25 am
batch update qn | article only | Oct 08, 2000 12:40 pm
small doubts | article only | Oct 08, 2000 02:49 pm
Tablespace | article only | Oct 09, 2000 06:35 am
UTL_SMTP - Package | article only | Oct 09, 2000 07:11 am
Cursor with parameter | article only | Oct 09, 2000 07:22 am
how to use oracle server with servlet? | article only | Oct 09, 2000 07:25 am
Is database level constraints good for OLAP ? | article only | Oct 09, 2000 07:28 am
A question | article only | Oct 09, 2000 09:17 am
Sorts.. | article only | Oct 09, 2000 09:41 am
Estimate | article only | Oct 09, 2000 09:44 am
BFILE size and configuration Wizard | article only | Oct 09, 2000 09:55 am
Table partition | article only | Oct 09, 2000 10:00 am
How can I use javascript file with PL/SQL HTML stored procedures ? | article only | Oct 09, 2000 01:36 pm
error in connecting to database from my jsp | article only | Oct 09, 2000 02:23 pm
Best Practices to insert records into tables in 24x7 setup. | article only | Oct 09, 2000 10:11 pm
SGA | article only | Oct 09, 2000 10:13 pm
Mutiple instance Or mutiple schema | article only | Oct 11, 2000 11:00 am
export/import | article only | Oct 11, 2000 11:03 am
sharing an instance vs using separate instances? | article only | Oct 11, 2000 11:30 am
oracle client | article only | Oct 11, 2000 01:21 pm
database triggers | article only | Oct 11, 2000 01:23 pm
dbms_obfuscation_toolkit | article only | Oct 11, 2000 01:26 pm
job scheduling | article only | Oct 11, 2000 01:35 pm
Diff. between Oracle 8 and Oracle 8i | article only | Oct 11, 2000 03:31 pm
Tape Issue | article only | Oct 11, 2000 03:36 pm
sortinf by date | article only | Oct 11, 2000 04:02 pm
how to make procedure working in unix environment | article only | Oct 11, 2000 07:22 pm
row(s) 1 - 36 of 36
October 07, 2000 -- Thanks for the question regarding "DB Security and Roles", version 8.1.6
You Asked
Can two roles access two separate views with the same name?

Role 1 granted to user A wants to see View x

Role 2 granted to user B wants to see View y

They both want to call it View z and get View x or View y back
according to which role is granted to a given user.

This did not seem possible unless a synonym was created at the
user level.

I set up some proof of concepts and public synonyms were out.

You should be able to access a resource via a synonym in your
schema as long as the role grants you privileges to acces that
resource.  It looks like there would need to be a script that
would grant the role to a user and then add the appropriate
synonym.
and we said...
Roles do not govern a namespace -- they only govern what is
available to each user.

You are correct in your analysis that user level synonyms would
be necessary.  User A would need role1 and a "create synonym z
for x".  User B would need role2 and a "create synonym z for y".
 Synonyms are for name resolution, roles are only for
authorization.
October 07, 2000 ahmed -- Thanks for the question regarding "databse buffer cache", version version 8
You Asked
hi tom,
my question is that when a user used cursors for fetching the
data and the cursor is placed in the uga(am i right)and theri is
no place to store data in uga, then how it is possible that a
cursor in the uga fetch data.or if used data base buffer cache
then what is the method of addressing. please answer.
and we said...
Parts of the cursor will be in the PGA and UGA and shared pool
(depending on the server mode -- dedicated server or MTS will
dictate where components are stored).  The current sessions
specific data being in the UGA as it is the specific to the user
(pga and uga are fairly synonymous in dedicated server mode,
very different in MTS mode).  The parsed cursor and query plan

The result set itself (pointed to by the cursor but not really
part of the cursor) will be in either the sort (temp) area or
the database buffer cache -- depending on how the data is
accessed.  All cached blocks will be in the buffer cache -- if
there is a sort or aggregate or the need of temporary result
sets, then the sort area (which is in the pga and/or uga
depending on the server mode -- dedicated server or MTS again)
will hold much of the result set.

In many cases -- the data is "no where" as we do not fetch the
entire answer before getting the first row -- we typically get
the data as it is requested whenever possible.
October 07, 2000 Hassan -- Thanks for the question regarding "Need to if any record exist ", version 8i
You Asked
Currently using select count(*) int :hostVar from table_name
where (put your where clause here).  This is causing a full scan
when all I need is to know where such a record exist or not.
and we said...
Thats not alot of information to go on.  I would need to see the
where clause and table definition (including indexes) to
determine if an index can be used or not.

In any case, a better way to write an "existence" query is as
follows:

 select count(*) into :hostVar
   from DUAL
  where exists ( select NULL
                   from table_name
                  where <predicate> );

That will full scan DUAL (1 row) and run the exists predicate
once.  Exists stops as soon as it finds the first row (so if
many match - it finds the first and stops).

If the where clause cannot make use of an existing index
efficiently in the exists clause though -- it'll still full scan
table_name.  If it does that -- provide the table structure,
indexes on the table, the predicate used and the optimizer mode
being used.
Review & Followup
Rating: 5
April 03, 2001
Reviewer: Helena Markova from Bratislava, Slovakia

October 07, 2000 Dev -- Thanks for the question regarding "Developing Web Application", version Oracle8i 8.1.5
You Asked
HI!Tom,

   I am planning to use Java for developing the
application.Could Jdeveloper and Oracle Appilication server be
the right products to be use?

Thanks in advance

Dev

**************Tom Response*************

>>not really -- what language/technologies are you planning on
>>using to code this
>>in?  what are you planning on building? etc...

>>use
http://osi.oracle.com/wa/ask/owa/ask_tom_pkg.main
to ask >>in the future
>>please.  helps me keep track.

*********** REPLY SEPARATOR  ***********

On 10/6/2000 at 1:00 PM dev sawant wrote:

>Hi!Tom
>
>    I am developing a Web Application by using Oracle8i 8.1.5
Enterpraise
>Edition for Windows NT.I have already loaded Oracle8i
database.Can you
>please tell me what more products do I need for my application.
>
>Thanks in advance
>
>DEV
>________________________________________________________________
_________
and we said...
iAS would be better then OAS as it is the future direction.  iAS
is built on Apaches technology rather then Spyglass Mosaic as
OAS was.

But in short -- yes, jdeveloper + app server would be an
appropriate (but not the only) choice.

Now you have to decide if you want to use servlets, ejbs, jsps,
or what to implement your application....
October 07, 2000 zaibi -- Thanks for the question regarding "Several queries!", version oracle 7.3
You Asked
Hi,

I have following queries,

1. I want to export my database on tape using tape drive.  How
can I do that.What will be the syntax for export.Also after
exporting the database , how can I import specific tables from
that tape on some other machine.( note: I am using sun solaris
2.6 with oracle 7.3)

2. Does oracle 8i support forms 4.5. I want to install oracle 8i
on my sun solaris 2.6 server.Tell me forms 4.5 can be connected
to oracle 8i or not?

3. I want to create several users for particular operations.
The users and their operations are:

user      operation
-----     ---------------
dbstart   database startup
dbshut    database shutdown
exp       database export
imp       databse import
lsr       listener startup

Tell me how can I restrict each user to do only specific task.
What are the privileges  I  should assign to each user.

Thanks.
and we said...
1) There are only 2 parameters that you need to change to do
this :

1. FILE - The name of the tape device you are exporting to
           e.g. /dev/rmt0

2. VOLSIZE - The amount of data that can be written to one tape.

 If the entire export file will fit onto a single tape, then a
volsize of 0 (variable length) can be used. If the resultant
export file is larger than a single tape, then volsize  needs to
be set accordingly e.g. exp <other options> volsize=<size>M.
Please note, there is a 4 Gigabyte limit to the volsize
parameter.

EXAMPLE OF EXPORTING DIRECTLY TO TAPE

A full database export to a QIC 150 (150 Megabytes capacity) to
a tape device "/dev/rmt/0m",where the resultant file is 200M
would be exported using the following syntax :

$exp userid=system/manager full=y file=/dev/rmt/0M volsize=145M

The volsize is set to 145M, even though the tape is a QIC 150
because there may not be exactly 150M of tape on the volume.
Once the export utility has written <volsize> to the tape, it
will  prompt for the next tape:
 "Please mount the next volume and hit <ret> when you are done."

To import from the resultant export on tape, the following
commands would be used :

$ imp userid=system/manager full=y file=/dev/rmt/0M volsize=145M

2) forms 4.5 can be used with 8i yes.

3) You cannot divide the startup/shutdown privs into 2 different
accounts -- they either can startup + shutdown or not (see the
admin guide for all of the details).

You can grant EXP_FULL_DATABASE to someone for the export.
You can grant IMP_FULL_DATABASE to someone else for the import.

The listener is outside of the scope of the database and
starting the listener is not a restricted capability (although
shutting down the listener can be).  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:826826941359
for details on those steps.
October 07, 2000 Madhuri -- Thanks for the question regarding "Block Size of database", version 7.3.4.0.0
You Asked
I have a technical query regarding Oracle database block size.
If I import a database from a 4KB block size to a 2KB block size
what could be the repurcussions? I am importing the dump from
Oracle 7.1.3.0.0 on Sun Solaris to Oracle 7.3.4.0.0 on Hp-UX.
and we said...
The only side effect will be that the database with the 2k
blocksize will need more space then the database with the 4k
blocksize.  There is more block overhead in the 2k database.
Since an export/import will result in an overall "smaller"
initial database (everything is as compact and organized as it
possibly can be) you probably won't notice until the database
has been running for a while (until some space management starts
taking place).
October 07, 2000 Dev -- Thanks for the question regarding "Re:Developing Web Application", version Oracle8i 8.1.5
You Asked
Tom,
    I am planning to use applets,servlet and jsp to develop the
web application.Can you help me to decide between
IAS + JDeveloper or Apache web server + Tomcat considering
oracle8i as my database.

Thanks in advance

Dev

***********Tom Response*************

iAS would be better then OAS as it is the future direction.  iAS

is built on Apaches technology rather then Spyglass Mosaic as
OAS was.

But in short -- yes, jdeveloper + app server would be an
appropriate (but not the only) choice.

Now you have to decide if you want to use servlets, ejbs, jsps,
or what to implement your application....

*************Dev ASked****************

HI!Tom,

   I am planning to use Java for developing the
application.Could Jdeveloper and Oracle Appilication server be
the right products to be use?

Thanks in advance

Dev

**************Tom Response*************

>>not really -- what language/technologies are you planning on
>>using to code this
>>in?  what are you planning on building? etc...

>>use
http://osi.oracle.com/wa/ask/owa/ask_tom_pkg.main
to ask >>in the future
>>please.  helps me keep track.

*********** REPLY SEPARATOR  ***********

On 10/6/2000 at 1:00 PM dev sawant wrote:

>Hi!Tom
>
>    I am developing a Web Application by using Oracle8i 8.1.5
Enterpraise
>Edition for Windows NT.I have already loaded Oracle8i
database.Can you
>please tell me what more products do I need for my application.
>
>Thanks in advance
>
>DEV
>________________________________________________________________

_________

-----------------------------------------------------------------
---------------
and we said...
iAS has apache with apaches servlet engine.  So, in this case,
it would be no different.

it would not be ias + jdeveloper vs apache + tomcat, it would be

ias vs apache+tomcat

(jdeveloper would be needed in both as the development tool).
Since ias has in it the apache components -- they are the same.

ias and its release of apache and supporting software is the
supported configuration -- so I would recommend using that.
October 08, 2000 Prakash -- Thanks for the question regarding "Developing Multilingual Application", version Oracle 8.1.5
You Asked
I am developing multilingual application in which database is
supposed to store in both ENGLISH and ARABIC.
On client i changed parameters DEVELOPER_NLS and USER_NLS to
ARABIC_QATAR.AR8MSWIN1256. Now the user interface accepts in
both languages and can save in database too. But when i query
from database i see all question marks for ARABIC characters
typed. Numbers in ARABIC are saved properly. On server while
installing i selected the Product Language ARABIC and English.
Is there anything else which i have skipped or forgotten to do.
Or is that i got to install database again?
Kindly get back
Thank you
and we said...
What is the character set of the database?  If you intend to
store more then 1 language in there, it should be something like
UTF8.  Otherwise -- everything is mapped into the characterset
of the database as you created it.

select * from nls_database_parameters

will tell you what you created the database with.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:327817160881
it'll point you to the NLS guide as well.  In chapter 3 of that
guide, you'll find how to change the character set of a database
after creation IN SOME CASES.  You may have to recreate the
database.
October 08, 2000 Ramakrishnan -- Thanks for the question regarding "choice of jsp engine", version oracle8i
You Asked
our host has the option of servlet exec and tomcat for
running jsp. our database will be on oracle8i.

which is the preferred one in terms of performance metrics
and future roadmap.
and we said...
I would use the servlet engine incorporated in with the Apache
version we ship with iAS as that would be the supported
configuration.

We use Apache JServ.
October 08, 2000 Reji -- Thanks for the question regarding "batch update qn", version 8.1.6
You Asked
Tom:
    I have 120 rows of data to be inserted into a table
    and I have a batch size of 25.  How can I restrict the
    commit process so that if the 5th batch of inserts fails
    then rollback the entire set.

    I am using statement level batching ( setting the batchsize
    to the statement).

    TIA
    Reji

Additional Info:

    I have an account table which has 20 columns ( no LOBs ).
    datatypes are DATE, NUMBER and VARCHAR2.  I have a JDBC
    application processing usage data and the rated data shoudl
    be loaded into our db for invoicing.

    -Thx
    -Reji
and we said...
Ok, in the jdbc application issue:

    conn.setAutoCommit(false);

so that statements do not commit by default.  Now, you must
issue your own

   conn.commit(); or conn.rollback();

to commit work.  JDBC (probably copying from odbc) "auto
commits" -- effectively disabling the transaction control
databases are supposed to be known for.  I know why ODBC does it
(invented by SQL Server and SQL Server has a terrible time if
locks remain open for any duration of time) but don't know why
jdbc does.
Review & Followup
Rating: 5
Also gives you a chance to check number of rows affected April 05, 2001
Reviewer: Harrison Picot from Haymarket, VA USA
As Tom points out, there are benefits in turning auto commit
off, maybe you want to check the number of affected rows on
an update: " intVar_rowCount = pstmt.executeUpdate();"
and then make sure that intVar_rowCount is not bigger than you want before you
commit. Or if it is less than you want,  maybe you want to trigger an error
message here.

October 08, 2000 rahim -- Thanks for the question regarding "small doubts", version 8
You Asked
1.how save images in oracle table? by which command
2. I want to create a procedure in which
   i want to pass two parameters i.e, one is table name
   and another is rownum.
Based on the tablename the row should be deleted with rownum.
3. I want to create a procedure in which
   i want to pass two parameters
   first parameter is tablename and another is newtable name.
   the procedure has to create a newtable.
4.The main difference between function and procedure
5. i want a query to delete a row by using a rownum value

Sir, Kindly clarify my doubts.
and we said...
1) depends on the client and the circumstances.  What is the
client and what are the circumstances??? (eg: I am writing a
java/jdbc application that will connect over a network and I
need to read a file from the local client machine and store it
in a BLOB on the remote database).  Followup with another
question just about that (or search my site for BLOB.  I have
tons of examples there).

2) Rownum is a variable thing.  There is no such thing as "row
5" for example.  You cannot delete by rownum.  Since you only
gave me a server version of "8" (not 8.0.5 or 8.1.6... ) I don't
know exactly what release you had but dynamic sql in 8.1.6 would
be as easy as:

   execute immediate
    'delete from ' || p_table_name || ' where rownum = :n'
   using p_rownum;

But be aware that unless p_rownum = 1, this will NEVER delete
any rows and if p_rownum = 1, it'll always delete the first row
it happens to find.  Rownums would not be a good thing to use.
You want to use a rowid maybe or better yet -- the PRIMARY KEY.

3) Again, not knowing the release -- it could look like this in
8i:

  execute immediate 'create table ' || p_new_table ||
                    ' as select * from ' || p_old_table;

for example.  If you have 8.0, search my site for
execute_immedaite to see a function I use to do execute
immediate before 8i.

4) a function is a procedure that can additionally return a
value.  Instead of coding:

   ...
   foo( x, y );
   ...

a function can:

   ....
   some_variable := foo( x, y );
   ....

5) cannot be done correctly.  rownums are assigned to rows on
the fly in a query -- there is no such thing as "row 5" in a
database.  Don't attempt to use rownum for this -- it'll only
lead to bugs in your application as you delete the wrong row(s).
October 09, 2000 Kin Sun -- Thanks for the question regarding "Tablespace", version 8.1.6
You Asked
to create a tablespace, should a large data file (5000M), or
multiple data files (5 x 1000M) be assigned. thanks.
and we said...
It is a matter of choice.

My personal preference is to not use files that exceed 2
gigabytes in size and to use files that are some integer
multiple of my extent size (i always use locally managed
tablespaces with UNIFORM allocation) plus 64k (for the bitmap).
Search for locally managed on my site for more info on that
feature.

2gig is one of those magic sizes -- there are utilities that
cease to function on files larger then that.  If you have a
single large file and it gets damaged, you have that much more
to recover.  Things just get unwieldy after 2 gig.  Since each
tablespace can have 1022 datafiles - limiting them to 2 gig
isn't going to constrain the size of your database too much.  It
is the rare database that needs to use larger files to avoid
having too many files in it.  Using multiple smaller files will
allow you to possibly spread the IO for this tablespace across
many physical devices as well.

It is OK to use one giant file -- if you are comfortable with
it.  Both approaches work.
October 09, 2000 Prem -- Thanks for the question regarding "UTL_SMTP - Package", version 8.1.5.0.0
You Asked
Hi

I am having Oracle 8.1.5.0.0 Version Installed in our Solaris
machine, I want to use UTL_SMTP package. Where can I get the
package is any download is available for this package. Please
let me how to install the UTL_SMTP package into my database. Is
any upgrade is need for my database?.

Thanks
prem
and we said...
You cannot put UTL_SMTP (an Oracle8i release 2 package for
database version 8.1.6) into an 8.1.5 instance.

You would need to have 8.1.6 with java installed for this to
function.

If you have the java option, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:255615160805
for how to do this in 8.1.5 without utl_smtp.
Review & Followup
Rating: 5
UTL_SMTP - Package August 20, 2002
Reviewer: Ramesh Vadlamani from Harrisburg,Pa, USA
Hi,

This review is so very good. I am just the beginner in Oracle and i am trying to
send create a procedure which
will send a automated message from server to the me.

this helped me a lot. and thanks a lot for maintaing a
good website.

RAMS

Rating: 4
UTL_SMTP November 05, 2002
Reviewer: Ramesh Vadlamani from Harrisburg, USA
Dear Tom,

Thank for your detailed suggestions, actually i have posted my review about this
UTL_SMTP before, but after i saw my own review i recognised that i missed so
many words and letters in my typing,so i am doing this once again.

Anyway..s thanx for your suggestions.

Thanks
Ramesh.

October 09, 2000 G. -- Thanks for the question regarding "Cursor with parameter", version 2000
You Asked
Running time of following cursor is 1 second:
FOR REK IN
(SELECT CA.DISTINCT CUSTOMER_ID, DN.DN_NUM
 FROM CONTRACT_ALL CA, CONTR_SERVICES_CAP CS, DIRECTORY_NUMBER
DN
 WHERE (DN.DN_NUM LIKE '7032347%') AND (CA.CO_ID=CS.CO_ID) AND
(CS.DN_ID=DN.DN_ID))
     LOOP
       ...
     END LOOP;

Type of  DN_NUM is VARCHAR2(20).

Running time of the same cursor with parameter is 10-20 minutes:
DECLARE
           NNN VARCHAR2(10);
BEGIN
           NNN:= '7032347%';
FOR REK IN
  (SELECT CA.DISTINCT CUSTOMER_ID, DN.DN_NUM
   FROM CONTRACT_ALL CA, CONTR_SERVICES_CAP CS,DIRECTORY_NUMBER
DN
   WHERE (DN.DN_NUM LIKE NNN) AND (CA.CO_ID=CS.CO_ID) AND
(CS.DN_ID=DN.DN_ID))
       LOOP
       ...
       END LOOP;
END;

What is the problem?
and we said...
(you really have a column named distinct?  that is probably not
a really good thing but...)

Query Plans go alooonnnggg way to solving these mysteries.  they
would really help.  Otherwise -- I'm guessing.

My guess:

When you use the hard coded value -- it sees that

dd.dn_num like '7032347%'

is very discriminating -- it can see the % is very far into the
string and that 7032347... can be used very effectively against
the index, returning a small number of rows.

In the second case, it sees:

dn.dn_num like :x

and not knowing anything about :x, it is assuming that :x is '%'
and will return lots of rows.  Hence, it is probably not using
an index.

So, what I might suggest is you use a hint in this case to help
it rethink its plan.  Lets say that the index on DN_NUM is
DN_NUM_IDX, try:

  (SELECT /*+ INDEX( DN DN_NUM_IDX ) */
          CA.DISTINCT CUSTOMER_ID,
          DN.DN_NUM
     FROM CONTRACT_ALL CA,
          CONTR_SERVICES_CAP CS,
          DIRECTORY_NUMBER DN
    WHERE (DN.DN_NUM LIKE NNN)
      AND (CA.CO_ID=CS.CO_ID)
      AND (CS.DN_ID=DN.DN_ID))

Making sure to have a SPACE between /*+ and INDEX (plsql tends
to remove the first character after the /*+, hence /*+INDEX
would become /*+NDEX which is not valid....
October 09, 2000 mitesh -- Thanks for the question regarding "how to use oracle server with servlet?", version oracle8.0
You Asked
hi tom,

we are developing website using servlet.we want to maintain the
data base using oracle enterprise edition.I have knpwledge of
pl/sql.so how can i use OEE with servlet?
and we said...
You would get an application server such as OAS, iAS or Apache
with a servlet engine (say tomcat or jserv) in it and write java
code.  Thats for 8.0.

In Oracle8i release 3, there is a servlet engine right in the
database that can run java servlets or even PLSQL servlets.
October 09, 2000 David -- Thanks for the question regarding "Is database level constraints good for OLAP ?", version version 8.1.5
You Asked
I know some ERP software dont use constraints, why?
Is database level constraints good for OLAP system?
please explain.

Thanks
and we said...
In general, vendors who try to make database agnostic software
tend to use the database as a big VSAM file -- like it was a
bunch of files with indexes and thats all there is.  They do not
use primary/foreign keys, constraints, triggers, stored
procedures and the like because they have to go for the lowest
common denonimator.  They use plain vanilla SQL (select columns
from T <simple where clause>) and avoid the use of functions or
advanced features.  They do this to be portable.  They end up
reimplementing all of this logic in their application.

Database level constraints are excellent for OLTP systems --
since OLAP is typically "read only", I do not see the connection.
October 09, 2000 Vinh -- Thanks for the question regarding "A question", version 8.0.4
You Asked
Hi Tom,
I want you give me an advice for a following problem:
- We intend developing a system for query words or phrases that
have same meaning. For example: When i submit a query criterion
as "advice", the system can find out some words have same
meaning like " advice, recommendation, consultation...". Of
course, these words are in Vietnamese, not English.
- Now, i don't know whethe Oracle supports these feature. Please
tell me some information about the problem.
Thanks a lot.
Vinh
and we said...
This sounds like a job for interMedia text (aka "context").

This will do a keyword full text index that allows for
searching.  As well, you can setup a thesaurus so that a search
for advice will find all of those words above as well.  The
searching works with all languages.

Also, in addition to using a thesaurus for synonym-searching (as
the you requested), you can also exploit a thesaurus to search
for related search terms, broader search terms, or even narrower
search terms.

Note that interMedia Text comes with a sample thesaurus in
English only.

See
http://technet.oracle.com/doc/oracle8i_816/inter.816/index.htm
for more details.
October 09, 2000 Vittal -- Thanks for the question regarding "Sorts..", version 8.1.6
You Asked
Why do I see a negative number for SORTS column in V$SQL for a
particular SQL?
and we said...
It would mean that lots of sorts have been performed and this
number has wrapped around and gone negative.  They are storing
this in a signed 16bit number internally.

for exmaple, if you run the following:

begin
  for i in 1 .. 10000 loop
     for x in ( select * from dual order by dummy ) loop
         null;
     end loop;
  end loop;
end;
/

select sql_text, sorts from v$sql
where sql_text = 'SELECT *   FROM DUAL ORDER BY DUMMY'
/

about 4 times -- you'll find that sorts goes negative, run it 4
more times and it'll go positive.  It wraps at 32k.
October 09, 2000 Sarosi -- Thanks for the question regarding "Estimate", version 7.3.4
You Asked
Hi !
Can you tell me the way, how can i estimate a size of rows
that will fit in a data block?
I couldn't understand the formula (Step 3) from the Oracle7
Server Administrator's Guide:

Space used per row (rowspace)
=
MIN(UB1 * 3+UB4+SB2, rowsize)+SB2

I can use MIN() function in a SELECT statement only, and MIN()
has only one parameter.

Thank you very much!
and we said...
it is "psuedo code".  You would pick the maximum of that set of
values. It is wrong actually -- it should be the MAX of that,
not the min (documentation bug).

IMHO -- The only TRUE way to get accurate average row lengths
for YOUR data is to load some representative sample of it (from
0.1% to 10% depending on the size of the final table) and
analyze it -- then the avg_row_len will be in the data
dictionary for you.

I've never seen a formula arrive at a good, accurate estimate.
October 09, 2000 julien -- Thanks for the question regarding "BFILE size and configuration Wizard", version 8.1.6
You Asked
Hi,

I'm trying to evaluate my future db size and i want to kown how
much space a external bfile use : This is just a pointer and not
the exact size of the file that its refers.

I want to know if there is an Oracle configuration Wizard that
tolds me ifi had to buy 2 or 4 proc, ... regarding to my
database  size and the number of concurent transactions

Thanks,

Julien Nitot
and we said...
It'll be a function of the length of the filename and directory
name.  It appears that there is a 24 byte fixed overhead +
length(directory) + length(filename) needed for a bfile.  Test
case:

ops$tkyte@DEV816> create table t ( x bfile );
Table created.

ops$tkyte@DEV816> begin
  2   for i in 1 .. 1000 loop
  3      insert into t
  4      values
  5      ( bfilename( 'DIR1', 'foo.dat' ) );
  6   end loop;
  7  end;
  8  /
PL/SQL procedure successfully completed.

ops$tkyte@DEV816> select length('DIR1')+length('foo.dat') from
dual
  2  /

LENGTH('DIR1')+LENGTH('FOO.DAT')
--------------------------------
                              11

ops$tkyte@DEV816> analyze table t compute statistics;
Table analyzed.

ops$tkyte@DEV816> select avg_row_len from user_tables where
table_name = 'T';

AVG_ROW_LEN
-----------
         35

35-11 = 24 bytes.  To show the directory and file name
contribute to the overall length:

ops$tkyte@DEV816> drop table t;
Table dropped.

ops$tkyte@DEV816> create table t ( x bfile );
Table created.

ops$tkyte@DEV816> begin
  2   for i in 1 .. 1000 loop
  3      insert into t
  4      values
  5      ( bfilename( 'DIR1 longer longer longer', 'foo.dat' )
);
  6   end loop;
  7  end;
  8  /
PL/SQL procedure successfully completed.

ops$tkyte@DEV816> select
  2    length('DIR1 longer longer longer')+length('foo.dat')
  3    from dual;

LENGTH('DIR1LONGERLONGERLONGER')+LENGTH('FOO.DAT')
--------------------------------------------------
                                                32

ops$tkyte@DEV816> analyze table t compute statistics;
Table analyzed.

ops$tkyte@DEV816> select avg_row_len from user_tables where
table_name = 'T';

AVG_ROW_LEN
-----------
         56

 32 is 21 more then 11 (previous length) and 56 is 21 more
then 35 (previous avg row len)...
October 09, 2000 Narendra -- Thanks for the question regarding "Table partition", version 8.1.6
You Asked
Hi Tom,
Thanks for the previous help.
I have some doubt regarding table partition.
1.How to avoide the rollback entry when use below statement
Insert into T1
SELECT * FROM T2
(tABLE t1 AND T2 ARE OF SAME STRUCTURE,BUT t1 HAVE FOUR
PARTITION ON DATE COL.)aS table T2 is very large,and during
insert rollback segment error occurs that can not extend the
certain Rollback segment.
I want to avoide rollback entry during that transaction.
Thanks
NP
and we said...
try

insert /*+ APPEND */ into t1
select ......

Make sure you understand what this does first.  It is similar to
a direct path load of the table.

See the concepts manual
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c21dlins.htm#880
for details.
October 09, 2000 Alan -- Thanks for the question regarding "How can I use javascript file with PL/SQL HTML stored procedures ?", version 4.0.7
You Asked
  When I want to protect the javascript source code from the
client I put it in *.js file and put this file in the same
directory where the *.html exists. But in my case I don't have
a *.html file, I have a stored PL/SQL procedure that generates
the HTML page when the client request it. So how can I do to
reference this external *.js file. Because I'm trying to put
this file in the same virtual path of the procedure and nothing
happens
and we said...
Your choices are two fold:

1) do not use the same virtual path.  The virtual path you have
defined to run PLSQL cannot retrieve files -- it is defined to
run PLSQL.  If you use a slightly different virtual path --
it'll work just fine.

2) have the PLSQL return the javascript as well.  If you are
using a URL like:
  http: //hostname/foo/plsql/mystuff.js

and mystuff.js is currently a file, simply create a package
called mystuff, have a procedure called JS in it.  and have JS
return the text that is currently in the file.
October 09, 2000 arjun -- Thanks for the question regarding "error in connecting to database from my jsp", version 8i
You Asked
i try to connect to oracle driver (classes12.zip) which supports
jdbc2.0.

when i try to use scrollable resultset in jdbc 2.0 from my jsp
program...i am getting an error.

The error is as follows:

No variable TYPE_SCROLL_SENSITIVE defined in interface
java.sql.ResultSet

pl. help me out.....

regards

Arjun
and we said...
You need 1.2 JDK compiler as well.  I have both a jdk 1.1 and
1.2 compiler and when I use the 1.1:

$ javac Employee.java

Employee.java:32: No variable TYPE_SCROLL_INSENSITIVE defined in
interface java.sql.ResultSet.
    Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
                                                    ^
Employee.java:33: No variable CONCUR_UPDATABLE defined in
interface java.sql.ResultSet.

ResultSet.CONCUR_UPDATABLE );
                                                    ^
Employee.java:40: Method last() not found in interface
java.sql.ResultSet.
    if ( rset.last() )
                  ^
3 errors

But when I set my path to use a 1.2 jdk compiler:

$ set path = ( /usr/java1.2/bin $path )
$ rehash
$ javac Employee.java

no problems....

You need a compiler upgrade for 1.2
October 09, 2000 -- Thanks for the question regarding "Best Practices to insert records into tables in 24x7 setup.", version 8.1.5
You Asked
I would like to know the best practices to insert or Updates
tables in 24x7 setup.

There are two schemas in the application.
First schema stores all the data which is viewed by 24x7 Users.

Second schema has all the data which needs to be inserted or
updated to first schema.

How do we insert or update first schema quickly from second
schema ensuring 24x& users will not feel the delay (caused due
to locks , etc ..) during DML operations.
and we said...
In Oracle -- readers are NEVER blocked by writers.  You can
safely insert/update the data that others are reading and will
have no cause for concern.  It is one of our best features.

Update the data whenever you want -- It will not affect the
people who view the data.  Size your rollback sufficiently large
and do the operation as one big transaction if you need and the
users will only see the data BEFORE the update and then after
(you don't need to incrementally commit the changes).
October 09, 2000 Keith -- Thanks for the question regarding "SGA", version Oracle8i
You Asked
Tom,

Our database's memory allocation is grossly undersized. I know I
will need to increase the sort_area_size,shared_pool_size, and
db_block_buffers. Is the a parameter I will have to adjust for
the SGA as a whole?

Thanks.

Keith M. Cutler
and we said...
No, you adjust the individual parameters to size the SGA.

You do not specify an OS but you might have to increase your
shared memory parameters on Unix before doing this.  See your OS
specific admin guide for details.
October 11, 2000 Amy -- Thanks for the question regarding "Mutiple instance Or mutiple schema", version 8.1.6
You Asked
Dear Tom,

Thanks for your huge help!!

When I port database from SQL SERVER/NT to Oracle/UNIX, I find
every database is small and no communicating  each other. I
think there are two ways to port them.
One is creating a schema for each of them on the same instance.
The other is creating each instance on the same computer box. Is
that right? I am not sure which one  gains performance. To my
understund, first one do not need seperate SQL*plus libary and
save space. However, it may make network busy since we use one
listener. Or we may use more than one listeners?

Thanks again.

Amy
and we said...
I would definitely use 1 database with 1 instance with many
schemas.

Each Oracle instance will have somw amount of overhead
associated with it -- the SGA, the processes and so on.  Running
many instances on a single machine duplicates lots of that
stuff.

The listener is involved in getting the conversation going in
the first place and then is out of the picture.  You can run
more then 1 listener per instance if you choose but in general
it will not be necessary.

Go for 1 database with 1 instance.
October 11, 2000 wallacel -- Thanks for the question regarding "export/import", version 8.1.6
You Asked
Tom:

I have a user name test_exp default tablespace exp_tablespace.
and user test_imp default tablespace imp_tablespace.

1.when i export in user mode all table belong to test_exp and
imp it use test_imp, all tables imported by default go to
exp_tablespace although test_imp's default tablespace is
imp_tablespace. am i right?

2.if i want to import it to imp_tablespace, the only thing
i need to do is revoke user test_imp's quota in exp_tablespace.

3. now i use alter table xxx move tablespace imp_tablespace.
alter index yyy rebuilt tablespace imp_tablespace to move
table and index , can you tell me how to move lobindex and
lobsegment?

Regards,
and we said...
1) the tables will go into  the tablespace they came from -- if
that tablespace exists and if the user importing into has the
ability to create objects in there.  Else the objects will go
into that users default tablespace.

So, if test_exp has all of its objects in exp_tablespace and
test_imp imports it -- they will be created (if possible) in
exp_tablespace and if not possible -- in imp_tablespace.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:47812348053
for how to control this better.

2) see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:47812348053
3) see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:378418239571
...
October 11, 2000 Rick -- Thanks for the question regarding "sharing an instance vs using separate instances?", version 7.3.4.2, 8.0.5, 8.1.6
You Asked
Tom,
I'm curious if having apps share an instance (separate schemas)
is a common practice? We do some of it here (we have some small
OLTP apps sharing instances, DSS apps sharing others) but there
are issues; different software packages may be ok under the same
version of the dbms when you start but eventually separate
instances may be required for app/dbms compliance (i.e. you may
want to upgrade the dbms and that may be ok for certain apps but
not for others), availability (downtime for one could mean
downtime for all), contention, etc.

On the other hand, for small apps, a separate instance per app
may be overkill in terms of resources (e.g. $$). And you end up
having to administer a larger quantity of instances; 20 small
instances vs 5 larger, shared instances for example (i.e.
viewing 20 alert logs vs 5, patching 20 instances vs 5, etc).
And multiple instances per UNIX machine will consume available
machine memory more quickly (ever have to balance the
"processes" init parameter between multiple instances on
a machine?).

Ideally, in terms of performance, availability, etc., you'd
probably go with a single app per instance and have that sole
instance on a single UNIX machine, but the dollar cost to do
that prevents us from having that arrangement.

Any feedback is appreciated. Thanks in advance.
-Rick
and we said...
There are two cases to consider here in my opinion:

o things that you buy from 3rd parties (commercial off the shelf
COTS) software.

o things you've built.

For "things you've built", I would definitely go with 1 database
-- many schemas.  I myself work on a database where we have
about 40 in house apps we run.  They all run in the same
database.  We upgrade them all at the same time and correct any
abnormalities as well.  I've never had to take down an instance
due to an application needing the database to come down -- I do
not see how one (or two, or a dozen) apps could cause downtime
for the entire instance.

As for contention -- you have as much flexibility in a single
instance as in many instances to reduce contention (in fact, if
you are on a single machine, you have more ability to reduce
contention simply because you are consuming much less resources
then you would in a database/application scenario.   You can
still place datafiles in certain locations to reduce IO
contention.  You can use buffer pools to slice up the SGA.  And
so on.

For "things you buy", many times you are forced into a situation
where you have a database per application -- this is unavoidable
at times.  Some vendors will only support their product on
version x.y.z and even if it works on x.y.a, they won't answer
support questions.  I simply think of these databases as part of
that application (don't let anything but that application get in
there) and manage them as an overall part of managing that
application.  It is unfortunate but has no good solution.  I
would calculate the cost of managing the additional software,
increased hardware costs into the overall cost of the solution.
Typically on these instances, you only need to support backup
and recovery and with RMAN this is fairly straight forward.

So, all in all -- i would shoot for as few instances as
possible.  The ones you have great degrees of latitude on (your
developed software) you would definitely have in 1 (or as few as
possible) instances.  The others -- you would have a
database/application.
Review & Followup
Rating: 5
Yes! August 03, 2002
Reviewer: Dan from Yukon Territory, Canada
Thanks a response that speaks to my slothful nature....

I know my DBA workload probably doubles if the number of instances doubles...
but my workload is essentially unaffected if the number of objects in one
database doubles.  So I'm all for multiple apps in a single database.  Problem
is I get a lot of resistance from our contract developers (who lean on the
project managers) who want a database all to themselves for each system (plus
test databases etc...)

Now, I'm all for keeping developement systems seperate from production (big test
dataloads etc. might impact production instance).  But I've never understood the
rational for a seperate db for each little app.

This article give me a bit more ammo - thanks!

October 11, 2000 wallacel -- Thanks for the question regarding "oracle client", version 8.1.6
You Asked
Tom:

i installed oracle client in sun 2.7
under user X,
and then run sqlplus , everything works fine.

can other unix account y run oracle client as well?
what should i do to setup it?

Regards,
and we said...
The other account needs to simply:

o add $ORACLE_HOME/bin to their path
o set ORACLE_HOME in their environment
o either set ORACLE_SID or use @database in the connect string.
Review & Followup
Rating: 3
Oracle Client For SGI Irix May 06, 2002
Reviewer: Kalpesh from NJ USA
Hi Tom,
I need Oracle Client for SGI IRIX.
From where I can get that.
Please let me know.

Thanks

October 11, 2000 greeshma -- Thanks for the question regarding "database triggers", version 8.0.6
You Asked
hi! tom
 1)whenever a DML command acts on a table,a trigger fires and
data is popped up
in a temp table.i have a column in temp table which is not from
the
base table into which i send a standard value of 'W'.my
requirement
is to send 'W' if my p_no (varchar2) column value starts with
'1%'
and 'P' if p_no value starts with '7%'.
2) i have a trigger fired if a dml command acts on base table.
before popping up the data in temp table i take care that a
particular data
is popped up in temp table by using
IF (:NEW.COL='F') THEN
if inserting then
INSERT INTO............
this  trigger is in use in production database for nearly one
month.
this table populates millions of records per day.but i saw some
40 records
 in the last two days where  col <>'F'. what could b the reason?

thankx for ur help
and we said...
1) the trigger can contain:

    insert into TEMP
     ( c1, c2, ....., cn )
    values
    ( ....., decode(substr(:new.p_no,1,1), 1, 'W',
                                           7, 'P',
                                              '?' ), .... );

That will look at the first character of the p_no column and if
it is 1, insert W, if 7 insert P, else insert ? (you need to put
whatever you want there)....

2) let me see the real trigger -- that snippet won't tell me.
October 11, 2000 wallacel -- Thanks for the question regarding "dbms_obfuscation_toolkit", version 8.1.6
You Asked
Tom:

i can't find dbms_obfuscation_toolkit in my system,
do i need to run something to install it?

Regards,
and we said...
You need to install

catobtk.sql

found in $ORACLE_HOME/rdbms/admin using SVRMGRL when connected
as SYS or INTERNAL.  These encryption packages are not installed
by default
October 11, 2000 raghava -- Thanks for the question regarding "job scheduling", version 8.0.6.0
You Asked
i have few temp tables in a database called 'X' into which data
is poplated by different triggers.now i want move this data from
temp tables from database 'X' to another set of temp tables on
different database 'Y' on different server,
every ten minutes and the moved data has to b deleted from the
first set of temp tables.pl.help me do it
thankx tom
with regards.
and we said...
You could write a small plsql procedure that looks like:

create procedure move_it
as
begin
  for x in ( select rowid rid, t.* from T ) loop
     insert into T@y values ( x.c1, x.c3, ... );
     delete from t where rowid = x.rid;
  end loop;
end;
/

declare
  l_job number;
begin
  dbms_job.submit( l_job, 'move_it;', 'sysdate+1/24/60*10' );
end;
/

Or, perhaps you could use:

create procedure move_it
as
begin
 set transaction isolation level serializable;
 insert into t@y select * from t;
 delete from t;
end;
/

(the isolation serializable ensures you only delete rows  you
inserted -- not any new rows that you haven't moved yet)
October 11, 2000 Rupali -- Thanks for the question regarding "Diff. between Oracle 8 and Oracle 8i", version 8.1.5
You Asked
Dear Tom,

Often people like to ask about the difference between oracle 7.3
and oracle 8 but i really want to know the difference between 8
and 8i.

Similarly,  Tell me if there is any other diff. between 7.3 and
8.0 inspite of the following -
1) U can create ur own types.
2) Nested Tables.

Regards,

Rupali
and we said...
see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
it covers all of that.
October 11, 2000 zaibi -- Thanks for the question regarding "Tape Issue", version oracle 7.3
You Asked
Hi,
Please answer following queries.

1. How can I take multiple exports on a single tape without
overwritings.

2.Is there any name for the export file  formed on tape (we
don't mention the name of file while exporting on tape, just
device).

3.If on a single tape there are  three exports taken on day1,
day2 and day3. How can I import the export taken on day2 only.
and we said...
You would write to the tape without rewinding.  Unix operating
systems typically incorporate device characteristics into the
file name used to access a tape device. The two to be concerned
with are “rewind” and “compression.” To append to a tape, you
must be configured with the non-rewinding tape device, so called
because when the device is opened and closed it stays at the
same position and does not automatically rewind. This is
typically a name with an n in it, such as /dev/rmt/0n. On AIX,
it is a name with a .1 or .5 suffix.

There is no name for a dmp file on tape.  Only cooked file
systems have filenames.  The tape is just a big device as far as
unix is concerned - you cannot "ls" it.

For #3, you'll have to imp .... show=y the first import and use
the non-rewinding tape device when you do that.  Then, you can
imp the second thing on the tape.

A tape is not setup to do the sort of random IO you want to do.
You might consider using more then 1 tape or using some other
storage media.
October 11, 2000 mitesh -- Thanks for the question regarding "sortinf by date", version oracle8.0
You Asked
In our Servlet program we are trying to sort the table using
'order by date', in which we have written:

    select * from tablename order by to_char(column
name,'DD/MM/YYYY');

but problem is that it give no result. so give me the proper
solution.
and we said...
are you telling me that it gives no rows back?

more likely you are saying "its not sorted right".  If that is
the case you just want to

select * from tablename order by column_name;

Don't to_char() the date field to sort it -- we sort dates.
Using the mask you did you are sorting by a character string
starting with the DAY and then the month and then the year.

Just lose the to_char().
October 11, 2000 Steven -- Thanks for the question regarding "how to make procedure working in unix environment", version V7.3
You Asked
Tom,

I hope you could help:

I have a procedure that is working on win sqlplus (on win98),
but can not work on unix sqlplus.    The syntax is working fine
for sql command, but something is missing for executing
procedure that I am confused about.    Here is the syntax:

------------------------------------------------------------
PATH=$PATH:/disk1/app/oracle
ORACLE_HOME=/disk1/app/oracle/database; export ORACLE_HOME
ORACLE_SID=WEBDB; export ORACLE_SID

sqlplus abc/bbb@WEBDB<<EOF

DECLARE

PROCEDURE WEB_VIEW_COUNT_PROC IS

CURSOR C_WEB IS
SELECT PROJ_NBR, RESOURCE_ID, HITS, PAGE_VIEWS, TIME_STAMP
FROM WEB_VIEW_COUNT
WHERE TRUNC(TIME_STAMP) LIKE SYSDATE;

V_PROJ_NBR VARCHAR2(10);
V_RESOURCE_ID VARCHAR2(10);
V_HITS  NUMBER;
V_PAGE_VIEWS NUMBER;
V_TIME_STAMP DATE;

BEGIN

OPEN C_WEB;
LOOP
FETCH C_WEB INTO
V_PROJ_NBR,V_RESOURCE_ID,V_HITS,V_PAGE_VIEWS,V_TIME_STAMP;
EXIT WHEN (C_WEB%NOTFOUND);
   INSERT INTO WEB_VIEW_COUNT_TOTALS

VALUES(V_PROJ_NBR,V_RESOURCE_ID,V_HITS,V_PAGE_VIEWS,V_TIME_STAMP)
;
   COMMIT;
END LOOP;
CLOSE C_WEB;
END;

EOF
------------------------------------------------

Hope you don't mind my question.

Thanks a lot,

Steve
and we said...
You are missing the slash needed to run the buffer:

...
END;
/
EOF

Put that in there and it'll create the procedure.

Note:

the procedure would be infinitely better if coded as:

PROCEDURE WEB_VIEW_COUNT_PROC
IS
BEGIN
   INSERT INTO WEB_VIEW_COUNT_TOTALS
   SELECT PROJ_NBR, RESOURCE_ID, HITS, PAGE_VIEWS, TIME_STAMP
     FROM WEB_VIEW_COUNT
    WHERE timestamp between trunc(sysdate) and
                            trunc(sysdate)+1-1/24/60/60;
END;

It is much smaller, more efficient, will be faster and can use
an index on timestamp if available (and is exactly the same as
yours above...)


Subject | Article | Last Updated (East coast time)
Tuning | article only | Oct 14, 2000 12:21 pm
Installation by Tar Ball | article only | Oct 14, 2000 01:48 pm
"Standard" edition differences | article only | Oct 14, 2000 01:53 pm
Please explain unrecoverable_time field in v$datafile. | article only | Oct 15, 2000 09:52 am
Bulk Binding vs. Cursors | article only | Oct 15, 2000 09:56 am
alter table | article only | Oct 15, 2000 10:37 am
Date datatype | article only | Oct 15, 2000 11:33 am
Oracle UTL_SMTP | article only | Oct 15, 2000 11:55 am
Oracle Nested Table | article only | Oct 15, 2000 01:58 pm
A few questions -- export & import | article only | Oct 15, 2000 02:05 pm
question on REMOTE_OS_AUTHENT | article only | Oct 17, 2000 11:31 am
How to make a trigger when update one row and tigger to update another row ? | article only | Oct 17, 2000 11:54 am
Inactive Sessions | article only | Oct 17, 2000 12:23 pm
information for database maintainance | article only | Oct 17, 2000 12:26 pm
How to use a variable table name in a select clause? | article only | Oct 17, 2000 12:40 pm
Implicit Commit Logic | article only | Oct 17, 2000 07:54 pm
Developing data entry forms for Palm Computing Platform ( Window CE ) | article only | Oct 19, 2000 11:17 am
Q on ANALYZE | article only | Oct 19, 2000 11:39 am
RAID levels to be adopted for various physical files? | article only | Oct 19, 2000 12:33 pm
What is two_task? | article only | Oct 19, 2000 12:37 pm
sql_trace | article only | Oct 19, 2000 12:47 pm
OR expansion | article only | Oct 19, 2000 01:13 pm
:new or new? | article only | Oct 19, 2000 01:27 pm
Equivalent of identity column (sql server 7.0) In oracle ! | article only | Oct 19, 2000 02:15 pm
Developer 2000 client access | article only | Oct 19, 2000 08:58 pm
PLSSQL Error handling | article only | Oct 19, 2000 09:11 pm
DECODE or NVL | article only | Oct 19, 2000 09:15 pm
Using To_Char within Procedural code | article only | Oct 19, 2000 09:17 pm
OEM open_cursor | article only | Oct 20, 2000 08:46 am
Using multiple embedded decode statements | article only | Oct 20, 2000 09:02 am
triggers for auditing | article only | Oct 20, 2000 09:46 am
How to find out the ip address of the client? | article only | Oct 20, 2000 09:49 am
SQL Script for counting the number of columns in a table. | article only | Oct 20, 2000 09:51 am
multiple database | article only | Oct 20, 2000 10:09 am
row(s) 1 - 34 of 34
October 14, 2000 Abdullah -- Thanks for the question regarding "Tuning", version 7.3.4 & 8.0.5
You Asked
How can i measure the database performance to know how many
transactions excuted in time (second or minute) to compare that
after tuning?if there is any script please send it to me.

Thanks
and we said...
I would use utlbstat/estat.

It will show you many statistics, including number of commits
(transactions) in any given timeframe.

You would

o run $ORACLE_HOME/rdbms/admin/utlbstat using svrmgrl at some
time.  Make sure TIMED_STATISTICS is set to true (alter system
set timed_statistics=true)

o run your system for some period of time.

o run $ORACLE_HOME/rdbms/admin/utlestat using svrmgrl.  You will
copy the generated report.txt to some unique name (so as to not
lose it).

o "tune" your system

o do the above and compare the results.

In fact, the report.txt can help you figure out what you need to
tune.
October 14, 2000 Bibiana -- Thanks for the question regarding "Installation by Tar Ball", version 8.1.6
You Asked
We had a ISP install Oracle via a tar ball.  Basically, they
installed Oracle on one machine, created a tar file, and
untarred it on the new machine.  I can think of many reasons why
this is a bad idea but they say they have dones this many times
and that it is perfectly acceptable.

I'd appreciate your opinion regarding this.

Thanks!

b
and we said...
as long as the machines are identical (same OS, same rev, same
patches) -- It is OK, done that myself to stamp out lots of
machines.

If anything differs between the machines, you might have to
relink to pick up static libraries.

If the OS's are at different major release levels, I wouldn't do
it.
October 14, 2000 Guy -- Thanks for the question regarding ""Standard" edition differences", version 8.1.6
You Asked
Hi Tom,

I read many papers about the differences between the standard
and enterprise edition of 8i. I always worked with the
enterprise edition but we want to reduce costs and move to the
standard edition.

The papers are not very clear on some points. Could you please
answer the following questions ?

a) Standard does not support advanced replication but supports
ditributed database. They say it supports basic replication.

Can I create a DB link in the standard edition ?

Can I create a snapshot between 2 instances ? I need to place
des2K CG_REF_CODES on one location and distribute it accross a
couple of instances. If I can create database links, and no
snapshots, I could simply create a copy of the tables I need to
replicate, truncate and select from a db_link.

b) Does the standard edition benefit from multi processor
machines even if no parallel query is available ?

c) They say that the standard edition does not support
tablespace point in time recovery ? IS TSPIR the same as RECOVER
DATABASE UNTIL xxx ? I mean, can I do online backups with the
standard edition and be able to apply the redo logs until time x
if say, someone does something BAD to the database (Bad load,
dropped table, etc ?)

Thanks
and we said...
a) you can create a database link in standard -- that is part of
"distributed".

You can create a READ ONLY snapshot between 2 instances.

b) yes, Oracle is a multi-process/multi-threaded program.  It'll
make use of every CPU on the machine and will greatly benefit
from >1 CPU regardless of the "flavor" you are using.

c) tablespace point in time recovery is the ability to recover a
SINGLE tablespace of a database to a given point in time -- not
the entire database.  You can recover an entire instance to a
point in time with SE and EE.  You can recover an indivdual
tablespace to a point in time with EE.

(btw: you can sort of do it in SE as well.  just take the
affected tablespace, system + rollback.  restore them elsewhere.
 offline drop the other files from this copy.  point in time
recovery the tablespace.  EXP it.  IMP it.  EE uses the
transportable tablespace feature -- not available with SE -- to
make the EXP/IMP very very fast.  So, you can achieve the same
thing in SE, it just takes longer)
Review & Followup
Rating: 5
May 11, 2001
Reviewer: A reader

October 15, 2000 Ravi -- Thanks for the question regarding "Please explain unrecoverable_time field in v$datafile.", version 8.1.5
You Asked
Tom,

I created table t1 with nologging option using "create table as
subquery". Then queried unrecoverable_change#,
unrecoverable_time columns v$datafile view. I am not able to
find the last SCN and unrecoverable_time corresponding to my
operation.

I also tried the same with "insert into t1 select * from
scott.emp nologgig". Then I quried from v$datafile to see the
last unrecoverable_time. I am not seeing the time corresponding
to the time I did the operation.

I expect unrecoverable_time of v$datafile to show the time when
I did the nologging operation. Is my expectaion correct. If so,
could you please explain what mistake I am doing.

Log of my activities:
---- ---- ----------

system@oracle>  create table t1 as select * from scott.emp
nologging;

Table created.

system@oracle>  select file#,  unrecoverable_change#,
to_char(unrecoverable_time, 'mm-dd-yyyy hh:mi:
ss') from v$datafile;

    FILE# UNRECOVERABLE_CHANGE# TO_CHAR(UNRECOVERAB
--------- --------------------- -------------------
        1                     0
        2                     0
        3                     0
        4                     0
        5                     0
        6                     0 07-19-2000 12:04:14
        7                     0
        8                     0

8 rows selected.

system@oracle> select to_char(sysdate, 'mm-dd-yyyy hh24:mi:ss')
from dual;

TO_CHAR(SYSDATE,'MM
-------------------
10-14-2000 17:13:48

system@oracle> commit;

Commit complete.

system@oracle> insert into t1 select * from scott.emp nologging;

14 rows created.

system@oracle> commit;

Commit complete.

system@oracle>  select file#,  unrecoverable_change#,
to_char(unrecoverable_time, 'mm-dd-yyyy hh:mi:
ss') from v$datafile;

    FILE# UNRECOVERABLE_CHANGE# TO_CHAR(UNRECOVERAB
--------- --------------------- -------------------
        1                     0
        2                     0
        3                     0
        4                     0
        5                     0
        6                     0 07-19-2000 12:04:14
        7                     0
        8                     0

8 rows selected.

system@oracle>

Regards
Ravi
and we said...
You've used the word "nologging" in the wrong place.  In the
above, it is being used as a TABLE ALIAS.  Your:

create table t1 as select * from scott.emp nologging;

is the same as:

create table t1 as select * from scott.emp A;

You want to:

create table t1 NOLOGGING as select * from scott.emp;

Here is an example that shows the create table as select and how
to do an unrecoverable INSERT (please read about the APPEND hint
and make SURE you understand the ramifications of using it
before using it!)

ops$tkyte@DEV816> drop table t;

Table dropped.

ops$tkyte@DEV816> select file#,
  2
to_char(unrecoverable_change#,'99999999999999999999'),
  3         to_char(unrecoverable_time, 'mm-dd-yyyy hh:mi:ss')
  4    from v$datafile
  5   where file# = 7
  6  /

     FILE# TO_CHAR(UNRECOVERABLE TO_CHAR(UNRECOVERAB
---------- --------------------- -------------------
         7         5966356510632 10-15-2000 09:53:22

ops$tkyte@DEV816>
ops$tkyte@DEV816> exec dbms_lock.sleep(2)

PL/SQL procedure successfully completed.

ops$tkyte@DEV816> create table t nologging as select * from
scott.emp;

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> select file#,
  2
to_char(unrecoverable_change#,'99999999999999999999'),
  3         to_char(unrecoverable_time, 'mm-dd-yyyy hh:mi:ss')
  4    from v$datafile
  5   where file# = 7
  6  /

     FILE# TO_CHAR(UNRECOVERABLE TO_CHAR(UNRECOVERAB
---------- --------------------- -------------------
         7         5966356510645 10-15-2000 09:53:48

ops$tkyte@DEV816>
ops$tkyte@DEV816> exec dbms_lock.sleep(2)

PL/SQL procedure successfully completed.

ops$tkyte@DEV816> insert /*+ APPEND */ into t select * from
scott.emp;

14 rows created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> select file#,
  2
to_char(unrecoverable_change#,'99999999999999999999'),
  3         to_char(unrecoverable_time, 'mm-dd-yyyy hh:mi:ss')
  4    from v$datafile
  5   where file# = 7
  6  /

     FILE# TO_CHAR(UNRECOVERABLE TO_CHAR(UNRECOVERAB
---------- --------------------- -------------------
         7         5966356510655 10-15-2000 09:53:51
October 15, 2000 Omar -- Thanks for the question regarding "Bulk Binding vs. Cursors", version 8.1.5
You Asked
Hi Tom,
   Does bulk binding in Oracle8i replaces standard explicit
cursor we uses to use, if not what are the diff. , if yes which
is better to use.

thanks in advance.
and we said...
Both use cursors.  Bulk binding allows you to do array
processing in PLSQL just like people have been doing for years
in Pro*C and OCI.

Which is better to use?  Depends on your needs.  If you are
writing a PLSQL procedure to load data from an input file into a
table for example, you can get it to run LOTS faster using bulk
binds (save up 100 rows -- then insert them all, instead of
inserting 100 individual rows).

If you can utilize array procesing (bulk binds) do so.  If you
cannot -- because your logic cannot -- then don't ;)

Bulk binds are just a performance tuning tool added on top of
that which already existed.  Everything is done via cursors.
With bulk binds, you are supplying X set of inputs at a time
instead of just 1 set.
October 15, 2000 priya -- Thanks for the question regarding "alter table", version version 8
You Asked
i am attempting to alter a table.  i want to change the
constraints on a column.  i would like to 'check' if the coloumn
has a value greater than 40000.  i get an error stating that
'ORA-02253: constraint specification not allowed here'.

Please help!
and we said...
without seeing your sql, I cannot tell you where you went wrong
but here is an example of how to accomplish what you are trying
to do:

ops$tkyte@ORA8I.WORLD> drop table t;

Table dropped.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> create table t ( x int );

Table created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> alter table t add constraint x_gt_40000
  2  check ( x > 40000 );

Table altered.
October 15, 2000 Hassan -- Thanks for the question regarding "Date datatype", version 7.3
You Asked
Having just finished doing my Oracle developer track and now
preparing for the OCP certification, I'm developing a small
database. I'm having problems regarding the DATE datatype. Is it
possible that we can change the default DATE datatype i.e.,
DD-MM-YY, specially when we are creating a table and similarly
when we are populating the Date column, is it possible if we can
enter the date entries in a different format like 23/12/00?
and we said...
What you want to change is the default date mask for a date --
not the "date datatype" itself.

By default, the default format is either DD-MON-YY or in 8.1.6
and up, it is DD-MON-RR.

You can change this at the session level via an ALTER SESSION:

ops$tkyte@ORA8I.WORLD> create table t ( x date );
Table created.

ops$tkyte@ORA8I.WORLD> alter session set nls_date_format =
'dd/mm/rr';

Session altered.

ops$tkyte@ORA8I.WORLD> insert into t values ( '23/12/00' );
1 row created.

ops$tkyte@ORA8I.WORLD> select x, to_char(x,'dd-mon-yyyy') from
t;

X        TO_CHAR(X,'
-------- -----------
23/12/00 23-dec-2000

Now, you can do it at the database level in the init.ora
parameter but this won't work in general (changing at the
session level in your application is suggested).  See
http://osi.oracle.com/~tkyte/Misc/NLSDateFormat.html
for why this is.

I would suggest using a 4 digit century+year if at all possible.
 Also, read up on the difference between RR and YY to make sure
you understand that:

ops$tkyte@ORA8I.WORLD> create table t ( x date );

Table created.

ops$tkyte@ORA8I.WORLD> alter session set nls_date_format =
'dd/mm/rr';

Session altered.

ops$tkyte@ORA8I.WORLD> insert into t values ( '23/12/99' );

1 row created.

ops$tkyte@ORA8I.WORLD> alter session set nls_date_format =
'dd/mm/yy';

Session altered.

ops$tkyte@ORA8I.WORLD> insert into t values ( '23/12/99' );

1 row created.

ops$tkyte@ORA8I.WORLD> select x, to_char(x,'dd-mon-yyyy') from
t;

X        TO_CHAR(X,'
-------- -----------
23/12/99 23-dec-1999
23/12/99 23-dec-2099
October 15, 2000 Seetharaman -- Thanks for the question regarding "Oracle UTL_SMTP", version 8.1.6
You Asked
Hi Tom,

  Greetings!...

  Is there any package available in Oracle Rel 2 and above to mail "attached
file" using oracle mail service packages...

  Pls. reply me as soon as possible

Thanks in advance

regards

Seetharaman Srinivasan
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:255615160805
we've modified the mail.sql to support attachments using the Java mail utilities.
Review & Followup
Rating: 4
UTL_SMTP June 04, 2001
Reviewer: Seetharaman from Chennai, TamilNadu India
Very userful stuff I was looking for

thank you Tom

October 15, 2000 Seetharaman -- Thanks for the question regarding "Oracle Nested Table", version Oracle 8.1.6
You Asked
Hi Tom,

  I have a table with two nested table within it..  I would like to insert n
number of rows in both the nested tables.. I donno how much of rows it is going
to have in the design time..  I have to do this in single INSERT statement...

  insert into table(select ntable1, ntable2 from table1 where id = 1) values
(values for ntable1), (values for ntable2)

is it possible to do it in single dml statement... Pls lemme know....

thanks in advance

Regards

Seetharaman srinivasan
and we said...
Yes it is but howto depends on what language you are using.  To modify 2 of
them, we will use an UPDATE -- not a insert.  You can only ever insert into A
table at a time, but we can update >1 nested table type at a time:

ops$tkyte@DEV816> create or replace type myTableType as table of number
  2  /

Type created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create table t ( id int, x myTableType, y myTableType )
  2  nested table x store as x_tab
  3  nested table y store as y_tab
  4  /

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816>
ops$tkyte@DEV816> REM to 'insert' into already existing
ops$tkyte@DEV816> REM we will update them
ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t ( id ) values ( 1 );

1 row created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> declare
  2          a   myTableType := myTabletype (1,2,3);
  3          b   myTableType := myTabletype (4,5);
  4  begin
  5          update T
  6             set x = a,
  7                     y = b
  8           where id = 1;
  9  end;
 10  /

PL/SQL procedure successfully completed.

ops$tkyte@DEV816>
ops$tkyte@DEV816> REM to insert a new row, we just insert
ops$tkyte@DEV816> declare
  2          a   myTableType := myTabletype (1,2,3);
  3          b   myTableType := myTabletype (4,5);
  4  begin
  5          insert into t (id,x,y) values ( 2, a, b );
  6  end;
  7  /

PL/SQL procedure successfully completed.

ops$tkyte@DEV816>
ops$tkyte@DEV816> select * from t;

        ID
----------
X
---------------------------------------------------------------------------------
-------------------
Y
---------------------------------------------------------------------------------
-------------------
         1
MYTABLETYPE(1, 2, 3)
MYTABLETYPE(4, 5)

         2
MYTABLETYPE(1, 2, 3)
MYTABLETYPE(4, 5)
October 15, 2000 -- Thanks for the question regarding "A few questions -- export & import", version 7.3.4
You Asked
Tom

I am having problems importing a table beacuse the initial
extent is over 2 GB.

What is the best way of getting the schema of the table so that
I can change the intial extent parameters ?

When doing an import of a 2 GB table what size should I make the
rollback segments ?

Thanks

Cathy
and we said...
That would be a problem since an extent cannot exceed 2gig ever
-- thats the max size of an extent.  I believe the DMP file
really has a 2gig extent -- but anyway -- how to get the DDL to
get a smaller size in there.

You can do this.  Let's say the table is called T.  You could:

$ imp userid=u/p tables=T indexfile=t.sql

that will run import and import will create a script -- not
actually import any data.  In that script, you will find the
create table for the table T.  You can uncomment that create
table -- fix the extent sizes to whatever you want and then
create the table.  Then, to import, you will:

$ imp userid=u/p IGNORE=Y tables=T

That'll get that table and ignore the object creation error it
will get otherwise.

As for the question on rollback.  Use the IMP parameter:

commit=y

and imp will commit as it goes along -- removing the need to any
large amount of rollback.
October 17, 2000 kew -- Thanks for the question regarding "question on REMOTE_OS_AUTHENT", version 7.3.4
You Asked
I am trying to access "remote" DB (residing in the same server),
by setting the two_task parameter. It does not work until I set
the REMOTE_OA_AUTHENT to yes in the remote DB (7.3.4).

Q1) I understand that the REMOTE_OS_AUTHENT has security
concerns, is there any alternative that I can achieve the same
objective and yet it is secure ?

Q2) Can I setup two instances in the same server accessing the
same database ? Is it difficult to setup and maintain ?

Thanks in advance

robert
and we said...
Q1) no, not securely.  When connecting over the network using OS
authentication you MUST trust all of the servers on the network.
 Otherwise, anyone can come along, drop a machine into the
network -- create an OS account named after your database
account and they are in.

Q2) No, not on the same server.  You can use a cluster of
computers running Oracle Parallel Server to have more then one
instance mount and open the same database -- but the instances
are on different machines.  This is done for availability and
scalability.  On the same machine -- you cannot do this.
October 17, 2000 zhu -- Thanks for the question regarding "How to make a trigger when update one row and tigger to update another row ?", version 8.1.5
You Asked
CREATE TABLE INDUSTRY (
industryID        VARCHAR(4),
maxNumber        Integer,
lastUpdateTime            DATE,
industryName        VARCHAR(60)
);
COMMIT;

INSERT INTO INDUSTRY VALUES ('01' ,0
,to_date('20000722','yyyymmdd'),'Agriculture');
INSERT INTO INDUSTRY VALUES ('0101' ,0
,to_date('20000722','yyyymmdd'),'Live animals');
INSERT INTO INDUSTRY VALUES ('0102' ,0
,to_date('20000722','yyyymmdd'),'Meat');
INSERT INTO INDUSTRY VALUES ('0103' ,0
,to_date('20000722','yyyymmdd'),'Milk & egg');
commit;

Question:
I want to make a trigger when I
update industry set maxnumber = maxnumber + 1 where
industryid = '0101' ;
to trigger
update industry set macnumber = maxnumber + 1 where
industry = '01';
So, I make it such as :
CREATE OR REPLACE TRIGGER INDUSTRY_T1
BEFORE UPDATE OF "MAXNUMBER" ON "INDUSTRY"
FOR EACH ROW WHEN (length(old.industryid)>3)
 begin
update industry set maxnumber = maxnumber + 1 where industryid =
substr(:old.industryid,1,2);
end;
But it make a few mistakes .
and we said...
You cannot update (or read) the table that fires the ROW LEVEL
trigger.  that table is mutating and cannot be modified.  What
we can do is outlined in
http://osi.oracle.com/~tkyte/Mutate/index.html

It'll look something like:

tkyte@TKYTE816> create or replace package state_pkg
  2  as
  3          type array is table of industry.industryId%type
  4          index by binary_integer;
  5
  6          modified array;
  7          empty    array;
  8  end;
  9  /

Package created.

tkyte@TKYTE816>
tkyte@TKYTE816> create or replace trigger industry_bu
  2  before update on industry
  3  begin
  4          state_pkg.modified := state_pkg.empty;
  5  end;
  6  /

Trigger created.

tkyte@TKYTE816>
tkyte@TKYTE816> create or replace trigger industry_aufer
  2  after UPDATE OF "MAXNUMBER" ON "INDUSTRY"
  3  FOR EACH ROW WHEN (length(old.industryid)>3)
  4  begin
  5          state_pkg.modified(state_pkg.modified.count+1) :=
:old.industryid;
  6  end;
  7  /

Trigger created.

tkyte@TKYTE816>
tkyte@TKYTE816> create or replace trigger industry_au
  2  after update on industry
  3  declare
  4          tmp state_pkg.array;
  5  begin
  6          tmp := state_pkg.modified;
  7          for i in 1 .. tmp.count loop
  8                  update industry set maxnumber = maxnumber +
1
  9           where industryid = substr(tmp(i),1,2);
 10          end loop;
 11  end;
 12  /

Trigger created.

tkyte@TKYTE816>
tkyte@TKYTE816> select industryid, maxnumber from industry;

INDU  MAXNUMBER
---- ----------
01            0
0101          0
0102          0
0103          0

tkyte@TKYTE816> update industry set  maxnumber = maxnumber;

4 rows updated.

tkyte@TKYTE816> select industryid, maxnumber from industry;

INDU  MAXNUMBER
---- ----------
01            3
0101          0
0102          0
0103          0
October 17, 2000 Raj -- Thanks for the question regarding "Inactive Sessions", version 8.0.6
You Asked
Hi Tom,

Whenever I try to check the sessios logged on to my system
we find say 100 users loigged on out of which hardly 20 sessions
are Active.

Should we have some way to kill the inactive sessions.

Pls tell me how to handle this condition

Thanks

Raj
and we said...
Well, you can use

alter system kill session 'sid,serial#'

where sid and serial are retrieved from v$session -- however --
why would you want to arbitrarily kill inactive sessions?  It
just means that someone is logged in but not executing SQL right
at that instant.  Your very own session is "INACTIVE" everytime
you are in the process of typing in a query via sqlplus.  It is
a normal state to be in.
October 17, 2000 nirad -- Thanks for the question regarding "information for database maintainance", version oracle server
You Asked
Hi Tom!

We are developing the webstite right now using Servlet.For that
we want to maintain the database with oracle .So please inform
me that which server is most suitable for our application.for
that server what type of basic knowledge is required?For
database maintainance with the Server which book of Oracle Press
I should refer?
and we said...
I cannot tell you if you need Oracle8i standard edition or
Oracle8i Enterprise Edition as I do not know what you are
building or how big it is or what features you need.

Your best bet would be to get the "getting to know Oracle8i"
guide from technet.  It has a chapter that breaks out the
features/functions of each and you can make your own decision
based on that.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
...
October 17, 2000 zhu -- Thanks for the question regarding "How to use a variable table name in a select clause?", version 8.1.5
You Asked
declare
 sql_clause VARCHAR2(200);
 p_companyid VarCHAR(6);
 table_name Varchar2(50);
 lastreferencenumber Varchar(13);
begin
sql_clause := 'select sendcompanyid into :p_conpanyid from
table_name where referencenumber =  lastreferenceNumber';
EXECUTE IMMEDIATE sql_clause ;
end;

The compiler tell me have a mistake or return not right .
and we said...
The into clause cannot go into the select statement and you must
use a bind variable for the inputs...

the correct code would look like this:

tkyte@TKYTE816> declare
  2          l_empno number;
  3          l_query varchar2(255) default 'select empno from
emp where rownum=:x';
  4          l_val   number default 1;
  5  begin
  6          execute immediate l_query INTO l_empno USING l_val;
  7  end;
  8  /

PL/SQL procedure successfully completed.
October 17, 2000 Rupali -- Thanks for the question regarding "Implicit Commit Logic", version 8.1.5
You Asked
Dear Mr. Tom,

I asked u about DDL related Parse, Execute & Fetch..
That time you have given me a sequence like this

o  Commit
o  DDL Statement
o  Commit

When we give commit command then whatever changes made before
get commited to database ...

I want to know why here u need the first commit ... The last
commit cannot do the work or what...

Kindly explain the same.

Rupali
and we said...
DDL is done via:

commit.
do the ddl
commit.

It does that to remove any potential locking issues / errors.
-- updates the data dictionary must go fast and just be done.
We don't want the DDL to fail upon a commit because a deferred
constraint failed or whatever.  We don't want a deadlock to
happen and so on.

DDL is done in isolation, issueing the commit before the DDL
ensures that the DDL is done atomically and does not affect your
work.  We need to be able to rollback and release any locks the
DDL attempt made in the event of an error -- so we commit your
work so we don't roll that back.
October 19, 2000 Ratan -- Thanks for the question regarding "Developing data entry forms for Palm Computing Platform ( Window CE )", version 6i
You Asked
Is it possible to create data capture forms using
Oracle Developer 6i tools ( Forms ) having
4/5 tables in Oracle8i Lite ( 4.0.0.2.0) database in plamtop.
Objective is to capture the prices from the market and
finally download into the main database through the remote or
local PC.
If yes, please highlight the necessary steps to be taken.
Thanks and regards.
and we said...
See
http://www.oracle.com/mobile/o8ilite/index.html?iconnect.html
you'll need to use CodeWarrior or something similar to build the
palm app but then syncronization between the palm database and
the "real" database is done by iConnect.
October 19, 2000 Bhavesh -- Thanks for the question regarding "Q on ANALYZE", version 8i (8.1.5)
You Asked
Dear Tom,
Thanks for helping me in setting Materialized view.
Here I have 2 Qs:
1)
We have only one temporary TEMP tablespace in our database,
and all the users have that one as TEMPORARY tablespace.
I have created a script (using DBA_TABLES) view, to analyze all
the tables in my database (there are total 3519 tables).
Here is a sample of script shown for 1 tables - I am
computing statistics , validating structure and
finding for chained rows also

analyze table MMSPROD.TL_PRO_PRICE compute statistics for
     all  indexes ;
analyze table MMSPROD.TL_PRO_PRICE validate structure cascade ;
analyze table MMSPROD.TL_PRO_PRICE list chained rows  into
     scott.chained_rows ;

While this script is raning, from the another session, I monitor
the free space in DBA_FREE_SPACE view. And
there, it is showing me all space available.

Can u tell from where it is getting space for analyzing ?.

Note: Here is the query I used to see the free space available
in temporary tablespace:

system@TTL8I>l
  1* select sum(bytes) from dba_free_space where
tablespace_name='TEMP'
system@TTL8I>/

SUM(BYTES)
----------
 314568704
system@TTL8I>/

SUM(BYTES)
----------
 314568704

system@TTL8I>

2) If I want to analyze all the tables/indexes
in my database once a month (like I did in above example), is
there any other shortcut / functionality (using
DBMS_UTILITY.ANALYZE_SCHEMA ) to achieve the same goal ?

Thanks in advance,
Bhavesh Patel
and we said...
q1) analyze will use temporary segments in the temporary
tablespace.  You do realize that temp segments are allocated
once and then managed internally -- you might not see free space
go up or down in a temp tablespace after a while.  We allocate
it once and then hand it out as needed, sort of like rollback.

look at
        V$SORT_SEGMENT
        V$SORT_USAGE

for stats on temp usage with temporary tablespaces...

2) you can use dbms_utility but I myself prefer to do it object
by object to

o do it in parallel
o have control over exactly HOW the stats on each object are
collected.

dbms_utility may meet your needs though.
October 19, 2000 Ravi -- Thanks for the question regarding "RAID levels to be adopted for various physical files?", version 8.1.5
You Asked
Dear Tom,

Could you please suggest me the RAID to be followed for small,
medium and large sized databases for OLTP and
DSS/DATAWAREHOUSING environment. What are the raid levels to be
adopted for

1) controlfile
2) redologfiles
3) temporary files(temp. tablespace)
4) undo files (rollback segment tablespace)
5) datafiles (files of data tablespace)
6) indexfiles (files of index tablespace)
7) systemfiles (files of system tablespace)
8) Tools and users files (files of TOOLS and USERS tablespace)
9) Oracle software
10) Unix OS software

I read in one book, that in OLTP env, RAID-1 gives good
performance than RAID5 for datafiles. But in another book, I
read RAID5 is good for datafiles. Is there any oracle
documentation for the same.

Could you please enlighten me in this area.

Regards
Ravi
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:359617936136
for my opinion.
October 19, 2000 Ravi -- Thanks for the question regarding "What is two_task?", version 8.1.5
You Asked
Dear Tom,

What is two_task env. variable and its significance. But all I
know is the database service name. Why at all I need to set
that. What are the activities for which I need to set that.

Thanks
Ravi
and we said...
You never "need" to set it.  You can set it instead of
ORACLE_SID so that it becomes the "default" database to log in
with.

It is an option, nothing mandatory.  It overrides an ORACLE_SID
value if one it set -- so that if TWO_TASK is set, we will use
TWO_TASK to connect to a remote database.

It comes in handy for anything that won't accept
user/pass@database -- you can set TWO_TASK to database and use
just user/pass --we'll add the @database for you.
October 19, 2000 wallacel -- Thanks for the question regarding "sql_trace", version 8.1.6
You Asked
Tom:

can i alter sql_trace on line?

alter system set sql_trace=true;
alter system set sql_trace=true
                 *
ERROR at line 1:
ORA-02095: specified initialization parameter cannot be modified

Regards,
and we said...
Only at the session level.

ALTER SESSION SET SQL_TRACE=true;

In 8i, you can create an on-logon type trigger:

create or replace trigger login_trigger
after logon on database
begin
     execute immediate 'alter session set sql_trace=true';
end;
/

to turn it on "globally".  Make sure the owner of the trigger
has been granted "ALTER SESSION" *directly* (not via a role).
See
http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
for why that is.
Review & Followup
Rating: 4
ORA-01031: insufficient privileges November 05, 2003
Reviewer: Robert from CT
Tom,
I want to try out tracing & tkprof HTML DB this way....
FLOWS schema flows_010309 has been granted "alter session" & "create any
trigger"

SQL> connect flows_010309@rcdb
Enter password:
Connected.
SQL> create or replace trigger login_trigger
  2  after logon on database
  3  begin
  4       execute immediate 'alter session set sql_trace=true';
  5  end;
  6  /
after logon on database
               *
ERROR at line 2:
ORA-01031: insufficient privileges

What privileges are missing ?
Thanks

October 19, 2000 wallacel -- Thanks for the question regarding "OR expansion", version 8.1.6
You Asked
Tom:

pls give me a example about what's OR expansion?
and at what situation we should use no_expand hint

ALSO,please give me a link to document relate to OR expansion.
and we said...
or expansion is the use of OR's to process something instead of
another method.  for example (P and Q are predicates):

 select * from t
 where P or Q

can be "or expanded" to something like

select * from t where P
union all
select * from t where Q and NOT(P)

that is or expansion.

The NO_EXPAND hint prevents the cost-based optimizer from
considering OR-expansion for queries having OR conditions or
IN-lists in the WHERE clause. Usually, the optimizer considers
using OR expansion and uses this method if it decides the cost
is lower than not using it.  NO_EXPAND is the opposite of
USE_CONCAT.

Use the no-expand when it goes faster.  The optimizer might have
many more permutations to consider with a OR-expansion then
without -- leading to a longer parse time and perhaps a less
optimal plan (if it gives up soon enough).

The designing and tuning for performance guide has info on this.
October 19, 2000 wallacel -- Thanks for the question regarding ":new or new?", version 8.1.6
You Asked
Tom:

when i am reading some oracle document , i found that
inside the trigger, somebody use :new, some use new
what's different between :new and new inside the trigger
and we said...
well, in the trigger body -- :new will work and new will not.

In the trigger header -- the opposite is true.

So,

create or replace trigger t_trigger
before insert on t for each row
when ( new.x > 5 )
begin
    :new.x := :new.x+1;
end;
/

shows that in definition (the header) you use new.x.  In the
BODY you use :new.x
October 19, 2000 OP -- Thanks for the question regarding "Equivalent of identity column (sql server 7.0) In oracle !", version 8.1.5
You Asked
Dear Tom,
Hi !

How are you doing ?

My question is :- I am developing an Application in Oracle

There is a need to generate Unique value for ecode in EMP
table.According to the SPECIFICATION I cannot make use of
SEQUENCE.When I write Trigger to insert Unique value for
ecode it gives "mutating table problem".

Is SQL Server we have something known as "IDENTITY Column"
Is there anything euivalent to that in ORACLE8i.

Thanks & Regards
OP
and we said...
Why cannot you use a SEQUENCE if the SEQUENCE is totally hidden
from the application.

the only way to do this in Oracle is:

create sequence emp_seq;
create trigger emp_trigger
before insert on emp for each row
begin
  select emp_seq.nextval into :new.empno from dual;
end;
/

The CLIENT will never see or access the sequence.  If you are
not allowed to use sequences for "portability", then you cannot
use identities in SQLServer.  In order to implement the
SQLServer identity type in Oracle -- the required code is above.
 Since the client never sees the sequence, never touches it, is
not aware of it -- you should (have to) make an exception in
this case.

This is as portable as using the proprietary identity type from
SQLServer.

If there is some logical reason you cannot use a sequence,
submit another question with the reasoning.
Review & Followup
Rating: 4
Finally, the answer first... December 03, 2002
Reviewer: Dave Bender from Minnesota
I'm new to Oracle, too, and I've been hunting all over for the answer to the
same question -- how to create an identity field(Sybase/SQL Server), or a SERIAL
data type (Postgres), or an AutoNumber (MS Access).

In my web wanderings, it seems that is a bit of a religious issue in this world
that's new to me. The question was asked many times in different forums and was
answered with a fair amount of venom about what a bad idea it is.

I appreciate that you provided the answer right off the bat in an example that
worked the first time. Now I can go read up on why this is such a bad idea....

October 19, 2000 Steven -- Thanks for the question regarding "Developer 2000 client access", version V6.0
You Asked
Tom,

I would like to know if Developer 2000 V6 clients need to
install client files on their win95/win98 PCs in order to access
NT4 based Developer 2000 form/report executable files.

We are using V1.3 and all clients using NT4 based Dev2K files
via network.    We have regedit4 to populate each client with
the paths for NT based Oracle Dev2K, and it has been working.

If we need to install each client, that would be a lot of work.
Can you help giving some thought how others are implemented the
client/server application, and what is the best way to install
hundred of clients?

Thanks a lot,

Steve
and we said...
The absolute correct answer is to use the developer server -- in
that fashion, you deploy your application to a single machine
and everyone accesses it via a web browser.

The only supported method for the client, when running clienct
server, is to install the entire client.  Developer server was
designed for just such an issue.
October 19, 2000 Prema -- Thanks for the question regarding "PLSSQL Error handling", version version 8.1.6
You Asked
My application has many packages and we are not using any
exception handling except in few cases assuming that data is
present in database. What is the best method to throw a common
exception and capture the information related to which table
generated the error. I have multiple tables in my select
statements. Thanks.
and we said...
I would probably use RAISE_APPLICATION_ERROR instead of a
generic exception.  Using that, you can set not only the error
code (the sqlcode) but the sqlerrm (sql error message text as
well).  So, when you want to throw an exception -- to raise an
error -- you will be able to set both the error code and error
message.

you can code:

 raise_application_error( -20000, 'Table: ' || p_table_name ||
                          ' caused error ' || p_error );

suppling the bulk of the error message at runtime.
October 19, 2000 Sateesh Kumar -- Thanks for the question regarding "DECODE or NVL", version 8.1.5
You Asked
Hi Tom,
  The question is whether to use a DECODE or NVL to cmpare a
null value.
Foe ex :
  declare
   name varchar2(10);
  begin
  Update emp
     set emp_name= nvl(name,emp_name);
  end;

I ran the above query with sql_trace and after viewing the
results using tkprof showed no difference.
and we said...
6 one way, 1/2 a dozen the other.

No difference - NVL() says it a little better (it makes more
sense) when reading the query so I'd use that.
October 19, 2000 Michael -- Thanks for the question regarding "Using To_Char within Procedural code", version 8.1.6
You Asked
I'm trying to convert a number to a Character within a line of
my procedural code.

Example:  v_amount      number(13,2)

select amount into v_amount from table;

to_char(v_amount, '99999999999.99')

I will need to print out 2 places after the decimal ex. 2500.50,
but oracle will store this as 2500.5.  I would select it to a
char in the select statement, but I need to perform math on it
later in my code.  I tried the To_Char function within my
procedural code just before I print it, but I get errors.  I
could be calling this function wrong, but I'm not clear whether
or not using to_char outside of a select statement is allowed.

I'd appreciate your opinion on this one.

Thanks,

Mike
and we said...
You can use to_char outside of a SELECT however, you must
realize to_char is a function -- you must return it INTO
something.

Here is an example:

ops$tkyte@ORA8I.WORLD> declare
  2          v_amount                number;
  3          v_amount_str    varchar2(255);
  4  begin
  5      select 2500.5 into v_amount from dual;
  6
  7      v_amount_str := to_char( v_amount, '99999999999.99');
  8
  9      dbms_output.put_line( 'Number = ' || v_amount );
 10      dbms_output.put_line( 'String = ' || v_amount_str );
 11
 12  end;
 13  /
Number = 2500.5
String =         2500.50

PL/SQL procedure successfully completed.
October 20, 2000 wallacel -- Thanks for the question regarding "OEM open_cursor", version 8.1.6
You Asked
Tom:

my server was installed at sun solaris 2.7
I use OEM on winNT to access the database,
I often get exceed open_cursor limited error.

here, after i exit OEM, I still found
something in v$open_cursor.
how to solve it?

sql>select sql_text from v$open_cursor;SQL_TEXT
------------------------------------------------------------
/* OracleOEM */ UPDATE smp_vdp_node_info SET status = 'N', D
ALTER SESSION SET NLS_LANGUAGE = "AMERICAN"
SELECT NUM_NODES   FROM SMP_VDP_OMS_NUM_NODES  WHERE (OMS =
/* OracleOEM */ select /*+ ALL_ROWS */ rowid, request_id, re
/* OracleOEM */ SELECT node FROM smp_vdp_node_info_vdd WHERE
/* OracleOEM */ UPDATE smp_vdp_node_info SET last_checked =
LOCK TABLE SMP_VDG_GATEWAY_MAP IN EXCLUSIVE MODE
LOCK TABLE SMP_VDP_NODE_OMS_MAP IN EXCLUSIVE MODE
UPDATE SMP_VDP_NODES SET TIMESTAMP=SYSDATE WHERE NODE IN (SE
select sql_text from v$open_cursor
SELECT OMS,NUM_NODES   FROM SMP_VDP_OMS_NUM_NODES  WHERE (OM

SQL_TEXT
------------------------------------------------------------
update smp_vdg_node_list set timestamp = sysdate, processing
/* OracleOEM */ UPDATE smp_vdp_node_info_vdd SET status = 'Y
UPDATE SMP_VDP_OMS_NUM_NODES SET NUM_NODES=NUM_NODES + :b1
UPDATE SMP_VDG_NODE_LIST SET AGENTSTATE='UNK',PROCESSING= NU

one more question is :
i once found some line in v$open_cursor ;
since those line is exactly the same, i think they
should be appear more than once . how does this happen?

SELECT VALUE FROM V$OPTION WHERE UPPER(PARAMETER)=:1
SELECT VALUE FROM V$OPTION WHERE UPPER(PARAMETER)=:1
SELECT VALUE FROM V$OPTION WHERE UPPER(PARAMETER)=:1
SELECT VALUE FROM V$OPTION WHERE UPPER(PARAMETER)=:1
and we said...
I'll answer backwards...

V$open_cursor is by user -- you are seeing that there are 4
sessions with the same open cursor.

The cursors you see in v$open_cursor when you exit are from
OTHER sessions -- this is normal.

v$open_cursor should really be named
"v$cursors_that_may_or_may_not_be_open".  Cursors are cached in
the server in the hopes you will reuse them.  It remembers what
cursors are really open (as opposed to "were opened but now are
closed").  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:553222846752
for more details on that subject.

The default of open_cursors=50 is way too small for any real
instance.  I recommend you set open_cursors=1000.  Cursors are
allocated 64 at a time so setting this "high" will not
materially affect you -- if the application needs that many
concurrently open cursors -- it needs them.

See open_cursors=1000 in your init.ora on the server and restart
the instance.  This issue will go away.
October 20, 2000 Daryl -- Thanks for the question regarding "Using multiple embedded decode statements", version 8.0.5
You Asked
I have written a sqlplus script with embedded decode statements
as follows:

Select tran_type,fp_name_type,
DECODE(TRAN_TYPE,
       'OF',(DECODE(FP_NAME_TYPE,'IN','THIS IS THE TEXT I WANT
FOR OF-IN!')),
       'TA',(DECODE(FP_NAME_TYPE,'EM','THIS IS THE TEXT I WANT
FOR TA-EM!')),
       'TA',(DECODE(FP_NAME_TYPE,'IN','THIS IS THE TEXT I WANT
FOR TA-IN!')),
       'E2',(DECODE(FP_NAME_TYPE,'IN','THIS IS THE TEXT I WANT
FOR E2-IN!')),
       'EA',(DECODE(FP_NAME_TYPE,'EM','THIS IS THE TEXT I WANT
FOR EA-EM!','NONE'))) OFFSET
from trec_rpt_vars
where FK_RPT_HDR_RPT_ID = '1303'
ORDER BY TRAN_TYPE DESC
/
there are 34 separate decode statments (shortened here for
space). What I am trying to do is test for the different
"tran_types" then "fp_name_types" to produce the different text
strings. The script works except the decode statement for the
"TA-IN" section does not return any values. For all others it
works. When I perform the query with just the "TA-IN" decode
statement alone it returns the desired result. Are there any
restrictions on the number decode statements you can have in one
script? What ami I doing wrong?
Thanks!

Daryl G.
and we said...
You have 'TA' in the decode list 2 times -- that value can
appear there only once (the second one is ignored - it never
gets there).  It found the first 'TA' in there and then decoded
the FP_NAME_TYPE for it.  Then it stopped.  It never gets to the
second 'TA'.

You can code this:

ops$tkyte@ORA8I.WORLD> create table trec_rpt_vars
  2  ( tran_type varchar2(2),
  3    fp_name_type varchar2(2),
  4    FK_RPT_HDR_RPT_ID varchar2(5)
  5  )
  6  /

Table created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> insert into trec_rpt_vars
  2  values ( 'OF', 'IN', '1303' );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into trec_rpt_vars
  2  values ( 'TA', 'EM', '1303' );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into trec_rpt_vars
  2  values ( 'TA', 'IN', '1303' );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into trec_rpt_vars
  2  values ( 'E2', 'IN', '1303' );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into trec_rpt_vars
  2  values ( 'EA', 'EM', '1303' );

1 row created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> Select tran_type,fp_name_type,
  2  DECODE(
  3    TRAN_TYPE,
  4    'OF',(DECODE(FP_NAME_TYPE,'IN','TEXT I WANT FOR
OF-IN!')),
  5    'TA',(DECODE(FP_NAME_TYPE,'EM','TEXT I WANT FOR TA-EM!',
  6                              'IN','TEXT I WANT TO TA-IN!')),
  7    'E2',(DECODE(FP_NAME_TYPE,'IN','TEXT I WANT FOR
E2-IN!')),
  8    'EA',(DECODE(FP_NAME_TYPE,'EM','TEXT I WANT FOR EA-EM!',
  9                                   'NONE'))) OFFSET
 10  from trec_rpt_vars
 11  where FK_RPT_HDR_RPT_ID = '1303'
 12  ORDER BY TRAN_TYPE DESC
 13  /

TR FP OFFSET
-- -- ----------------------
TA EM TEXT I WANT FOR TA-EM!
TA IN TEXT I WANT TO TA-IN!
OF IN TEXT I WANT FOR OF-IN!
EA EM TEXT I WANT FOR EA-EM!
E2 IN TEXT I WANT FOR E2-IN!
October 20, 2000 -- Thanks for the question regarding "triggers for auditing", version 8.1.5
You Asked
hi tom:

as an opinion, what do u feel about using triggers to audit dml
operations. by this i mean, if i have a requirement where every
field of a table needs to be audited, for e.g. a customer table
has 10 fields and all need to be audited. for this purpose i
have created an audit_customer table. so any dml operations on
customer r audited in audit_customer to maintain a trail.
is this a good way to do it, if not the best ?

basically, i have heard a lot of people discouraging usage of
triggers. i would like your expert opinion especially with
regards to what i am trying to achieve in my illustration.
r these people really talking from experience or is it just
unsubstantiated baloney.
i'm sure big OLTP apps must be using these to maintain trails of
say retail txns etc.
please comment.

thanks in advance !
and we said...
You have two choices:

o you can wrap everything in a stored procedure and have the
stored procedure read out the old values, stuff them somewhere,
and then apply the changes.  The application is never allowed to
directly access the table via DML.

o you can use triggers.

I myself prefer the triggers as it does not preclude me from
using straight SQL on the tables at some point in time in the
future.  Also, I can disable/enable them to turn auditing on and
off without affecting the application.  It also removes the need
to "read", "copy", then "write".  I just "write" and "copy".

Every application of interest I have ever seen and/or worked on
used triggers.  Oracle's replication is implemented via
triggers.  Triggers are very robust.  Unless people can qualify
their "don't use them" with cold hard provable facts -- ignore
them.  (if they give you cold hard provable facts, put them up
here and we'll discuss them).
October 20, 2000 Reji -- Thanks for the question regarding "How to find out the ip address of the client?", version 8.1.6
You Asked
Tom:
   How can I find out the origin of a client request to a DB?
   What I am looking for is to find out the IP address or HOST
   name where the client initiated the request. There is no
   Web Client involved in the architecture.

   Ex: If I make a sqlplus using the service name from
HOSTA(Client) to HOSTB DB Server, Can I findout from DB or the
HOSTB machine ( NT or Solaris) that HOSTB DB got a sqlplus
connection from HOSTA.  If yes, how?

  Thx
  Reji
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:510222107880
..
October 20, 2000 Maggee -- Thanks for the question regarding "SQL Script for counting the number of columns in a table.", version 8.0.4
You Asked
Our users frequently look at our views in excel and access which
place a limit of 256 columns.  We have tables in excess of 256
columns, and some that appear close to that number of columns
(but we do not want to count them manually).  Is there handy
script or command for counting the number of columns in a table?
 This one has stumped us.  Thanks.
and we said...
  1  select table_name, count(*)
  2  from user_tab_columns
  3* group by table_name
ops$tkyte@8.0> /

TABLE_NAME                       COUNT(*)
------------------------------ ----------
ANALYSIS                                2
C                                       1
CHAINED_ROWS                            6
ITEM                                    2
OTBLCOUNTERTEST                         1
PARTITIONED                             3
RECIPE                                  2
RECIPEVERSION                           1
RESULT                                  5
T                                       3
T1                                      3
T2                                      3
TEMP_PROJECT_19072000                   1
V                                      12

14 rows selected.

will do that for you..
Review & Followup
Rating: 5
May 02, 2001
Reviewer: Helena Markova from Bratislava, Slovakia

October 20, 2000 wallacel -- Thanks for the question regarding "multiple database", version 8.1.6
You Asked
Tom:

I have a unix server (2.7) which have one oracle database
installed, version is 8.1.6.
I was wondering if i can use dbassist to setup another one
at the same machine?
if so, can i startup both database at the same time?
can you see any needs that setup two database at the
same machine? why?

2. since two database being startup at the same time will
consume more resource, why not combine them to one?
and we said...
You can have more then one database on a machine.  People do
this to have a testing instance and a development instance for
example.

If you are thinking of running 2 databases for 2 applications --
I would rethink that.  I would just run 1 database for both.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:897828464193
for further thoughts on this.


Subject | Article | Last Updated (East coast time)
Impoting a table structure only... | article only | Oct 21, 2000 01:44 pm
question on LICENSE_MAX_USERS | article only | Oct 21, 2000 01:54 pm
select statement | article only | Oct 21, 2000 03:20 pm
Multi-thread programming using Pro*C | article only | Oct 21, 2000 03:38 pm
About SQL * Plus/ PL/SQL | article only | Oct 21, 2000 03:43 pm
detect and sign duplicate reords | article only | Oct 21, 2000 03:53 pm
Difference between SVRMGE > & SQLDBA > | article only | Oct 21, 2000 04:37 pm
Question - preventing a dash from appearing in a field. | article only | Oct 22, 2000 09:25 am
OPS | article only | Oct 22, 2000 09:32 am
Oracle 8i with Sun Solaris 8 | article only | Oct 22, 2000 09:39 am
Orcale DBA | article only | Oct 22, 2000 09:51 am
Table extract. | article only | Oct 22, 2000 10:25 am
Complex distributed transactions and Commit Point Site | article only | Oct 22, 2000 03:10 pm
Oracle - Object | article only | Oct 22, 2000 03:18 pm
Question about one column in v$session | article only | Oct 22, 2000 03:19 pm
Oracle Stored Procedures | article only | Oct 22, 2000 06:58 pm
Auditing with AUDIT_TRAIL=OS | article only | Oct 22, 2000 09:40 pm
Log buffer | article only | Oct 23, 2000 06:26 am
How to make My Account Eqivalent to DBA ! | article only | Oct 23, 2000 06:52 am
I say I loaded Pro*C, but it isn't here. | article only | Oct 23, 2000 07:02 am
Storing export dump on a remote machine | article only | Oct 23, 2000 07:47 am
Checkpoint not Complete and NOARCHIVE LOG Mode | article only | Oct 23, 2000 07:58 am
Locally Managed Table Space and Data Segments : article only Oct 23, 2000 07:59 am
Best of both worlds | article only | Oct 23, 2000 08:01 am
How can I write image file on unix server from image in the oracle database? | article only | Oct 23, 2000 11:18 am
Pseudo Password | article only | Oct 23, 2000 01:06 pm
Generation of reports from the database and mailing the same. | article only | Oct 23, 2000 01:08 pm
Multiple Datafile Extents on RAID 5 | article only | Oct 23, 2000 01:37 pm
mutating error | article only | Oct 23, 2000 08:55 pm
adding a new redo log file | article only | Oct 23, 2000 09:18 pm
UTL FILE - ORA 6510 error | article only | Oct 23, 2000 09:21 pm
interMedia Text and XML | article only | Oct 23, 2000 09:22 pm
forms - complex queries | article only | Oct 24, 2000 08:16 am
Predicate Placement, Oracle 8.1.7, import and suspending DB | article only | Oct 24, 2000 11:13 am
Procedure Code. | article only | Oct 24, 2000 11:21 am
How to select table from remote database having clob field | article only | Oct 24, 2000 11:52 am
Constraints | article only | Oct 24, 2000 12:21 pm
Database Migration - OpenVMS to UNIX | article only | Oct 24, 2000 12:39 pm
executing the procedure | article only | Oct 24, 2000 12:51 pm
Urgent... | article only | Oct 24, 2000 12:58 pm
password file | article only | Oct 24, 2000 01:06 pm
What is Relation between COST and Response Time of Query | article only | Oct 24, 2000 01:28 pm
User Interface ( End User ) | article only | Oct 24, 2000 05:06 pm
Delete Conflict Resolution | article only | Oct 25, 2000 09:14 am
RMAN and NIS | article only | Oct 25, 2000 05:11 pm
Context Index | article only | Oct 25, 2000 08:49 pm
Several question | article only | Oct 26, 2000 08:05 am
Oracle Questions. | article only | Oct 26, 2000 04:25 pm
to_char(date) field size in a view | article only | Oct 26, 2000 04:29 pm
Regarding: PARALLEL QUERY EXECUTION | article only | Oct 26, 2000 04:35 pm
No 0 Value | article only | Oct 26, 2000 09:33 pm
row(s) 1 - 51 of 51
October 21, 2000 Bhavesh -- Thanks for the question regarding "Impoting a table structure only...", version 8i (ver 8.1.5)
You Asked
Dear Tom, thanks a lot for helping out developrts in solving problems. I have 3
questions this time:
1) This q is about import.
I have a full database exp dump file, and from that dump file,
I need to import only a DDL for a table (NO data). When I created that table, I
just created it in single shot - I
did not altered it afterwards, but my imp command (shown here:)

    $ imp userid=system/*** fromuser=scott touser=scott  \
       tables=temp1 file=dbak_full_12Oct.dmp show=y

gives me following output. Can u tell me why too many alter schema comes here ?

----   here is o/p of imp command -----

Import: Release 8.1.5.0.0 - Production on Thu Oct 12 10:02:18 2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 - Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

Export file created by EXPORT:V08.01.05 via conventional path
import done in US7ASCII character set and US7ASCII NCHAR character set
. importing SCOTT's objects into SCOTT
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "CREATE TABLE "TEMP1" ("COL1" VARCHAR2(10))  PCTFREE 10 PCTUSED 40 INITRANS "
 "1 MAXTRANS 255 LOGGING TABLESPACE "TS1" PARTITION BY RANGE ("COL1") (PARTIT"
 "ION "TEMP1_PART1" VALUES LESS THAN ('P')  PCTFREE 10 PCTUSED 40 INITRANS 1 "
 "MAXTRANS 255 STORAGE(INITIAL 20480 NEXT 20480 MINEXTENTS 1 MAXEXTENTS 3 PCT"
 "INCREASE 10 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE ""
 "TS1" LOGGING, PARTITION "TEMP1_PART2" VALUES LESS THAN (maxvalue)  PCTFREE "
 "10 PCTUSED 40 INITRANS 1 MAXTRANS 255 STORAGE(INITIAL 20480 NEXT 20480 MINE"
 "XTENTS 1 MAXEXTENTS 249 PCTINCREASE 10 FREELISTS 1 FREELIST GROUPS 1 BUFFER"
 "_POOL DEFAULT) TABLESPACE "TS1" LOGGING )"
. . skipping partition "TEMP1":"TEMP1_PART1"

. . skipping partition "TEMP1":"TEMP1_PART2"

 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
 "ALTER SCHEMA = "SCOTT""
Import terminated successfully without warnings.

----   o/p of imp command ends here -----
2) This q is in connection with following:
http://osi.oracle.com/wa/ask/owa/ask_tom_pkg.show_week_of?p_date=15-Oct-2000#tag917629022445
How can I perform validate structure cascade and list chained
rows (both actions) using DBMS_UTILITY.ANALYZE_SCHEMA (for all the tables in the
schema in one go) ?
Analyze will ALWAYS use temporary segments in the temporary
tablespace OR if it finds enough free space in SGA, it does
not look into temporary tablespace at all ?

3) This is just a q to get useful hint. What is the structure
you are using to generate "tag" for a question? If we need to
keep track of numbering for some event generated in our system,
we can use that method if you provide hint on how you are
generating this track number.

Thanks in advance,

Bhavesh Patel
and we said...
1) that'll happen because you said "show=y".  It is showing you what commands it
would execute.  It hit that many "alter session set current_schema=scott"
commands and, given your import command, it would have executed them.

Perhaps a better way to get the DDL is to use indexfile=filename.  Using
indexfile=stdout for example:

$ imp fromuser=scott touser=scott tables=emp indexfile=stdout

Import: Release 8.1.5.0.0 - Production on Sat Oct 21 13:27:03
(c) Copyright 1999 Oracle Corporation.  All rights reserved.
Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 - Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

Export file created by EXPORT:V08.01.05 via conventional path

Warning: the objects were exported by SCOTT, not by you

import done in US7ASCII character set and US7ASCII NCHAR character set
REM  CREATE TABLE "SCOTT"."EMP" ("EMPNO" NUMBER(4, 0) NOT NULL ENABLE,
REM  "ENAME" VARCHAR2(10), "JOB" VARCHAR2(9), "MGR" NUMBER(4, 0),
REM  "HIREDATE" DATE, "SAL" NUMBER(7, 2), "COMM" NUMBER(7, 2), "DEPTNO"
REM  NUMBER(2, 0)) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 LOGGING

. . skipping table "EMP"
REM  STORAGE(INITIAL 16384) TABLESPACE "UTILS" ;
REM  ... 14 rows
CONNECT SCOTT;
CREATE INDEX "SCOTT"."EMP_IDX" ON "EMP" ("JOB" , "SAL" ) PCTFREE 10
INITRANS 2 MAXTRANS 255 STORAGE(INITIAL 524288) TABLESPACE "UTILS" LOGGING ;
CREATE INDEX "SCOTT"."DEPT_IDX" ON "EMP" ("DEPTNO" ) PCTFREE 10 INITRANS 2
MAXTRANS 255 STORAGE(INITIAL 524288) TABLESPACE "UTILS" LOGGING ;
REM  ALTER TABLE "SCOTT"."EMP" ADD CONSTRAINT "EMP_VALID_JOB" CHECK (job
REM  in ('CLERK','SALESMAN','MANAGER','ANALYST','PRESIDENT')) ENABLE
REM  NOVALIDATE ;
REM  ALTER TABLE "SCOTT"."EMP" ADD CONSTRAINT "EMP_PK" PRIMARY KEY
REM  ("EMPNO") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
REM  STORAGE(INITIAL 524288) TABLESPACE "UTILS" ENABLE NOVALIDATE ;
REM  ALTER TABLE "SCOTT"."EMP" ADD CONSTRAINT "EMP_FK" FOREIGN KEY
REM  ("DEPTNO") REFERENCES "DEPT" ("DEPTNO") ENABLE NOVALIDATE ;
REM  ALTER TABLE "SCOTT"."EMP" ENABLE CONSTRAINT "EMP_VALID_JOB" ;
REM  ALTER TABLE "SCOTT"."EMP" ENABLE CONSTRAINT "EMP_PK" ;

Import terminated successfully without warnings.
REM  ALTER TABLE "SCOTT"."EMP" ENABLE CONSTRAINT "EMP_FK" ;

That'll create the create statements without the quotes and wraps them properly
- all you need to do is put these statements into a file (indexfile=emp.sql for
example) and then uncomment what you want to run.

2) you cannot with dbms_utility.analyze_schema.  It is a very simple script to
analyze the tables in a schema and compute or estimate statistics.

You can write your own very easily:

SQL> create or replace procedure validate_structure
  2  authid current_user
  3  as
  4      l_cmd varchar2(255);
  5  begin
  6      for x in ( select table_name
  7                   from user_tables )
  8      loop
  9          l_cmd := 'analyze table ' || x.table_name ||
 10                    ' validate structure cascade';
 11          dbms_output.put_line( l_cmd );
 12          begin
 13              execute immediate l_cmd;
 14          exception
 15              when others then
 16                  dbms_output.put_line( sqlerrm );
 17          end;
 18      end loop;
 19  end;
 20  /

Procedure created.

ops$tkyte@ORA8I.WORLD> grant execute on validate_structure to public
  2  /

Grant succeeded.

ops$tkyte@ORA8I.WORLD> connect scott/tiger
Connected.

scott@ORA8I.WORLD> exec ops$tkyte.validate_structure

analyze table BONUS validate structure cascade
analyze table DEPT validate structure cascade
analyze table EMP validate structure cascade

PL/SQL procedure successfully completed.

Analyze will use temporary segments when and if it needs them which is almost
always (since tables tend to exceed the limit of sort_area_size).  It will not
use the SGA (ever) it uses the PGA or UGA (the uga might be located in the SGA
in MTS mode).  If you have really small things, it won't swap to disk.

3) The number after the word tag is the p_disp_id I use to identify all
articles.  For example:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:917629022445
and
http://osi.oracle.com/wa/ask/owa/ask_tom_pkg.display_plain?p_dispid=917629022445
both point to that very same article (and always will, my display id is imutable
-- i never change it).  I would suggest using the display or display_plain
routine instead of show_week_of as that is a much smaller page.
October 21, 2000 Jigna -- Thanks for the question regarding "question on LICENSE_MAX_USERS", version 8i - 8.1.5
You Asked
Dear Tom,
I have read somewhere that, Oracle8 can support up to
50,000 users. Is this the same figure for Oracle 8i (ver 8.1.5) ?
Or it is improved ?
And, in the process of deploying FGAC (Fine Grade Access
Control), we plan to put real data within some 15/20 Schemas, and
allow SELECT/UPDATE access to all other users (assume that
there are a huge number of users out there), we need to create an account for
each user. In this plan, the creation of
a user just acquire a row in some SYS (or SYSTEM) owned
table, right ? So there is no harm in going for that.

2) In connection with above: The alert<SID>.log file  (in
background_dump_dest directory ) (among other things) shows
following. Here, I replaced three actual numbers with xx, yy,
and zz. What do these numbers represent actually ?
What if any of these three numbers are zero ?
What if all are zero ?
Why it is NOT MUST to set these values in initSID.ora file?
(at present, one can go without setting them in initSID file.)

#####  content of alert<SID>.log file starts here #####
Sun Oct  1 12:13:01 2000
Starting ORACLE instance (normal)
LICENSE_MAX_SESSION = xx
LICENSE_SESSIONS_WARNING = yy
LICENSE_MAX_USERS = zz

Starting up ORACLE RDBMS Version: 8.1.5.0.0.
System parameters with non-default values:
  ....  /* all other initialization parameters */
  ....  /* thread recovery and other stuff */
Completed: ALTER DATABASE OPEN

#####  content of alert<SID>.log file ends here  #####

Thanks in advance,

jigna patel
and we said...
Oracle8 and up can support over 50k concurrently connected users yes.  Same
applies for 8i.  You can have many hundreds of thousands of users created in the
database (upto 2 billion).

There are no problems having many user accounts created.

The license parameters:

ops$tkyte@ORA8I.WORLD> show parameter license

NAME                           TYPE    VALUE
------------------------------ ------- --------------------
license_max_sessions           integer 0
license_max_users              integer 0
license_sessions_warning       integer 0

are init.ora parameters.  You can set them so the system would alert you  and
eventually stop letting people log in.  If left at the default of zero, they
have no effect.  If you do not set them in the init.ora -- they default to zero.

You do not have to set these as they are for your use, if you want to use them.
Depending on your license arragement, you might have negotiated a contract such
that you have a 50 concurrent session license.  You can use this facility to
ensure you do not exceed that limit (but there is nothing to prevent you from
NOT doing that either -- you do not have to have that limit set).
October 21, 2000 Abdullah -- Thanks for the question regarding "select statement", version 7.3.4 & 8.0.5
You Asked
Mr. Tom

To get the size of the tablespace we can use the statemnt

select tablespace_name,sum(bytes)
from dba_data_files
group by tablespace_name;

and to get the free space for the tablespace we can use this
statment

select tablespace_name,sum(bytes)
from dba_free_space
group by tablespace_name;

but if we try to combine the tow statements in one it
give me wrong result if the tablespace has more than one
datafile.

How can i get the total size and the free sapce in one statemtn
or in one report.

Thanks
and we said...
This is what I use, run:

SQL> @free 1

--------------------------------------------------------
-- free.sql
--
-- This SQL Plus script lists freespace by tablespace
--------------------------------------------------------

column  pct_used format 999.9       heading "%|Used"
column  name    format a16      heading "Tablespace Name"
column  Kbytes   format 999,999,999    heading "KBytes"
column  used    format 999,999,999   heading "Used"
column  free    format 999,999,999  heading "Free"
column  largest    format 999,999,999  heading "Largest"
column  max_size format 999,999,999 heading "MaxPoss|Kbytes"
column  pct_max_used format 999.9       heading "%|Max|Used"
break   on report
compute sum of kbytes on report
compute sum of free on report
compute sum of used on report

select nvl(b.tablespace_name,
             nvl(a.tablespace_name,'UNKOWN')) name,
       kbytes_alloc kbytes,
       kbytes_alloc-nvl(kbytes_free,0) used,
       nvl(kbytes_free,0) free,
       ((kbytes_alloc-nvl(kbytes_free,0))/
                          kbytes_alloc)*100 pct_used,
       nvl(largest,0) largest
from ( select sum(bytes)/1024 Kbytes_free,
              max(bytes)/1024 largest,
              tablespace_name
       from  sys.dba_free_space
       group by tablespace_name ) a,
     ( select sum(bytes)/1024 Kbytes_alloc,
              tablespace_name
       from sys.dba_data_files
       group by tablespace_name )b
where a.tablespace_name (+) = b.tablespace_name
order by &1
/
October 21, 2000 Nick -- Thanks for the question regarding "Multi-thread programming using Pro*C", version Oracle 8i
You Asked
Hi Tom,

We are developing an application that will spawn variable number
of threads and each thread needs to have access to Database. We
are using VC++ and Pro*C/C++ Release 8.1.6.0.0 to build this
application under Windows NT.

What is the most efficient way to implement this application? My
main questions are:

[1] What would be the best way to implement the connection to
the DB server? Is it better to have a static shared pool of
connections? Or is it better for each thread to handle its own
connection? The catch is that the number of threads are
variables so there is no way to know how many connections that
this application needs.

[2] Oracle 8i has a feature to pre-spawn threads for database
connection. Does this mean that there is no need for any
connection pooling mechanism for a client application?

[3] Do I have to define 'threads=yes' in Pro*C compiler to be
able to build a thread-safe application?

[4] Say, if I don't define 'threads=yes' and I write my C++
class code that contains Pro*C code without using Context
variable, and this class is instantiated separately in each
thread.  Is this still thread-safe?

Thanks a lot!

Nick
and we said...
1) it depends.  Will all threads in general need a connection
simultaneously or will a small percentage of them need a
connection at the same time.

If they all (or nearly all) need a connection simultaneously --
you will want to have each thread having its own connection.

If a small percentage need a connection simultaneously,
connection pooling would be a better idea.

2) that feature is a way to make a dedicated server connection
go faster (take less time to connect).  It is not connection
pooling for the client.

3) yes.

4) no.  you need to use threads=yes to get the threadsafe
library and that requires the use of a context.
October 21, 2000 Guru -- Thanks for the question regarding "About SQL * Plus/ PL/SQL", version Version 7.3
You Asked
Sir, I would like to know how to display Cumulative Salary by
using a SELECT statement. For Example, if we consider EMP table,
for each row the last column must display the sum of salaries of
all previous rows and the current row.
and we said...
In SQLPlus it would look like this:

scott@ORA8I.WORLD> compute sum of sal on report
scott@ORA8I.WORLD> break on report
scott@ORA8I.WORLD> select ename, sal from emp;

ENAME             SAL
---------- ----------
SMITH             880
ALLEN            1600
WARD             1250
JONES            2975
MARTIN           1250
BLAKE            2850
CLARK            2450
SCOTT            3000
KING             5000
TURNER           1500
ADAMS            1100
JAMES             950
FORD             3000
MILLER           1300
           ----------
sum             29105

14 rows selected.
October 21, 2000 -- Thanks for the question regarding "detect and sign duplicate reords", version 8.0.5
You Asked
Hi Tom,
how can I detect and sign duplicate records in a table.
e.g.
then table I have is like this
SQL> select * from tab1;

F1           ID DUP_V
----- --------- ----------
t1            1
t1            2
t2            3
t3            4
t3            5
t3            6
t3            7

after the statement it shoud be like this

SQL> select * from tab1;

F1           ID DUP_V
----- --------- ----------
t1            1 DUP_1
t1            2 DUP_1
t2            3
t3            4 DUP_2
t3            5 DUP_2
t3            6 DUP_2
t3            7 DUP_2

Thanks for help
and we said...
For this, I would use a tmp table to help.  It would look like this:

scott@ORA8I.WORLD> create table tmp
  2  ( f1 varchar2(2) primary key,
  3     r int
  4  )
  5  organization index;

Table created.

scott@ORA8I.WORLD>
scott@ORA8I.WORLD> insert into tmp
  2  select f1, rownum r
  3    from ( select f1
  4             from t
  5            group by f1
  6           having count(*) > 1  )
  7  /

2 rows created.

scott@ORA8I.WORLD>
scott@ORA8I.WORLD> update
  2   ( select dup_v, r
  3           from t, tmp
  4      where t.f1 = tmp.f1 )
  5   set dup_v = 'DUP_' ||     r
  6  /

6 rows updated.

scott@ORA8I.WORLD> select * from t;

F1         ID DUP_V
-- ---------- ----------
t1          1 DUP_1
t1          2 DUP_1
t2          3
t3          4 DUP_2
t3          5 DUP_2
t3          6 DUP_2
t3          7 DUP_2

7 rows selected.
October 21, 2000 OP -- Thanks for the question regarding "Difference between SVRMGE > & SQLDBA >", version 8.1.5
You Asked
Dear Tom,
Hi !

Quest) What is the difference between SQLDBA prompt
       and SVRMGR > prompt.How to get these prompts.
       What are the USERNAME and passwords to get
       these prompts.
       Is there any euivalent GUI Interface for these
       things.

Thanks & Regards
OP
and we said...
sqldba was the name of the command line tool to manage databases
in Pre oracle7.3 days (7.2 and before). svrmgrl (server manager)
superceded sqldba with 7.3.

You will not see sqldba anymore.

To get a svrmgr> prompt, run the program "svrmgrl" from the
command line on a machine with the server installed.  Use any
database userid/password to connect.

The GUI equivalent is OEM (Enterprise Manager).
October 22, 2000 Richard -- Thanks for the question regarding "Question - preventing a dash from appearing in a field.", version Version 8.1.5
You Asked
Hi,
  I have a couple of question for you
1) I have a field that can take up to 9 digits how prevent this
field from absecting any daches?.
and we said...
A check constraint is useful for that.

ops$tkyte@ORA8I.WORLD> create table t
  2  ( x varchar2(5)
  3          CHECK ( nvl(instr(x,'-'),0) = 0 )
  4  );

Table created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> insert into t values ( '1' );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into t values ( null );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into t values ( '1-1' );
insert into t values ( '1-1' )
            *
ERROR at line 1:
ORA-02290: check constraint (OPS$TKYTE.SYS_C0032673) violated
October 22, 2000 Sriv -- Thanks for the question regarding "OPS", version 8.1.6
You Asked
Tom

How to implement OPS, what are the basic requirements to
implement ops.

Sriv
and we said...
OPS is Oracle Parallel Server.

OPS allows for more then one instance (set of processes+sga) to
open and mount a single database (set of files -- the data)
simultaneously.  It is designed for 2 things:

o high availability.  You can protect disks using raid so they
are never unavailable.  You can protect the network via
redundancy.  With OPS you can protect that last link, that last
single point of failure -- the computer itself.  OPS allows for
many discrete computers to provide access to the data.

o scalability.  Instead of buying bigger and bigger machines,
you can buy another machine.  This is sometimes refered to as
horizontal scalability.

In order to implement -- you first need a cluster of computers.
Most all hardware vendors support such a configuration.

You should also see the OPS concepts guide:
http://technet.oracle.com/doc/oracle8i_816/paraserv.816/index.htm
for all of the details.
October 22, 2000 zaibi -- Thanks for the question regarding "Oracle 8i with Sun Solaris 8", version oracle 7.3
You Asked
Hi,

Glad to see your link active after so many days.

I want to ask you does 'oracle 8i rel. 2 for sun solaris'  runs
on sun solaris 8. I saw in the Oracle 8i documentation that this
rel 2 only supports sun solaris 2.6 to solaris 7.

Thanks.
and we said...
According to the certification matrix, Versions:

7.3.4, 8.0.6, 8.1.5, and 8.1.6 are all certified on Solaris 8.
October 22, 2000 anil -- Thanks for the question regarding "Orcale DBA", version version 8
You Asked
Does Rollback Segment used during Insertion and Deletion same as
used during updation ?
and we said...
Technically yes but an insert will generate less rollback in
general then either of update or delete will -- in many cases,
the before image that needs to be stored is "empty" during an
insert.  Not so during an update or delete.

Yes -- rollback is used in the same fashion for all 3 operations.
October 22, 2000 Irshad -- Thanks for the question regarding "Table extract.", version 8.0.5 & 8.1
You Asked
Hi Tom,

I have a table start_stop as below:

Day          Date;
time         varchar2;
start_stop   varchar2;
userid       Varchar2;
port         Varchar2;

A typical look at the table is as:

Sep-01-2000 05:31:29 start ins006     port 221
Sep-01-2000 05:37:21 stop  ins006     port 221
Sep-01-2000 05:43:45 start ins007     port 138
Sep-01-2000 05:48:24 stop  ins007     port 138
Sep-01-2000 05:55:08 start ins007     port 247
Sep-01-2000 06:01:08 stop  ins007     port 247
Sep-01-2000 06:08:13 start ins008     port 1
Sep-01-2000 06:12:45 stop  ins008     port 1
Sep-01-2000 06:18:09 start ins007     port 13
Sep-01-2000 06:22:46 stop  ins007     port 13
Sep-01-2000 06:28:13 start ins009     port 192
Sep-01-2000 06:32:38 stop  ins009     port 192
Sep-01-2000 06:38:14 start ins007     port 289
Sep-01-2000 06:43:34 stop  ins007     port 289

I want to create another table from this table that should have
the structure as:

Day          Date;
start_time   varchar2;
stop_time    varchar2;
userid       Varchar2;
port         Varchar2;

now a look at the table would be:

Sep-01-2000 05:31:29 05:37:21 ins006     port 221
Sep-01-2000 05:43:45 05:48:24 ins007     port 138
Sep-01-2000 05:55:08 06:01:08 ins007     port 247
Sep-01-2000 06:08:13 06:12:45 ins008     port 1
Sep-01-2000 06:18:09 06:22:46 ins007     port 13
Sep-01-2000 06:28:13 06:32:38 ins009     port 192
Sep-01-2000 06:38:14 06:43:34 ins007     port 289

Can you tell me the best way of doing that?

Thanks.
and we said...
A simple decode and group by can do that:

ops$tkyte@8.0> select day, userid, port,
  2   max(decode( start_stop, 'start', time, null )) start_time,
  3   max(decode( start_stop, 'stop',  time, null )) stop_time
  4    from t
  5   group by day, userid, port
  6  /

DAY         USERID PORT      START_TI STOP_TIM
----------- ------ --------- -------- --------
sep-01-2000 ins006 port 221  05:31:29 05:37:21
sep-01-2000 ins007 port 13   06:18:09 06:22:46
sep-01-2000 ins007 port 138  05:43:45 05:48:24
sep-01-2000 ins007 port 247  05:55:08 06:01:08
sep-01-2000 ins007 port 289  06:38:14 06:43:34
sep-01-2000 ins008 port 1    06:08:13 06:12:45
sep-01-2000 ins009 port 192  06:28:13 06:32:38

7 rows selected.
October 22, 2000 Ofir -- Thanks for the question regarding "Complex distributed transactions and Commit Point Site", version 8.1.6 EE
You Asked
Hi Tom,

My scenario is as follows:
I am connecting the database A and performing the following
transaction. I am doing some local DML on database A (whose
Commit Point Strength - CPS - is 40). Then I am inserting rows
at database B (CPS - 20) and database C (CPS - 60) through
database links. Then I am updating a row at database B which
fires a trigger that inserts rows into database D (CPS = 100).
Finally, I am updating a row in database C which fires a trigger
that insert a row into datase E (CPS = 80).
         ----> B (20) ----> D (100)
A (40) --
         ----> C (60) ----> E (80)
Then I am commiting the transaction.
Before the prepare phase of the distributed commit (2PC), Oracle
must determine which site is the commit point site.

1. Which site will be the commit point site in Oracle 8i (and
before) ? Will it be database D(with the highest CPS) or will it
be E (or C) due to the fact that database C has the highest CPS
from all the direct neighbours of database A ? If it's not
database D, when that behavior will be fixed ?

2. How can I see what is current CPS of a site ? For example, in
database A, the CPS of site B should be 20 after my remote
insert command and it should raise to 100 after my remote update
command. How can I verify that ?

3. The way I see it, the only way Oracle can maintain a correct
CPS is that every remote DML will return an updated CPS in its
respond (1 byte overhead) based on the databases involved at
that DML operation. Is that correct ? Is the CPS really changes
dynamicly ?

Thanks in advance
and we said...
1)

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76960/ds_txns.htm#908
for more details.  An extract from there shows:

<quote>
How Oracle Determines the Commit Point Site The commit point
site, which is determined at the beginning of the prepare phase,
is selected only from the nodes participating in the
transaction. The following sequence of events occurs:

1. Of the nodes directly referenced by the global coordinator,
Oracle selects the node with the highest commit point strength
as the commit point site.

2. The initially-selected node determines if any of the nodes
from which it has to obtain information for this transaction has
a higher commit point strength.

3. Either the node with the highest commit point strength
directly referenced in the transaction or one of its servers
with a higher commit point strength becomes the commit point
site.

4. After the final commit point site has been determined, the
global coordinator sends prepare responses to all nodes
participating in the transaction.

</quote>

So, in your case, D would be the commit point site.

2)  You cannot see what the commit point site will be since that
is not determined until the prepare phase of the 2PC -- its all
part of "commit".  Its like asking for your SCN (system commit
number).  It is something that might be only discovered after
the fact.

3) see #1.
October 22, 2000 Seetharaman -- Thanks for the question regarding "Oracle - Object", version Oracle
You Asked
Hi Tom,

  Greetings...

  Today I have three questions.....

  1.  Recently I was asked in an interview abt Oracle Object Stripping?...  What
is object Stripping?

  2.  I have a table

     desc samptest

      id varchar2(10),
      name varchar2(10),
      address addresstype,
      contact contacttype

  Now I wanna insert multiple values into samptest and in address and contact
simultaneously...  Meaning I want to do it in one insert statement.. How to
accomplish that?.. I was able to insert samptest and address or contact at one
time....

  3.  What is entity integrity and Domain Integrity in Datawarehousing.. or in
Oracle

  Pls. lemme know the answers for the above questions

  TIA

regards

Seetharaman Srinivasan
and we said...
I believe they meant striping of a database object in Oracle perhaps???  (not
Oracle Objects -- create type foo ... ).  If after questioning -- I found that
to be the case, I would have talked about paritioning (range and hash), using
multiple datafiles per tablespace -- each file on a separate disk -- and perhaps
how to use sqlldr to direct path load segments of data into specific files to
stripe the data.  I would have talked about raid striping at the hardware level
as well.

Not knowing what addresstype or contacttype look like -- I cannot answer that.
Why do you consider samptest, address and contact as separate "things" -- seems
to me samptest is the table and address and contact are columns -- in which case
I can use an insert into select ... to put more then 1 row in at a time or array
inserts in my 3gl program.  would need a better example in order to provide a
sample....

3) entity integrity specifies:

o No component of the primary key of a base relation is allowed to accept nulls.

that ensures that each record in the table has its own identity. It can be
distinguished from the other records

Domain integrity constraints are basically a set of values for an Attribute.
October 22, 2000 Donald -- Thanks for the question regarding "Question about one column in v$session", version 8.1.6.1
You Asked
Hi Tom

   In v$session dynamic view , there is a column named
   ROW_WAIT_FILE#.
   Does the content of this column refer to relative file number
   or absolute file number ?
                                   Thank you
and we said...
According to development -- that is the relative file#.  I'll
file a doc bug to have them be more specific in the future....
October 22, 2000 Seetharaman -- Thanks for the question regarding "Oracle Stored Procedures", version Oracle
You Asked
Hi Tom,

  Thanks for ur reply for my previous mail.. Reg. the que 2 the field types are
object only..  Anyway I'll  mail u with example..

  Now the thing is I wanna know how many times the db object in a database has
been called esp. Stored Procedures... Is there any method to find it.?????

  TIA

Regards

Seetharaman Srinivasan
and we said...
No, there is no way to find that out (unless you enable auditing and then you
can by querying the audit trail tables/views)
October 22, 2000 Tomás -- Thanks for the question regarding "Auditing with AUDIT_TRAIL=OS", version 7.3.4.5.0
You Asked
Hi Tom

How can I know what audit options are the current ones if the
parameter "AUDIT_TRAIL" has the value "OS"?

Greetings
Tomás
and we said...
The same way you would if it is set to TRUE or DB.  Audit_trail
= OS just dictates where the audit records are written (the OS
audit trail instead of the database) -- not what is audited.

Views such as ALL_DEF_AUDIT_OPTS, DBA_OBJ_AUDIT_OPTS,
DBA_PRIV_AUDIT_OPTS and so on.
October 23, 2000 Akthar -- Thanks for the question regarding "Log buffer", version 8.1.5
You Asked
Hi Tom,

Following query

select  substr(name,1,25) Name,
        substr(value,1,15) "VALUE (Near 0?)"
from v$sysstat
where name = 'redo log space requests'

My First question is - what does this query returns ??.

Above query returns following values for My database
Today  = 31613 , yesterday it was  = 30599.(it is increasing day
by day is that a wrong signal???).

What are all these numbers means .. is that it tells me the size
of current log buffer size or I have to increase my log buffer
size.

when querying with V$parameter .. databases's Log buffer values
is 163840.

Pls help me .. Thanks in advance
and we said...
This statistic gives an indication of how many times a user
process waited for space in the redo logs.

Actually what is being waited for is disk space to allocate for
the redo. This is NOT waiting for space in the redo buffer or
for LGWR to finish doing a write. The only way to get more disk
space is to do a log switch.

To reduce this number, you may increase the size of your online
redo logs (add new larger ones and drop the old small ones).
October 23, 2000 OP -- Thanks for the question regarding "How to make My Account Eqivalent to DBA !", version 8.1.6
You Asked
Dear Tom,
Hi !

Thanks Alot for your help in the recent past.

I have been assigned a new ROLE OF DBA in my organisation.

Ques) I have created My account with the name "OP" in the
database.
After this I also wrote
"Grant dba to OP" .This I did by logged as "SYSTEM/MANAGER"

Now when I login as OP,It works but it seems that I do
not have all the rights which a DBA is suppose to have.
Because when I wrote "select *  from V$DATABASE ",it said
insuffient privileges.

WHAT ADDITIONAL PRIVILEGES DO I NEED TO GIVE TO MY ACCOUNT
SO THAT IT HAS ALL THE RIGHTS WHICH A DBA IS SUPPOSE
TO HAVE ?

Thanks & Regards
OP
and we said...
If that did not convey access to that table, then someone has
modified your definition of DBA.  DBA is just a role -- you can
grant and revoke to/from it.

catalog.sql has the following:

create or replace view v_$database as select * from v$database;
drop public synonym v$database;
create public synonym v$database for v_$database;
grant select on v_$database to select_catalog_role;

So, anyone with select_catalog_role should have access to that
view.  DBA has select_catalog_role (this is done in sql.bsq
which should be run when you create the database).

To see what exactly DBA has, you can use the view

create view user_role_hierarchy
as
select u2.name granted_role
  from ( select *
           from sys.sysauth$
        connect by prior privilege# = grantee#
          start with grantee# = uid or grantee# = 1) sa,
       sys.user$ u2
 where u2.user#=sa.privilege#
union all select user from dual
union all select 'PUBLIC' from dual
/
grant select on user_role_hierarchy to public;
create public synonym user_role_hierarchy for
user_role_hierarchy;

(create that as SYS, it is a hierarchy of every role you have
and every role that role has and so on)

and then, create a temp user (or use your OP user) and:

sys@DEV816> grant dba to xxx identified by xxx;
Grant succeeded.

sys@DEV816> connect xxx/xxx
Connected.

xxx@DEV816> select * from user_role_hierarchy;

GRANTED_ROLE
------------------------------
DBA
SELECT_CATALOG_ROLE
EXECUTE_CATALOG_ROLE
DELETE_CATALOG_ROLE
EXP_FULL_DATABASE
SELECT_CATALOG_ROLE
EXECUTE_CATALOG_ROLE
IMP_FULL_DATABASE
SELECT_CATALOG_ROLE
EXECUTE_CATALOG_ROLE
JAVA_ADMIN
XXX
PUBLIC

13 rows selected.

If your list is smaller -- someone has changed what is means to
be a DBA in your database

YOU DON'T HAVE TO SHOUT.  I can hear you just fine ;)
October 23, 2000 Harrison -- Thanks for the question regarding "I say I loaded Pro*C, but it isn't here.", version 8.1.6.0.0 - Pro
You Asked
Hi Tom:

I think I have loaded Pro*C, but I am not sure it is even
on the CD

$ ls
JRE          dbs          jlib         oracore      rdbms
svrmgr
admin.old    doc          ldap         orb          relnotes
sysman
analyzer     hs           lib          ord          root.sh
ys
assistants   install      md           otrace       root.sh.old
bin          jar          network      owm          slax
classes      javavm       ocommon      plsql        sqlj
ctx          jdbc         odg          precomp      sqlplus
$ find . -name proc -print
./ord/ts/demo/proc

And that is it.  Is it possible that loading the precomp
didn't load Pro*C? (if it is, I promise not to ask why).

Thanks, Harrison
and we said...
if proc was loaded there would be a ./precomp/demo/proc
directory.

Proc does not appear to be loaded.  Pro*c does not get loaded by
default with the server.  You need to re-run the installer and
goto the Programmer Tools install - part of the client tools if
I recall.  There you can explicity select pro*c to install.

./precomp gets created -- but until you actually install one of
pro*c, pro*cobol, pro*fortran etc -- it'll not have anything
useful in it.
Review & Followup
Rating: 5
Part of the client tools is the key ... April 05, 2001
Reviewer: Harrison Picot from Haymarket, VA USA
Part of the development tools were in the server installation, but not Pro*C.
Even though they were both on the CD (and should have been linked) only the
Client installation installed Pro*C.  We are talking Solaris here; I have no
idea how NT CDs are done, and Pro*C WAS always installed with the server
development tools.

October 23, 2000 Jayaraman -- Thanks for the question regarding "Storing export dump on a remote machine", version 8.0.4.4.1
You Asked
Hi Tom
We have oracle 8.0.4.4.1 running on HP-UX11.0 The total size of
the database is arounf 18GB and the export dump comes to around
6 - 8 GB. We need to recreate this database on an IBM RS/6000
server.Is it possible to transfer the dump by using OEM
installed on a WIndowsNT client.? Using the Data Manager of OEM
we were able to run the export with the destination of the dump
being one of the clients running on windows in the network. But
is it also possible to get the unix servers in the network as
the destination for the export dump.? Kindly tell us a method
without the use of an external device like a DAT/DLT as we are
arranging for it.Thanks in advance
Regards,
Ashok
and we said...
Export needs to be able to write to a locally connected device
(locally connected to the machine it is running on).  OEM is
just running export on one of those machines.

You can install the database software on the IBM box and do the
export yourself over the network using the IBM boxes software.
Just run export on that machine after you setup sqlnet so it can
see the remote HP/UX box.

In that fashion, export can write to the disks on the IBM box
directly.

But since that'll just be going over the network anyway -- you
might as well just export on the HP/UX machine to compressed
files and then ftp them.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:122612348063
for a script to do that.  It'll create N files of equal size
(all compressed) that can be imported on the remote machine
after you copy them there.
October 23, 2000 Raja -- Thanks for the question regarding "Checkpoint not Complete and NOARCHIVE LOG Mode ", version 8.1.5
You Asked
Checkpoint not Complete and NOARCHIVE LOG Mode :

I always see that this Checkpoint Not  Complete Error for Log
files is mentioned with respect to NOARCHIVE Log Mode only .

Is that the case ? Is the chance for this error to occur minimal
in ARCHIVELOG Mode ?

Regards
Raja
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:69012348056
for the solution. It can and will happen in both archivelog
and noarchivelog mode.  This is due to online redo logs being
filled too fast -- not anything to do with archive redo logs.
October 23, 2000 Raja -- Thanks for the question regarding "Locally Managed Table Space and Data Segments :", version 8.1.5
You Asked
Locally Managed Table Space and Data Segments :

We are  using Locally Managed Table space for Tablespace
containing
1.    Temporary Segments
2.    RollBack  Segments  only .
Initially we were advised to use for these type of segments only
.

Now it is said it can be used for any type of Segments . Is it
also advisable to use Locally Managed Tablespace  for Datafiles
( ie containg Data Segments )

Has this feature been fully tested out ?

Regards
Raja
and we said...
It is the ONLY type of tablespace I use.  I don't know who
recommended using only for temp and rollback but if they were
not "safe" using them for rollback would be DEADLY.  Rollback is
one of the most important tablespaces in your database.

Use them -- they are great.  Search for locally managed on my
site for more info/details (like making sure to add 64k to the
size of each file)
October 23, 2000 Raja -- Thanks for the question regarding "Best of both worlds ", version 8.1.5
You Asked
Best of both worlds :
We wish to have  equi sized extent  allocation to take place .
So PCTINCREASE has to be Zero .

But  SMON will not do automatic coalescing , in which case
PCTINCREASE has to  be greater than Zero .
Shall we keep PCTINCREASE = 1 to have the best of both worlds (
almost) ?

or shall we keep the PCTINCREASE = 1 at Tablespace level and
PCTINCREASE = 0 at Objects level .

Is it advisable ?

Regards
Raja
and we said...
If you have equi sized extents -- you have no need to coalesce
extents since they are all equi sized (so if I give back one --
it is the perfect size for the next guy to use.  we never need
coalesce).

I would just use locally managed tablespaces as they never need
coalescing, are much faster for space allocation, and force you
into equi sized extents (if you use UNIFORM sizing which I
recommend).
Review & Followup
Rating: 5
Best of both worlds September 06, 2001
Reviewer: Robert Eke from England
This was exactly the answer that I was looking for.

We currently have a miss match of table sizes in our tablespaces, and I'm
looking for a solution to bring order to the problem.

This artical's answer is spot on, and confirms what I was original thinking.

Thank you

October 23, 2000 unee -- Thanks for the question regarding "How can I write image file on unix server from image in the oracle database?", version oracle 7.2.3
You Asked
Hello. I'm Unee NOh form south korea.
I've been suffering from finding the solutions
how to write image file on server from image in the
oracle database.

I'm a beginner as part of a pro*C programming .

My code is as below. Please Help me.
=======================================================
EXEC SQL CONNECT :username IDENTIFIED BY :password;

   if (sqlca.sqlcode < 0) {
      printf("Oracle connect error!\n");
      exit(1);
   }
EXEC SQL CONNECT :username IDENTIFIED BY :password;

EXEC SQL DECLARE emp_cur CURSOR FOR
  SELECT RESNO, FACE , FACELEN , IMGTYPE FROM IMG ;
EXEC SQL OPEN emp_cur;

for (;;) {
  EXEC SQL WHENEVER NOT FOUND DO break;
  EXEC SQL FETCH emp_cur INTO :resno, :buffer, :facelen,
:imgtype;

  strncpy(yy , resno.arr, 2);

  spritf(imgfile, "%s%s%s.gif", IMGDIR, yy, resno.arr);
  printf("%s",imgfile);
  printf("\n ==Making image.... \n");
  fp = fopen(imgfile, "w");
  fputs(buffer.arr, fp);
  fclose(fp);
  printf("== Done! \n");

break;
}

========================================================
during compilation,
it occured errors in fputs.... line.

I hope to recieve ur useful response.
Thanks for reading.
and we said...
Well, I don't know why your fputs is complaining -- hard to say
since I don't know what the error is or what buffer is defined
as or anything....

In short though, buffer looks like a varchar, varchars are never
null terminated so that would not work (fputs needs a null
terminated string).  Also, FACE is a long raw right?  If it is
an image -- it could contain a NULL in it as part of the data.
You need to use fwrite, not fputs.

Here is a full example.  My table is:

scott@ORA8I.WORLD> desc image
 Name                          Null?    Type
 ----------------------------- -------- --------------------
 NAME                          NOT NULL VARCHAR2(255)
 MIME_TYPE                              VARCHAR2(30)
 IMG_SIZE                               NUMBER
 IMAGE                                  LONG RAW

and the pro*c code that can be used to unload it is:

static void process()
{

/*
 This is the data structure we will use with our LONG RAWs.
 We will always use pointers to this structure as
 it is big and I don't want that on the stack
*/
typedef struct TAGmy_raw
{
    long            len;
    unsigned char    arr[1];
}
    my_raw;

/*
 Use type equivalencing to tell Oracle that the C
 type "my_raw" is equivalent to the Oracle type
 LONG VARRAW and can hold upto 2mill bytes of data
*/

EXEC SQL BEGIN DECLARE SECTION;

EXEC SQL TYPE my_raw IS LONG VARRAW(2000000) REFERENCE;
my_raw    * buffer;

varchar        name[256];
varchar        mime_type[256];
int            img_size;

EXEC SQL END DECLARE SECTION;

long    size = 2000000;
FILE     * fp;

    EXEC SQL WHENEVER SQLERROR DO sqlerror_hard();

    buffer = (my_raw *)malloc( size+sizeof(my_raw) );

    EXEC SQL DECLARE C CURSOR FOR
       select name, mime_type, img_size, image
         from image;

    EXEC SQL OPEN C;

    for( ;; )
    {
        EXEC SQL WHENEVER NOTFOUND DO break;
        EXEC SQL FETCH C INTO
              :name, :mime_type, :img_size, :buffer;

        printf( "Name = %.*s, mime_type = %.*s, size = %d\n",
                 name.len, name.arr,
                 mime_type.len, mime_type.arr,
                 img_size );

        /* need to NULL terminate this, I've overallocated
           my varchars so I can do that
        */
        name.arr[name.len] = 0;

        if ( (fp=fopen( name.arr, "wb" )) == NULL )
        {
            perror( "fopen" );
            exit(1);
        }
        if ( fwrite( buffer->arr, 1, buffer->len, fp ) !=
                                               buffer->len )
        {
            perror( "fwrite" );
            exit(1);
        }
        fclose( fp );
    }
    EXEC SQL WHENEVER NOTFOUND CONTINUE;

    EXEC SQL CLOSE C;
    free( buffer );
}
Review & Followup
Rating: 5
making image file from db October 21, 2002
Reviewer: uneenoh from France
it's very useful.

October 23, 2000 kta -- Thanks for the question regarding "Pseudo Password", version 7.3.4
You Asked
Q1 : Do you have any procedure/script/documentation to implement
pseudo Oracle Password ? For certain security reasons, we do not
want the user to know the actual Oracle password. We want them
to login via an interface first to authenticate before allow
them to login.

Q2 : We want to create an Unix account (oper) to perform Oracle
operation tasks via cron job (compile program, export & etc) but
do not want to hard code the password in the scripts. How could
we archive this ? One constraint is that we do not want to
create the OPS$OPER account in Oracle.

Many thanks for your advise.

Regards
robert
and we said...
Not in Oracle7.3 -- in 8i there is, see:
http://osi.oracle.com/~tkyte/Misc/OCI-N-Tier.html
for details. Prior to that, what you can do yourself is to use
some hashing function that takes the username and some "magic
key" -- and hashes them into a password that you use.   You get
the username and password from the user, validate it yourself,
put the username + some magic key through a hash function -- get
a string out and thats the password you would use for them.
Secure the magic key and no one else can generate the password
even if they know the hash function.

Q2) if you don't wants ops$ type accounts -- you are out of
luck.  That is what they are for.  You create an OS account and
run the jobs as that account.  that account is implicity allowed
into the database.

Do you have a reasoning behind not allowing this?  Maybe I can
help you out if you describe WHY you hesitate to use an
"identified externally" account.
October 23, 2000 Shabbir -- Thanks for the question regarding "Generation of reports from the database and mailing the same.", version 7.2.3
You Asked
Hi Tom,
   I am storing a report in the database itself. Is there any
way by which I can generate the report from the database itself
on schedule and not from the O. S.

  I want the server itself to generate the report and mail it to
the corresponding users. I have a utility with me, DBMail which
creates a function send_mail() which does the needful. Also, is
it possible for me to store the generated report as an LOB?

Regards,
Shabbir.
and we said...
You can use DBMS_JOB to schedule a recurring PLSQL stored
procedure in the database.  See the supplied packages guide for
details.  It'll let you schedule your stored procedure to run
every N minutes to see if there is a report to run and if so --
it'll do it and then email it.

Since you have 7.2, using a LOB is not feasible as that was
first introduced in 8.0.  You'll be using a LONG datatype (and
if you do the work in plsql, only the first 32k of it)
October 23, 2000 Tad -- Thanks for the question regarding "Multiple Datafile Extents on RAID 5", version 8.0.5
You Asked
Tom

I'm currently looking at a customers database that is quite
large (around 35Gb).

Some of the larger tables (3.5Gb) have been put into their own
tablespaces, which is good, but the tables have multiple extents
(around 35 - 50).  This is also true of the indexes which have
up to 85 extents.

Currently the customer is happy with this as they say the
datafiles exist on a RAID 5 array and that the extents do not
make a difference, as they would if they were on a single
physical disk.

The question is :  Is it better to have the tables in a
tablespace in one (or two) extents on a RAID 5 device, or is it
okay to let it extend thus enabling multiple reads from
different parts of the tablespace ?

I would rather have minimal extents as I have always believed
that this offers better performance.  Am I wrong ?

Thanks,

Tad
and we said...
It is a MYTH.

Go for many extents.  It cannot, willnot, does not, affect
performance with the exception of certain DDL operations (such
as DROP or truncate).

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:421419463648
...
October 23, 2000 vishal -- Thanks for the question regarding "mutating error", version oracle8i version 8.1.5.0.0
You Asked
hi! Tom ,
i 've oracle 8.1.5.0.0 running on solaris2.6
I've created a table CUSTOMER with the following fields :

cust_city    char(3),
cust_co_code char(4),
cust_loc_id  char(1),
cust_code    char(8)

Now whenever a row is inserted in the above table i want to
update cust_code column i.e.

update customer
set    cust_code = cust_city ||cust_co_code ||cust_loc_id

for that row

if i write the update statement in after insert trigger on
customer it gives me mutating error because CUSTOMER becomes
the mutating table. so what's the solution ?

how can i update cust_code column using database trigger ?

thanks in advance

vishal
and we said...
You have full read/write access to the row in the BEFORE for
each row trigger.  Simply code:

create trigger t_trigger
before insert on t for each row
begin
  :new.cust_code := :new.cust_city||
                    :new.cust_co_code||
                    :new.cust_loc_id;
end;

for example:

ops$tkyte@ORA8I.WORLD> create table t
  2  (
  3  cust_city    char(3),
  4  cust_co_code char(4),
  5  cust_loc_id  char(1),
  6  cust_code    char(8)
  7  )
  8  /

Table created.

ops$tkyte@ORA8I.WORLD> create trigger t_trigger
  2  before insert on t for each row
  3  begin
  4    :new.cust_code := :new.cust_city||
  5                      :new.cust_co_code||
  6                      :new.cust_loc_id;
  7  end;
  8  /

Trigger created.

ops$tkyte@ORA8I.WORLD> insert into t ( cust_city, cust_co_code,
cust_loc_id )
  2  values ( 'a', 'b', 'c' );

1 row created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select * from t;

CUS CUST C CUST_COD
--- ---- - --------
a   b    c a  b   c
October 23, 2000 Bhavesh -- Thanks for the question regarding "adding a new redo log file", version 8i (8.1.5)
You Asked
Dear tom, thanks a lot for helping me in my earlier problems.
Here I have two questions:
Q1)
We have following redo-log in our database:

system@TTL8I>column size_mb format 999,999,990.99
system@TTL8I>l
  1  select l.GROUP#, members, l.STATUS status,
  2         substr(MEMBER,1,35) member_file,
  3         l.bytes/(1024*1024) size_mb
  4  from v$log l, v$logfile lf
  5* where l.group# = lf.group#
system@TTL8I>/
Press Enter...

 GROUP#    MEMBERS
------- ----------
STATUS        MEMBER_FILE                       SIZE_MB
------------- ------------------------------- ---------
      1          1
INACTIVE      /u92/oradata/TTL8I/redo01.log        4.88
      2          1
CURRENT       /u92/oradata/TTL8I/redo02.log        4.88

We want to add one more redo log file (for performance reason),
and then we want to multiplex them (all three redo log files)
onto a different disk (/u41) (to be safe against the disk
failure).
- Is following set of commands are fine to achieve
  what we want ? If not, can you please correct them
  and guide us?
- If one has five members (all on diff disks) in
  all (say, three) redo log groups, it means he is multiplexing
  the redo members onto five different disks - Right ?

/* here is the set of commands: */

SQL> alter database add log file group 3
     ('/u92/oradata/TTL8I/redo03.log') size 5m ;
SQL> /* shut-down and start-up  ?  */
SQL> alter database add log file
      member '/u41/oradata/TTL8I/redo01_mx.log'  to group 1 ;
SQL> alter database add log file
      member '/u41/oradata/TTL8I/redo02_mx.log'  to group 2 ;
SQL> alter database add log file
      member '/u41/oradata/TTL8I/redo03_mx.log'  to group 3 ;

Q2)
Should table and index be stored on the difference tablespaces
(on different disks) for performance ? The question appeared
because, the two links following are giving different information:

/* following are both links with the quotes found there: */
link-1:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76956/indexes.htm#340
<quote>
Using different tablespaces (on different disks) for a table
and its index produces better performance than storing the
table and index in the same tablespace, due to reduced disk
contention.
</quote>

link-2:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76992/ch20_io.htm#7181
<quote>
It is not necessary to separate a frequently used table from
its index. During the course of a transaction, the index is read
first, and then the table is read. Because these I/Os occur
sequentially, the table and index can be stored on the same
disk without contention. However, for very high OLTP systems,
separating indexes from tables may be required.
</quote>

- If we are not talking about very high OLTP, then which of the
  above is correct?
- If following both is true in different context, can you pls
  throw light on when/how they are correct?

Pls answer each questions - if not in depth, then in
short - by saying yes/no.

Thanks in advance,
Bhavesh Patel
and we said...
q1) the syntax to add another redo log is:

tkyte@TKYTE816> alter database add logfile group 4
  2  ('C:\ORACLE\ORADATA\TKYTE816\REDO04.LOG' ) size 1m;

Database altered.

and then to add a member to it would be:

tkyte@TKYTE816> alter database add logfile
  2  member 'c:\oracle\oradata\tkyte816\redo04a.log' to group 4;

Database altered.

So, you were very close but it is not "log file" but "logfile".

No restart needed.

q2) The first quote, as it is phrased, was more relevant in days gone by.  Back
when disks were disks, before raid, before large multi-user systems, when slow
seek times ruled.  The concept was -- the heads will not move if I put my index
on disk1 and data on disk2.  I'll not force the heads to move lots on one disk
but rather disk1 will seek -- find a rowid and disk 2 will move around.

Nowadays with striping, super fast disks, multi-user systems (the head is not
yours alone), this advice is not as material.  Now it is not index/data you need
to separate but you would rather want to achieve an even distribution of IO over
all of your disks.

So, in reality -- you would still probably want your index separate from data.
Why?  Because if you have hundreds of people reading the index to get  to the
data (as you would in an oltp system) -- if they were both on the same device --
that device would get all of the IO's.  We don't want that, we want an even
distribution -- so, put the index on one and data on the other.  Now both disks
will get lots of activity (although the index disk probably more so since it
takes at least 2-4 reads to find something in the index and then 1 read to read
the data).
October 23, 2000 Chella -- Thanks for the question regarding "UTL FILE - ORA 6510 error", version 8i
You Asked
I can run the following script in my local db but not on a db
that's on the server;
-----------------------------------------------------------
declare
      output utl_file.file_type;
 begin
      output := utl_file.fopen( 'c:\bsp\', 'epoctrans.slk',
'w');
      utl_file.fclose( output );
      output := utl_file.fopen( 'c:\bsp\', 'epoctrans.slk',
'w',32000);
      owa_sylk.show(
          p_file => output,
          p_query => 'select * from scott.tblMailBoxData where
CustAcNumber = :CustAcNumber',
          p_parm_names =>
                 owa_sylk.owaSylkArray( 'CustAcNumber'),
          p_parm_values =>
    owa_sylk.owaSylkArray( '11318624' ),
         p_show_grid => 'YES' );
      utl_file.fclose( output );
end;
/

---------------------------------------
I get this error if I try to run on the server side db;

SQL> @c:\bsp\excltrans_e.sql
declare
*
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at "SYS.UTL_FILE", line 101
ORA-06512: at "SYS.UTL_FILE", line 157
ORA-06512: at line 4

I have the GRANT EXECUTE permission to use the UTL_FILE on this
server side database but what else could be wrong ? Thank you
for your help in advance.

Chella
and we said...
You have not setup the init.ora parameter utl_file_dir to allow
file IO to c:\bsp\ OR c:\bsp\  does not exist on that server.

UTL_FILE only works on file systems available to the server and
only if the utl_file_dir init.ora parameter allows it.

if you use an exception block like this:

exception
    when utl_file.invalid_path then
        raise_application_error(-20001,
       'INVALID_PATH: File location or filename was invalid.');
    when utl_file.invalid_mode then
        raise_application_error(-20002,
      'INVALID_MODE: The open_mode parameter in FOPEN was
       invalid.');
    when utl_file.invalid_filehandle then
        raise_application_error(-20002,
        'INVALID_FILEHANDLE: The file handle was invalid.');
    when utl_file.invalid_operation then
        raise_application_error(-20003,
       'INVALID_OPERATION: The file could not be opened or
        operated on as requested.');
    when utl_file.read_error then
        raise_application_error(-20004,
       'READ_ERROR: An operating system error occurred during
        the read operation.');
    when utl_file.write_error then
        raise_application_error(-20005,
            'WRITE_ERROR: An operating system error occurred
             during the write operation.');
    when utl_file.internal_error then
        raise_application_error(-20006,
            'INTERNAL_ERROR: An unspecified error in PL/SQL.');
end;

You'll get a more meaningful error message perhaps...
October 23, 2000 Joern -- Thanks for the question regarding "interMedia Text and XML", version 8.1.6.1.3
You Asked
Hi Tom

You have helped me before. Please help me with this one too!

I our database, we store XML-tagged strings of search words in a
VARCHAR field. This way: If new search items are requested, we
can add a new XML-tagged item to our column and avoid creation
of
(yet) another column of the table.

Currently - I am adding a search facility to our users. Instead
of knowing, what word to look for, they are presented with a
list of prefixes. They can then drill down to the next layer of
prefixes.

E.g: The user presses 'suggest..' and is presented with
a - words from animal to azimuth
b - words from bavarian to boutique
....
The user can then select 'a' and get a drill-list:
an - words from animal to antelope
az - words from azimov to azimuth.

The related statement takes advantage of the interMedia
generated
table DR$<indexname>$I:

select substr(token_text,1,2),min(token_text),
max(token_text)
from DR$<indexname>$I
where token_type=16
and token_text like 'A%'
group by substr(token_text, 1,2);

Now - My question is: In order to generate these suggestions to
the user, I always assume that the words I look for have a
certain tag-marking. And I assume that the words tagged with
this marking has the token_type value 16 in the table
DR$<indexname>$I.

Is there a way to look up, if this assumption is true? I.e.: Can
I look up the internal definition of the interMedia generated
indexes somewhere?

Regards

Jørn Hansen
The Stibo Group
and we said...
It is typically ill-advised to query directly from the
underlying interMedia Text meta tables, as these may be subject
to change in subsequent Oracle releases.

The preferred method of returning the tokens associated with an
interMedia Text is to use the procedure CTX_QUERY.BROWSE_WORDS.
Using this procedure, you can  quickly fetch a list of tokens
beginning from a starting token and/or token fragment.  You can
read more about this at:
http://technet.oracle.com/doc/oracle8i_816/inter.816/a77063/cqrypkg2.htm#16105
...
October 24, 2000 Eben -- Thanks for the question regarding "forms - complex queries", version Forms 4.5
You Asked
We are pretty new to oracle but enjoying the challenge

I have a form that needs to collect some user query data and
then search a database to find the matching entries and resorts
and re-selects them to to display only certain entries.

I'll give a more specific example:

database of all sales order lines

user needs to enter customer name (usually w/ wild cards) and a
part number (and perhaps several other criteria like a customer
partnumber or po number  - also usually wild carded)

we want to return only the most recent order number FOR EACH
CUSTOMER.  Any inquiry could have one or many responses.

If I was going to build a table with this information I can work
out how to do this in PL/SQL and insert the records ..no
problem.

The problem is how use the same logic to populate a form?

Thanks for you help, Eben
and we said...
You would have a predicate that looks like:

select *
  from sales_order_line
 where customer_name like :block.bv1
   and customer_part_number like :block.bv2
   AND order_date =
       ( select MAX(order_date)
           from sales_order_line b
          where b.CUSTOMER# = sales_order_line.customer#
            and customer_name like :block.bv1
            and customer_part_number like :block.bv2
       )

You can use the DEFAULT_WHERE block property (set is a pre-query
trigger) to add the and order_date = ( subquery ) before the
query is executed.

For example:

Ok, lets say you have a table "emp_demo"

drop table emp_demo;

create table emp_demo
as
select empno, ename, hiredate, sal from emp
/

insert into emp_demo
select empno, ename, hiredate+20, sal+1000 from emp
/
commit;

built in scott.tiger.  Now, each emp has 2 records -- and the
column I want to MAX on is hiredate.  I build a default block on
this table and add a PRE-QUERY trigger such as:

declare
    l_where  long;
    l_op     varchar2(25) default ' AND ';
begin
   if ( :emp_demo.empno is not null )
   then
      l_where := l_where || l_op || 'empno = :emp_demo.empno ';
   end if;
   if ( :emp_demo.ename is not null )
   then
      l_where := l_where || l_op || 'ename like
:emp_demo.ename';
   end if;
   if ( :emp_demo.sal is not null )
   then
      l_where := l_where || l_op || 'sal > :emp_demo.sal';
   end if;

   l_where := 'where hiredate = ( select max(hiredate) from
                emp_demo b where b.empno = emp_demo.empno ' ||
                l_where || ' )';

  set_block_property( 'emp_demo', default_where, l_where );
end;

If I run that form and just hit f8 to execute query -- i get the
rows i put into emp_demo with insert above -- since their
hiredate is the max.  If I hit f7 and put %A% in the ename field
-- I get all of the records I inserted with A in the name... And
so on..

So, if I do the f7 thing and put %A% in the ename field, the
query forms actually runs is:

SELECT ROWID,EMPNO,ENAME,HIREDATE,SAL
FROM
 EMP_DEMO WHERE HIREDATE = ( SELECT MAX(HIREDATE)
      FROM EMP_DEMO B WHERE
  B.EMPNO = EMP_DEMO.EMPNO AND ENAME LIKE :1 )
   and (ENAME LIKE :2)

(forms added the and (ENAME LIKE :2) part for us) which is
exactly what we need.
October 24, 2000 Andre -- Thanks for the question regarding "Predicate Placement, Oracle 8.1.7, import and suspending DB", version 8.1.6
You Asked
Hi again !

Q1) Predicate placement is not stabilized by way of stored
outlines, according to Oracle. Could you briefly describe the
concept of "predicate placement" and the use of the
ORDERED_PREDICATES hint ?

Q2) It seems Oracle8i Release 3 (version 8.1.7) is not being
widely used. 8.1.6 appears to be the most accepted version now.
Would you give your opinion on that ?

Q3) Would you please shed some light on the TTS_OWNERS and
TOID_NOVALIDATE parameters in the import utility ?

Q4) Could you explain the practical use of "suspending" the
database ? It seems to me the same effect was achieved by
putting the database in "hot backup" mode.

Thanks !
and we said...
q1) ordered predicates causes the where clause to be processed
in some known fashion -- according to how you wrote it (see the
designing and tuning for performance manual for the steps).
Otherwise, the predicate is evaluated in some order according to
statistics on the table (histograms and such might change the
order of evaulation of the predicate -- resulting in the same
answer but a slightly different runtime execution process.  The
where clause "where p and q" might be evaluated as P and then Q
or Q and then P.

q2) Oracle8i release 3 is just now hitting the streets.  8.1.6
is more widely apparent out in the world since it has been
available and in shipping for quite a while -- 8.1.7 has not yet
been (as of the middle of october 2000).

q3) tts_owners is a way to validate the set of users you are
importing.  If you leave this off (the default) all the owners
are imported.  If you add this -- you are specify a list of
expected owners.  If and only if the list of expected owners =
the list actual owners in the dmp file will the tablespace be
attached.

This applies to transportable tablespaces only.  It is a method
to validate the users that are in the dmp file.

TOID_NOVALIDATE (type object id) -- from the server utilities
guide:

....
When you import a table that references a type, but a type of
that name already exists in the database, Import attempts to
verify that the preexisting type is, in fact, the type used by
the table (rather than a different type that just happens to
have the same name).

To do this, Import compares the type's unique identifier (TOID)
with the identifier stored in the export file. Import will not
import the table rows if the TOIDs do not match.

In some situations, you may not want this validation to occur on
specified types (for example, if the types were created by a
cartridge installation). You can use the TOID_NOVALIDATE
parameter to specify types to exclude from TOID comparison.
.....

basically it means "should import verify that the type is
exactly the same or should it trust that it is".  With cartridge
types like Intermedia or ordsys types -- we can trust that they
are the same (but the type ids might be different due to the
different install -- this allows you to move the stuff from db
to db)

q4) see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:373618158622
...
October 24, 2000 Shadab -- Thanks for the question regarding "Procedure Code.", version 8.0.5 & 8.1
You Asked
Hi,

I have a simple question to ask:
Which dictionary view contains the procedure code. DESC PROC
give me 'PROCEDURE PROC'.

I want to give access to the code of my procdures to another
user in addition to 'grant execute to PROC; '

Thanks.
and we said...
select text from user_source where name = 'PROC' order by line;

In order for someone else to see the source code of another
person (beyond a package spec that is) they need:

o EXECUTE ANY PROCEDURE
o CREATE ANY PROCEDURE
(to see standalone functions/procedures)

o CREATE ANY PROCEDURE
(to see package bodies)

I do not recommend giving those VERY large, generous privs
out...

Instead:

The OWNER (say ABC) of the procedure PROC could:

abc@DEV816> create or replace view my_view as select * from
            all_source where owner = 'ABC';
abc@DEV816> grant select on my_view to another_user;

Another user can now query abc.my_view to see the code.
Review & Followup
Rating: 3
see the code of a procedure in a package ? February 21, 2002
Reviewer: g from China
TOM,
 How can i see the code of a procedure in a package?
What privileges needed ?

Rating: 5
alternative to create any procedure grant December 09, 2003
Reviewer: A reader
Tom, above you said that you would not grant create any procedure.  How would
you recommend granting the rights needed for one user (A) to be able to create,
replace, alter, drop procedures within another schema (B)?

October 24, 2000 vrishali -- Thanks for the question regarding "How to select table from remote database having clob field", version 8.1.6
You Asked
Hi Tom,

   I have a table on remote database having clob datatype of one
of its field. I want to select clob field from that table using
database link.

Select dbms_lob.substr(field_name,4000,1) from
schema_name.table_name@db_link;

Which is not returning its result but giving error-

ORA-22992: cannot use LOB locators selected from remote tables

Could you please suggest me any solution to see the data of
remote table having clob from local database?
--------------------------------------------------------------
Thanks
Vrishali
and we said...
2 methods:

1) create a view on the remote site that selects the
dbms_lob.substr.  You can then select from that view over the
dblink.

2) using a temporary table, copy the lob over to work with it.
For example:

scott@ORA8I.WORLD> create global temporary table foo ( x clob );
Table created.

scott@ORA8I.WORLD> insert into foo select x from
t@ora816dev.us.oracle.com;

1 row created.

scott@ORA8I.WORLD> select * from foo;

X
-----------------------------------------------------------------
---------------
Hello World
Review & Followup
Rating: 4
Thanks a lot, very useful September 12, 2003
Reviewer: Chris from Montreal
On metalink, every one said there's no solution ....
Oracle can't do that ...
but you Tom, have 2 solutions and it works very well !

Thanks

October 24, 2000 Mudassar -- Thanks for the question regarding "Constraints", version 8.1.5
You Asked
Can you explain the following extract from Oracle Education book
for DBA8i. It says:

If you execute the ALTER TABLE .. ENABLE VALIDATE CONSTRAINT ..
command when a constraint is enforced, it doesnot require any
table locks during validation.  The enforced constraint
guarantees that no violations are introduced during validation.
This has the following advantages:
1. All constraints are enabled concurrently
2. Each constraint is internally parallelized
3. Concurrent activity on the table is permitted

From the above extract, what I don't get is what is an ENFORCED
constraint. Just for checking reasons I wrote the following:
ALTER TABLE TABLE_NAME ENFORCE CONSTRAINT CONSTRAINT_NAME;
and it worked. Then according to the above I tried to check the
lock part, whether it actually locks the table or not, but
infact it doesnot attempt to lock. Now, the first question is
what is an ENFORCED constraint, and then how does this locking
issue work with the enforced constraint. Lastly, if it does work
how do the above advantages help us.

Thanks in advance,
Mudassar Shahzad
and we said...
Well, the enforce did not lock it.  Enforce just says "from now
on make sure everything is OK, ignore what is in there, but make
sure newly inserted data is OK".

Here is an example. I create a table, I disable the constraint
and simulate a bulk load.  I loaded some data that will violate
the constraint. I "enforce" the constraint (happens really fast)
but do not validate it.  This command works and in fact no new
bad data may be entered -- however when we goto validate it --
the bad data is found and we cannot validate the constraint.
This is typically used when the data you are bulk loading is
known to be clean -- you would disable the constraints, load,
and enforce the constraints (to speed the load).  After the
load, you enforce (but not validate necessarily) the constraint.

ops$tkyte@DEV816> create table t
  2  ( x int,
  3      constraint x_gt_zero check ( x > 0 )
  4  )
  5  /
create table t
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

Elapsed: 00:00:00.00
ops$tkyte@DEV816>
ops$tkyte@DEV816> select status, validated
  2    from user_constraints
  3   where constraint_name = 'X_GT_ZERO';

STATUS   VALIDATED
-------- -------------
ENABLED  NOT VALIDATED

Elapsed: 00:00:00.02
ops$tkyte@DEV816>
ops$tkyte@DEV816> alter table t modify constraint x_gt_zero
disable;

Table altered.

Elapsed: 00:00:00.10
ops$tkyte@DEV816> select status, validated
  2    from user_constraints
  3   where constraint_name = 'X_GT_ZERO';

STATUS   VALIDATED
-------- -------------
DISABLED NOT VALIDATED

Elapsed: 00:00:00.01
ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t select object_id from
all_objects;

23095 rows created.

Elapsed: 00:00:06.08
ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t values ( -1 );

1 row created.

Elapsed: 00:00:00.01
ops$tkyte@DEV816> alter table t modify constraint x_gt_zero
enforce;

Table altered.

Elapsed: 00:00:00.08
ops$tkyte@DEV816> select status, validated
  2    from user_constraints
  3   where constraint_name = 'X_GT_ZERO';

STATUS   VALIDATED
-------- -------------
ENABLED  NOT VALIDATED

Elapsed: 00:00:00.01
ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t values ( -2 );
insert into t values ( -2 )
*
ERROR at line 1:
ORA-02290: check constraint (OPS$TKYTE.X_GT_ZERO) violated

Elapsed: 00:00:00.02
ops$tkyte@DEV816> alter table t modify constraint x_gt_zero
validate;
alter table t modify constraint x_gt_zero validate
                                *
ERROR at line 1:
ORA-02293: cannot validate (OPS$TKYTE.X_GT_ZERO) - check
constraint violated

Elapsed: 00:00:00.06
ops$tkyte@DEV816>
ops$tkyte@DEV816> select status, validated
  2    from user_constraints
  3   where constraint_name = 'X_GT_ZERO';

STATUS   VALIDATED
-------- -------------
ENABLED  NOT VALIDATED

Elapsed: 00:00:00.01
ops$tkyte@DEV816>
October 24, 2000 Kathy -- Thanks for the question regarding "Database Migration - OpenVMS to UNIX", version 8.0.5.0.0
You Asked
Are there any Oracle tools that exist to help w/ an Oracle
database migration from OpenVMS to UNIX? Would I need to
re-create all schemas, users, security, etc, or would I be able
to export/import this data cleanly?

Is there any existing documentation on this migration? If so,
where might I look to find it?

Any information that you could provide would be greatly
appreciated.

Thank you in advance for you response.

Kathy Barthelt
and we said...
IMP/EXP should be all you need to move a database from one
machine to the other.

It'll just be like using exp/imp to migrate with -- you can read
about that at
http://technet.oracle.com/doc/server.804/a58243/migeximp.htm#6940

....
October 24, 2000 manmohan -- Thanks for the question regarding "executing the procedure", version 8.1.5.0.0
You Asked
 Tom,

 I want to execute a procedure (of a package )which takes some
input parameters and returns some outgoing parameters.I want to
execute this from sqlplus and in a single statement(like we used
to execute the procs: exec my_proc('p1',p2) etc...)..

  please tell me if there are some other convenient methods to
do the same.

 Thanks and Regards
 Manmohan
and we said...
sure, you use VARIABLES in sqlplus.  it would look like this:

tkyte@TKYTE816> variable x number
tkyte@TKYTE816> variable y varchar2(25)
tkyte@TKYTE816> set autoprint on
tkyte@TKYTE816>
tkyte@TKYTE816>
tkyte@TKYTE816> create or replace procedure do_something( x in
number, y out varchar2 )
  2  as
  3  begin
  4      y := x;
  5  end;
  6  /

Procedure created.

tkyte@TKYTE816>
tkyte@TKYTE816> exec :x := 5

PL/SQL procedure successfully completed.

         X
----------
         5

tkyte@TKYTE816>
tkyte@TKYTE816> exec do_something( :x, :y );

PL/SQL procedure successfully completed.

Y
--------------------------------
5

         X
----------
         5
October 24, 2000 Mohamed -- Thanks for the question regarding "Urgent...", version 8.1.5
You Asked
Dear Tom,

Thanks for the quick answer to my previous question regarding
viewing the query definition of a view. I need a quick answer
for these questions also.

I've got 2 questions.

(1.)

I need to create a table using a view.

For eg:

create table1 as select * from view1;

I got the following error.

ERROR at line 1:
ORA-00997: illegal use of LONG datatype

One alternative is to export this table and then import it.
Is there any other way of creating this table?

(2).

I have a view with a zero length column (varchar2(0)).
This is because, in the SELECT clause of the view, it has been
selected as,

SELECT
................,
................,
null column_name
from table1
................

So, when i issue a create table as select .... against that
view,
it gives the following error.

ERROR at line 1:
ORA-01723: zero-length columns are not allowed

How can i correct this problem?

Please reply as soon as possible.

thanks and regards,
rafi.
and we said...
for #1, you should not be using LONGs in 8i, you should really
use CLOBs -- much better, easier and flexible then longs.

You can use the TO_LOB() function in the create table command to
convert the long into a clob.

short of that, you can use the sqlplus copy command to do this.
An example is at
http://osi.oracle.com/~tkyte/Misc/MoveLongs.html
for #2, short of changing the view definition, there is not much
you can do except not do that.  NULL as a column type just
doesn't make sense in a persistant table.  It is like saying:

create table t as select NULL x from dual

which throws the same exact error.  It is not something we can
do.
October 24, 2000 wallacel -- Thanks for the question regarding "password file", version 8.1.6
You Asked
Tom:

by using which table or view can i find out where and which one
is my password file? or whatever method available.
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:847627176409
...

it is in a fixed location ($ORACLE_HOME/dbs) with a fixed name.
October 24, 2000 JAGJIT -- Thanks for the question regarding "What is Relation between COST and Response Time of Query", version 8.1.6
You Asked
I am tuning a query. There are four tables in the query. One
table is very big (40 million rows). Second table have 10
Million rows. Third table have 2 millon rows and the fourth
table is having 300 rows.

First, I did the EXPLAIN PLAN on the query. It shows me the cost
55000. When I run the query the result comes back in 2 minutes.

Thereafter, I used some hint in the query. Run the Explain Plan.
The cost is down to 22000. When I ran the query the results
comes back in 5 minutes.

Can u explain above ?
and we said...
Cost has no meaning outside of the optimizer and has absolutely
NO bearing on execution time.

see
http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:compare+cost
for a discussion of this.

The second cost in your example is "deflated" because you used
hints.  You artificially reduced the numeric cost we assigned to
some step in a alternate query plan (thats how hints work by
artificially reducing a cost).  That made that plan "lower" cost
then the other more optimal plan we developed.  We choose the
plan with the lowest cost and go with it.

The cost is just a number, nothing more or less.  It cannot be
used to infer anything.
October 24, 2000 Allan -- Thanks for the question regarding "User Interface ( End User )", version Forms 6i
You Asked
From an end-users perspecitve what would you say are the main differences in
terms of look and feel between screens developed in Forms 6i from those
developed in Forms 4.5 .
and we said...
Sorry so long to respond...

There is not much difference for client/server.  Release 6.0 added a native
forms hierarchical tree control developers can use.  Developer 6i adds right
click pop-up menus may now have images.

The more significant changes came with the web.  Release 6i supports a MDI
interface for Developer Server deployment.  Additionally, you may select the
"Oracle" look and feel and default color scheme.  You will find that the new
interface designed by Oracle's user interface designers is quite impressive.  It
includes things like rounded buttons and scrollbars, animated controls in
dialogs.  It's the Oracle look
similar to what you see when you use Enterprise Manager.  Using the Oracle look
is optional.  You can keep the other look if you prefer.

Java Pluggable Components makes it possible to replace the developer native
controls in the Developer applet with Java Beans which you write for a totally
custom user interface.

On technet, at
http://technet.oracle.com/products/forms,
you will find links to the following two papers which will
provide more detail.  Using Java Components in Oracle Forms Applications  and
New Features (Release 6i and 6.0)
October 25, 2000 -- Thanks for the question regarding "Delete Conflict Resolution", version 8.1.5
You Asked
We have developed an application in Access which uses Oracle 8i
Lite database for storing the data through link tables. We would
like to roll out this application to different sales
representatives and use the bi-directional replication to
synchronize the data from their laptops to the centralized
Oracle 8i server.

In order to avoid unique conflicts during synchronization we
have taken care of generating unique keys for each sales
representative. Similarly, we are using latest timestamp method
with user defined conflict resolutions to resolve update
conflicts. However, we are not sure as to how to implement the
delete conflict resolutions.

Could you please provide us the best possible methods to resolve
them  and some technical guidance to write the delete conflict
resolution. Your input is highly appreciated.
and we said...
The general answer is...

The replicated application should not overuse deletes.
They are difficult to resolve because they require a history of
deleted rows which Oracle does not maintain. Instead, the
application should mark a row as deleted and these rows should
be periodically purged from the replicated table using
procedural replication.

So, our suggestion would be to use "flag deletion" and create
views perhaps that filter the correct data.  For example, I
generally use an "END_DATE" column that I default to some known
date such as "01/01/0001" (year 1).  When someone wants to
delete a record, we set END_DATE = SYSDATE.  All of our queries
use "and end_date = to_date('01/01/0001','dd/mm/yyyy')".

You can use views to achieve this as well.  If you have a table
T currently and wanted to add this sort of feature, you could:

rename T to T_TABLE;

alter table T_TABLE add end_date date default
to_date('01/01/0001');

create view T as select <everything BUT end_date> from t_Table
where end_date = to_date( '01/01/0001', 'dd/mm/yyyy' );

create or replace trigger t_trigger
INSTEAD OF DELETE on T
as
begin
   update t_table set end_date = sysdate
     where primay_key = :old.primary_key;
end;

Your application may never need be aware of the fact that you
are flag deleting instead of physically deleting.  Now,
everything becomes an update conflict.
October 25, 2000 Sriv -- Thanks for the question regarding "RMAN and NIS", version 8.1.6
You Asked
Hi Tom

1.  Would like to know if i can have db in Sun solaris and take
a backup in the db in windows nt or windows 2000.

2.  I cannot bring the production db down, can i go for hot
backup, if so what all files i need to take backup in RMAN and
can i recover / recreate the db with the hot backup files.

3. Say if my production db is 20 gig, what should be my RMAN
tablespace size to store the files.  How do i calculate it.

4.  My company is planning to implement NIS and they wanted to
have one oracle user in NIS, we tried and i cannot mount the db
when NIS is implemented, how do we go abt implementing this any
input.  We do have 4 Sun boxes loaded with oracle separately.

Thanks in advance

Sriv
and we said...
1) you can "initiate" the backup from win/nt/2k via OEM but the
backup will take place on the Solaris box (and may only be
restored to another solaris box of the same architecture --
intel or sparc)

2) rman will help you automate this.  since backup and recovery
is a key, crucial, critical thing here -- I'm not even going to
attempt to list the files you need to backup.  You need to read
the backup and recovery guide.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76990/usingrma.htm#438923
for the commands you need to use to have rman do a whole
database backup but I URGE you to make sure you understand
exactly what it is doing and why.  When you need to recover from
a disaster is not the time to learn how backup and recovery
work.

3) rman keeps a catalog of backups in its directory.  It is not
a function of the size of the database in as much as it is a
function of the number of backups you have.

see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76990/preparer.htm#429560
for more details.

4) and the error message is?  Please post more info in a
separate question please.  A cut and paste of the starup
sequence from svrmgrl with the entire call stack would be a good
start.
October 25, 2000 Rajashekar -- Thanks for the question regarding "Context Index", version 8.1.5
You Asked
Hi

With ref to my prev. question i feel i have to make the changes
in the listener.ora and tnsnames.ora for the following error

-----------------------------------------------
error while creating index is
CREATE INDEX perf_av_str_val on perf_attributevalue(stringvalue)

INDEXTYPE IS ctxsys.context PARAMETERS('memory 50M')
ERROR at line 1:
ORA-29855: error occurred in the execution of ODCIINDEXCREATE
routine
ORA-20000: ConText error:
DRG-50704: Net8 listener is not running or cannot start external
procedures
ORA-28575: unable to open RPC connection to external procedure
agent
ORA-06512: at "CTXSYS.DRUE", line 122
ORA-06512: at "CTXSYS.TEXTINDEXMETHODS", line 34
ORA-06512: at line 1
-----------------------------------------------
My listner.ora file is as follows

DREAMDEV =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS_LIST =
        (ADDRESS = (PROTOCOL = TCP)(HOST = dreambuilder)(PORT =
1522))
      )
    )
 )

SID_LIST_DREAMDEV =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = DREAMDEV)
      (ORACLE_HOME = /u01/app/oracle/product/8.1.5)
      (SID_NAME = DREAMDEV)
    )
 )
--------------------------------------
My tnsnames.ora file is as follows

DREAMDEV =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = dreambuilder)(PORT =
1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME =DREAMDEV )
    )
  )

---------------------------------------
Please advise me the changes

Regards
Raj
and we said...
You can use the Network Assistant to add this service but here
is my listener/tnsnames.ora for reference:

You need to setup the listener.ora and tnsnames.ora file for
extprocs.

Here is a sample listener.ora file:

----------------------------------------------------
LISTENER =
  (ADDRESS_LIST =
    (ADDRESS=(PROTOCOL=IPC)(KEY=oracle81.world))
    (ADDRESS=(PROTOCOL=TCP)(Host=sheepdog)(Port=1521))
  )
SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME=sheepdog.us.oracle.com)
      (ORACLE_HOME= /d01/home/oracle81)
      (SID_NAME = oracle81)
    )
    (SID_DESC =
      (SID_NAME = extproc)
      (ORACLE_HOME = /d01/home/oracle81)
      (PROGRAM = extproc)
    )
  )
STARTUP_WAIT_TIME_LISTENER = 0
CONNECT_TIMEOUT_LISTENER = 10
----------------------------------------------------

The important things in the listener file for extprocs:

o ADDRESS=(PROTOCOL=IPC)(KEY=oracle81.world))

set up an IPC based listener.  remember the value of the KEY=
(you can make it whatever you want, just remember what it is)

o (SID_DESC=(SID_NAME=extproc)

remember that SID_NAME, call it extproc.

The next file is the tnsnames.ora file, it needs an entry like:

---------------------------------------------------
extproc_connection_data =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = IPC)(KEY = oracle81.world))
    (CONNECT_DATA = (SID = extproc))
  )
--------------------------------------------------

Important things:

o (ADDRESS = (PROTOCOL = IPC)(KEY = oracle81.world))

should be the same as was in the listener.ora file....

o (CONNECT_DATA = (SID = extproc))

the sid must match the sid in the (SID_DESC=(SID_NAME=extproc)
from the listener.ora....

Also, if your sqlnet.ora specifies some default domain, it needs
to be on the tnsnames entry.  So if you have a sqlnet.ora with
stuff like:

sqlnet.authentication_services=(none)
names.directory_path = (TNSNAMES, HOSTNAME)
names.default_domain = world
name.default_zone = world
automatic_ipc = off

in it, that would be extproc_connection_data.world -- not just
extproc_connection_data.

hope this helps...
October 26, 2000 Vladimir -- Thanks for the question regarding "Several question", version 8i
You Asked
Hi Tom,
Sorry, but I am confuse my questions are:
1. What is the default tablespace and temporary tablespace for
user SYSTEM,  I can see than in Oracle 8i is TOOLS and TEMP, in
my opinion should be SYSTEM and TEMP
2. When I load java class to the Database, I can see that Oracle
create on the DB two tables CREATE$JAVA$LOB$TABLE and
                     JAVA$CLASS$MD5$TABLE, what is that means?
it is necessary those tables?, accidently I deleted
CREATE$JAVA$LOB$TABLE nevertheless work good!!, also I grant
JAVASYSPRIV and JAVAUSERPRIV to that user
3. How I can see which is the default tablespace and temporary
tablespace for each user but not used Oracle Enterprise Manager,
Imeans I means manually (SQL command!!)

thanks and regards
Vlado
and we said...
1) it is by default SYSTEM & TEMP but the default tablespace can
(and many times is) changed to something other then system.  It
is OK for SYSTEM (who does not own alot of tables, some deferred
queue stuff) to not be in the SYSTEM tablespace and lots of
people prefer it is not.

2)
JAVA$CLASS$MD5$TABLE
  - This is a hash table that tracks the loading of Java objects
into a schema.  ** If you use the loadjava utility to load the
objects, you must use the dropjava utility to drop the objects
otherwise this table is not updated.

CREATE$JAVA$LOB$TABLE
  - This table contains the name of the Java object, the date it
was loaded, and has a BLOB column to store the Java object.

you of course should not directly access these tables.

3) select * from dba_users where username = 'XXXXX'
October 26, 2000 bhaskara -- Thanks for the question regarding "Oracle Questions.", version 8.1.5
You Asked
Hi Tom,
    I have few questions.

1) what exactly MIG utility does as a part of Migration?

2) Support there are multiple copies of same table across
several databses using advanced replication. How exactly update
confliction be avoided i.e updating same same row and columns at
two databases simultaneously?

3) What are steps to be followed for configuring Advanced
Replication?

Thanks you very much in advance,
regards,
Bhaskara
and we said...
1)
Migration converts the data dictionary and structures of an
Oracle7 database into Oracle8i format. To migrate the database,
you first install the Oracle8i software and run the Migration
utility on the Oracle7 database. Then, you execute a series of
ALTER DATABASE statements on the new Oracle8i database and run
the u0703040.sql conversion script. The completion of these
procedures results in the conversion of the following Oracle7
structures into structures that can be used by Oracle8i:

o data files (file headers only)
o data dictionary
o control files
o rollback segments

2)
it is explicity NOT avoided.  We allow the same row and column
to be modified in 2 places simultaneously.  You can avoid it
using many partitioning schemes or rules.  we allow for it.  If
you allow it to ocurr, you must supply conflict resolution
routines that will resolve the update conflict.  There is a lot
written about this in the Replication guide.  See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76959/repover.htm#12360
3)
step #1 that I would suggest: take some training.  replication
is fairly complex -- not to setup -- but to implement.  There
are lots of issues you need to be aware of that others have
overcome before you.  This is one feature I highly recommend
getting a course on.

Other then that, please see the replication guide.
http://technet.oracle.com/doc/oracle8i_816/server.816/a76959/toc.htm
...
October 26, 2000 Jim -- Thanks for the question regarding "to_char(date) field size in a view", version 7.3 v 8.1
You Asked
I have an in house app that uses a view on a table where a date field in the
table is passed to the view as
to_char(lot.date_submitted,'DD-MON-YYYY') date_submitted
Now I would have just passed the date field to the view and avoided all of this
mess,
but in oracle 7.3.4 date_submitted is a varchar2(75)
in oracle 8i it is a varchar2(11)
This is a problem because BDE expects 75 chars when it passes a query on the
view to the database and complains when it only gets 11.
Is there anyway to force the field to be a varchar2(75) in 8i? Or do I need to
pad the format to be 75 chars?
Thanks
and we said...
When you create the view in 8i, you can:

create or replace view v
as
select to_char( sysdate, 'dd-mon-yyyy' ) d1,
       trim(rpad(to_char(sysdate,'dd-mon-yyyy'),75)) d2
 from dual
/

the first will be 11 and the second will be 75.
October 26, 2000 Vasudevan -- Thanks for the question regarding "Regarding: PARALLEL QUERY EXECUTION", version 7.3.3.4 and 8.1.5
You Asked
Hi Tom,

I know I can use the Parallel Query  with a degree in the Select
clause as below.

select /*+ parallel(my_fact_table)*/ count(*)
     from my_fact_table f, my_dim_table1 d1, my_dim_table2
d2where f.id1 = d1.id1
     and f.id2= d2.id2;

1. Is there anyway I can use this in DELETE , UPDATE, INSERT
   Statements in 7.3.3.4 or 8.1.5. If not available, will it
   be available in the future versions?

Thanks in advance for your reply,
vasu.
and we said...
In Oracle8.0 we introduced Parallel DML.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/ch3.htm#91084
for details.
October 26, 2000 Richard -- Thanks for the question regarding "No 0 Value", version SQL/plus 8.1.5
You Asked
How can i make a constraint that will not let a field in an
Oracle data base have a value of 0; Basicaly i have to check a
field call acct_type for it to be 1,2 or 3 and another field
call balance if the value acct_type is 1 then balance have to be
NOT NULL AND GREATHER THAN . Please help me i try several things
an it still doesn't work.
Thanks,
Rich Hernandez
and we said...
Here is one implementation you can use:

ops$tkyte@DEV816> create table t
  2  ( acct_type   int  check ( acct_type in ( 1, 2, 3 ) ),
  3    balance     int,
  4    constraint balance_constraint
  5        check ( acct_type <> 1
  6                OR
  7                ( balance is not null AND balance > 0 )
  8              )
  9  )
 10  /

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t values ( 1, 1 );

1 row created.

ops$tkyte@DEV816> insert into t values ( 1, 0 );
insert into t values ( 1, 0 )
*
ERROR at line 1:
ORA-02290: check constraint (OPS$TKYTE.BALANCE_CONSTRAINT)
violated

ops$tkyte@DEV816> insert into t values ( 1, null );
insert into t values ( 1, null )
*
ERROR at line 1:
ORA-02290: check constraint (OPS$TKYTE.BALANCE_CONSTRAINT)
violated

ops$tkyte@DEV816> insert into t values ( 2, 0 );

1 row created.

ops$tkyte@DEV816> insert into t values ( 4, 1 );
insert into t values ( 4, 1 )
*
ERROR at line 1:
ORA-02290: check constraint (OPS$TKYTE.SYS_C008101) violated


Subject | Article | Last Updated (East coast time)
Silent Commit in Forms | article only | Oct 28, 2000 02:14 pm
Oracle Auditing | article only | Oct 29, 2000 10:33 am
Row Insertion Order. | article only | Oct 29, 2000 10:53 am
Delete statement and bitmap indexes | article only | Oct 29, 2000 12:22 pm
wrap - what is it, how to do it. | article only | Oct 29, 2000 10:03 pm
How do i find the terminal ID of a system | article only | Oct 30, 2000 07:45 am
Application DBA | article only | Oct 30, 2000 08:11 am
Aplication for Import Data from file TEXT | article only | Oct 30, 2000 09:25 am
Converting forms to JSP. | article only | Oct 30, 2000 10:03 am
LOB usage | article only | Oct 30, 2000 10:13 am
SQL Query | article only | Oct 30, 2000 11:32 am
bad coding? --> view on view | article only | Oct 30, 2000 12:33 pm
init.ora | article only | Oct 30, 2000 12:37 pm
Loadjava error | article only | Oct 30, 2000 12:53 pm
Table Replication | article only | Oct 30, 2000 05:02 pm
password validation | article only | Oct 31, 2000 06:53 am
Ordering interdependent tables using their Primary - Foreign key relationships | article only | Oct 31, 2000 08:29 am
JDBC Qn | article only | Oct 31, 2000 08:31 am
Using local temp tablespace | article only | Oct 31, 2000 08:41 am
Converting Long to CLOB | article only | Oct 31, 2000 08:53 am
ASP query a ORACLE table | article only | Oct 31, 2000 09:00 am
Date processing | article only | Oct 31, 2000 09:10 am
Interaction with user while in DB stored procedure | article only | Oct 31, 2000 09:13 am
Password selection | article only | Oct 31, 2000 09:16 am
Connections/Process | article only | Oct 31, 2000 01:01 pm
Today's CLOB question. | article only | Oct 31, 2000 01:17 pm
Oracle Calendar | article only | Oct 31, 2000 02:47 pm
Timed_statistics parameter | article only | Oct 31, 2000 06:05 pm
Transaction Security on Oracle Developer 2000 | article only | Nov 01, 2000 08:37 am
moving a tablespace in production database to a testing database | article only | Nov 01, 2000 09:49 am
COMMAND LINE | article only | Nov 01, 2000 09:53 am
1 to 28 check | article only | Nov 01, 2000 09:59 am
Env setup for java | article only | Nov 01, 2000 10:20 am
changing next param of snapshots - user_jobs | article only | Nov 01, 2000 08:53 pm
Network routing w/SQLPlus COPY | article only | Nov 01, 2000 09:02 pm
Inserting New Rows with Old Data | article only | Nov 01, 2000 09:11 pm
Error Starting EXPORT program | article only | Nov 01, 2000 09:16 pm
Sub querry | article only | Nov 01, 2000 09:33 pm
Env java | article only | Nov 02, 2000 08:11 am
Size of Host Arrays | article only | Nov 02, 2000 08:47 pm
deletion of recs | article only | Nov 02, 2000 08:52 pm
DB link | article only | Nov 02, 2000 08:54 pm
Selecting rows with value '%' in them | article only | Nov 03, 2000 07:52 am
Global Variables | article only | Nov 03, 2000 07:56 am
connecting developer 2000 to an oracle database | article only | Nov 03, 2000 07:59 am
Inter Media | article only | Nov 03, 2000 08:47 am
how to trace the sql statements coming through net | article only | Nov 03, 2000 08:53 am
How to check if installed Oracle8 Server software is 32 or 64 bits | article only | Nov 03, 2000 08:54 am
XML | article only | Nov 03, 2000 08:59 am
DATABASE PROBLEM | article only | Nov 03, 2000 09:05 am
prevent multiple login | article only | Nov 03, 2000 09:23 am
Datafiles in v$datafile | article only | Nov 03, 2000 09:29 am
WebDB and ASP | article only | Nov 03, 2000 10:07 am
Copy one Row's Data to Other | article only | Nov 03, 2000 10:25 am
row(s) 1 - 54 of 54
October 28, 2000 Navdeep -- Thanks for the question regarding "Silent Commit in Forms", version Forms 4.5
You Asked
Tom,
I am using forms to do some database inserts. Like I am
inserting some 50 Records to a table using a code written on a
when buttom pressed trigger. Right now I commit the records at
the end. But i want to commit each record as it is inserted. The
Problem is that if I write a commit at the end of each inserts ,
It displays one record saved when it is executed and the user
has to press the OK Button to proceed. is there a way to do a
silent commit , which does not display one record applied and
saved?

Thanks
Navdeep
and we said...
forms_ddl( 'commit' );

that way -- forms will have no idea what DDL/DML statement you
executed since its dynamic.
October 29, 2000 Seetharaman -- Thanks for the question regarding "Oracle Auditing", version Oracle 8.0.5
You Asked
Hi Tom,

  Greetings and thanks for your kind help in the recent past.

  Now I have got two questions this time..

  1.  Is there any way to find out userid/username of the OS(NT User/ Unix User)
level accessing Oracle Database, by using Oracle WebDB or thro' utl packages or
by any means?

  2.  How to audit a table's or DB's transactions?.. For example, I have a table
in which frequent updates and inserts take place.  I have to audit these changes
(both) and If reqd I have to rollback the transactions say some 4 days old..
etc..  If it's there to do automatically lemme know it immed. pls...  And if
auditing is reqd. what are all the packages to be run?..

  TIA

regards

Seetharaman Srinivasan
and we said...
1) well, if you are using webdb -- then you are using 3 tiers and the physical
OS user connecting to the database will be that of the webserver -- not the
person using the browser.

You can query v$session to get the OS user but you will find that that is the OS
user is the user running the webserver in your case.

2) You can audit actions taken on a table -- eg, we can audit the fact that you
INSERTED into T at 5pm last friday.  We cannot audit that you inserted the
values x, y, z.

In order to do what you want -- you must use triggers.  It'll be very expensive.
 I might suggest that a method to "audit" inserts would be to add a column to
any table that way want this auditing on:

alter table T add created_by varchar2(30) default user;

And going a step futher, you might:

rename T to T_tbl;
create view T as select <everything but created_by> from T_tbl;

That way -- the new column is hidden, the applications never know and the end
user cannot supply some other value for created by.  That handles the audits of
the inserts.

For the updates -- it might be better to do "flag" updates that are really an
update and an insert.  For example, continueing with the above example, you
would add yet another column:

alter table T_tbl add end_date date default
to_date( '01/01/0001', 'dd/mm/yyyy' );

create view T as select <everything but created_by> from T_tbl
where end_date = to_date( '01/01/0001', 'dd/mm/yyyy' );

create or replace trigger t_trigger
instead of UPDATE on T
as
begin
   update t_tbl set end_date = sysdate
     where <primary key> = :old.<primary key>;

   insert into t_tbl values ( :new....... );
end;
/

That'll "flag" delete the updated data -- it'll not appear in the table anymore.
 It'll create a new row with the current users "create_by" value.  To get a
history of a row -- just make sure the primary key is imutable (never changing)
and

select * from t_tbl
where primary_key = some_value
order by end_date
/

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:59412348055
for an alternative method.
Review & Followup
Rating: 5
May 04, 2001
Reviewer: A reader

Rating: 5
May 04, 2001
Reviewer: A reader

Rating: 4
December 31, 2001
Reviewer: A reader

October 29, 2000 Ishaq -- Thanks for the question regarding "Row Insertion Order.", version SQL
You Asked
Row Insertion Order.

Suppose I insert three rows in a table
Is it Possible to find out which row was inserted first
i.e I want to know the insertion order of the rows.
I do not have any field like create date / time on the Table.

Thanks In Advance

Ishaq
and we said...
No, it is totally impossible.  Rows are inserted where ever
space may be.  There is no internal "order of creation" field.
Rows will come out of the table NOT in the order of insertion in
general.

If you truely need to find the order of creation, you will need
to add your own field to track that.
October 29, 2000 Dusan -- Thanks for the question regarding "Delete statement and bitmap indexes", version 8.1.6
You Asked
Hi Tom,

Lets consider partition table, each partition is based on
specific value in a foreign key column. There is a need for fast
delete of all rows for specific value in a foreign key column,
i.e.
fast partition delete in our case.
Because the amount of distinct values for foreign key column in
this table is very low (and foreign keys should be indexed), I
chose a bitmap index for this column. I have analysed the table
(computed statistics), but the delete statement is slow.
I hoped that the bitmap index can speed up the deletion process.
I know that I can truncate partition, but PK is based on one
column, so the PK unique index cannot be as LOCAL partition
unique index and after partition truncation must be rebuilt
(what, again, takes time).
Anyway, can bitmap index help during deletion process?

cheers,

Dusan
and we said...
Well, the reason foreign keys should be indexed is to avoid a
full table lock on the child in the event of an UPDATE to the
parents primary key ( should NEVER happen in my opinion) OR the
delete of the parent row.

So, if you never update the parent tables primary key (or
rarely, if every do so) and do not delete rows from the parent
table (or rarely do so) and the table is partitioned on the
foreign key -- you might not need that index.

Since the issue we are trying to solve here is one of
concurrency -- the bitmap index would be an unusual choice as
they themselves limit concurrency.

I would use a conventional btree index here (with compress
turned on perhaps to reduce storage given the value repeats
frequently).

If you are going to delete a whole partition -- you can also
look at using the extended table name --

delete from T partition(x);

That'll delete all of the rows in a given partition X and avoid
the index alltogether if you can.
October 29, 2000 raghava -- Thanks for the question regarding "wrap - what is it, how to do it.", version 8.0.6.0
You Asked
hi! tom
am new to oracle. pl.help in the following.
I want hide my stored procedures from the users.
how can i do it.
what is wrapping. how to do it.
bye
raghava
and we said...
see
http://technet.oracle.com/doc/server.804/a58236/d_wrap.htm#138
for all details.
October 30, 2000 Sanjay -- Thanks for the question regarding "How do i find the terminal ID of a system", version 7.3
You Asked
We are creating a audit log for the application. We want to
store the terminal id of the system when made the modifications
to the database record. Is there any way we can do that? if yes
then how?

Sanjay
and we said...
You can get the terminal from v$session -- however, in a
networked environment it'll not be 100% reliable (eg: if my
client is NT, I can make the terminal column be whatever I want
by naming my machine whatever I want).
October 30, 2000 Radhakrishnan -- Thanks for the question regarding "Application DBA", version 8.0.5
You Asked
Dear Tom,

Please explain me the role of an application DBA (in particular
a person who is working as DBA on Oracle Financials
Application). I would like to know from you how a regular DBA
differs from an Application DBA. If there is a difference,
kindly let me know, on which areas an application DBA needs to
concentrate.

Thanks

Ramesh
and we said...
Depends on who you ask.  Its like any other definition of "DBA"
-- it depends on what company you work for as to what the roles
are.

Many time, the apps dba is the person responsible for all of the
normal DBA stuff (backup, recovery, database wide tuning and
such) and has as the additional responsibility the application
of application patches, the maintaining of the history of
patches applied.  Also, monitoring things such as the concurrent
managers and such which may be on various machines throughout
the network.

For the traditional DBA, it is not that much different from
running a database upon which you built a large complex
application and rely on the DBAs to manage and monitor and patch.
Review & Followup
Rating: 4
need advise... June 02, 2002
Reviewer: mubeen from kuwait
Tom,

I am a certified DBA and I have over 5 yrs of oracle programming experience.
Now I am planning to swith to ERP. Can you please advise me, what could be the
best approach to make a successful career in ERP as technical
consultant/Applications DBA etc ?

thanks a lot

regs
mubeen

October 30, 2000 Liliana -- Thanks for the question regarding "Aplication for Import Data from file TEXT", version 6.0
You Asked
Hi.
Please I need a example for import to oracle a file txt.
the aplication have to get the route for a file and import the
file txt to a oracle table.

For add information:
I need a aplication for a users enter the path of file txt, and
the aplication can read and save in a table. Do you understand?

Thank You Very Much
and we said...
You'll use the file open dialog in forms then to get the name of
the file to read (see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:162612348068
for an example).

Then, you'll use TEXT_IO to read the file line by line.  You'll
parse each line and either user a STATIC SQL insert statement if
you always load into the same table or the EXEC_SQL package .
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:831427026414
for an example.
October 30, 2000 Farhad -- Thanks for the question regarding "Converting forms to JSP.", version 8.1.6
You Asked
Hi Tom,
   I would like to know that how to convert Forms6.0 to JSP?
   Mail a.s.a.p.

 Thanks,
 Farhad.
and we said...
There is only one method -- by hand.

forms is a rich client/server gui environment (even when
deployed in 3 tiers it retains much of its client server
"gui'ness".

A JSP is a stateless HTML interface.

they are completely and totally different.  There is no one step
conversion from one to the other.  Their interfaces,
capabilities, and implementations are so radically different
that it would be impossible to "convert" one to the other.  You
will need to redesign your application to take advantage of the
new environment, capabilities and missing features/capabilities.
October 30, 2000 V Siva -- Thanks for the question regarding "LOB usage", version 8.1.6
You Asked
Hi Tom,

In one of the table, used to store, email related stuff, like
sendto, copyto, subject, ..., attachment. The field attachement
should store the actual mail sent, it can be a file of type .msg

This mail will be generated from unix mail command.

So, Pleas suggest me what could be the data type, will it be LOB
or Long. I read that, it is easy to manipulate, LOB more
effeciently than LONGs. Give your comment on this. If this field
should be a LOB type, then whether it should be CLOB, BLOB,
NCLOB, or a BFILE.

Thanks,
Siva
and we said...
It'll be a LOB for sure.  You should not use LONG/LONG RAW in
8.0 and up except for backwards compatibility with existing
schemas.

Whether is should be a BLOB, CLOB, NCLOB, BFILE is upto you.

If the data is never to be in the database -- BFILE is the only
choice.  I myself prefer to put it all in the database, one
thing to backup, one thing to restore.  If you leave the msg's
on the file system -- you must coordinate backup and recovery
between the filesystem and us.

If you do put it in the database, you are probably going to
choose between CLOB and BLOB.  If you want the data to be stored
as text -- much like a very big varchar2 column, use a clob.
Otherwise -- use a BLOB.  If the data is text in nature, you'll
find clob easier to use and query with perhaps.
October 30, 2000 Chinmay -- Thanks for the question regarding "SQL Query", version Oracle8i
You Asked
I have a table - Item  with following Structure
Table Name : Item
Item_id  int,
quality  int,
rating   int
with following data
Item_id    Quality    Rating
-------    -------    ------
1          10         15
2          25          20

Need to generate a query with column name in the result set
i.e expecting the following result

1    Quality   10
1    Rating    15
2    Quality   25
2    Rating    20

How can I generate such a query with column name in the result
which I need to populate another table. My objective is to
convert the data in the table in a Name - Value pair

Thanks in advance

Chinmay
and we said...
Decode can do this nicely.  We just need another table with 2
rows (or more) in it.  We'll use that to turn each of the above
single rows into 2 rows and then use decode to pick off the
column we want:

scott@DEV816> create table t    (item_id int, quality int,
rating int );

Table created.

scott@DEV816>
scott@DEV816> insert into t values ( 1,10,15 );

1 row created.

scott@DEV816> insert into t values ( 2,25,20 );

1 row created.

scott@DEV816>
scott@DEV816>
scott@DEV816> select item_id,
  2             decode( r, 1, 'Quality', 2, 'Rating' ) What,
  3             decode( r, 1, quality,   2, rating )   Val
  4    from t,
          ( select rownum R from all_objects where rownum <= 2 )
  5  order by item_id
  6  /

   ITEM_ID WHAT                                  VAL
---------- ------------------------------ ----------
         1 Quality                                10
         1 Rating                                 15
         2 Quality                                25
         2 Rating                                 20

scott@DEV816>
October 30, 2000 Steven -- Thanks for the question regarding "bad coding? --> view on view", version V7.3
You Asked
Tom,

I have a "bad" coding written by consultant and believe you are
the only one who can find a better way to re-write it.   It is
causing performance problem.   It usually takes more than 15
seconds of Unix 2-CPU time and 300,000 Fetch (from trace tkprof
file) before result is shown.

The followings are the codings (hope you are interested):

1) from regular query:
select proj_nbr,question_id,display_ord_nbr,....
from appl_ans_view
where display_ora_nbr ....;

2) appl_ans_view
select aq.PROJ_NBR,
       aq.applicant_id,
       aq.PROTOCOL_ID,
       aq.QUESTION_ID,
       aq.QUESTION_TXT,
       aq.QUESTION_TYPE_CD,
       aq.SAME_ANSWER_IND,
       aq.DISPLAY_ORD_NBR

  FROM appl_quest_view aq, applicant_answer aa

 WHERE aa.proj_nbr (+) = aq.proj_nbr
   AND aa.applicant_id (+) = aq.applicant_id
   AND aa.question_id (+) = NVL(aq.valid_question_id,999999)
   AND aa.answer_txt (+) = NVL(aq.answer_txt,999999)
 GROUP BY aq.PROJ_NBR,
       aq.applicant_id,
       aq.PROTOCOL_ID,
       aq.QUESTION_ID,
       aq.QUESTION_TXT,
       aq.QUESTION_TYPE_CD,
       aq.SAME_ANSWER_IND,
       aq.DISPLAY_ORD_NBR
HAVING COUNT(aa.answer_txt) = 0

applicant_answer table count=8.7M rows

3) appl_quest_view (called by view listed above)
select pa.PROJ_NBR,
       pa.applicant_id,
       pq.PROTOCOL_ID,
       pq.DISPLAY_ORD_NBR,
       q.QUESTION_ID,
       q.QUESTION_TXT,
       q.QUESTION_TYPE_CD,
       q.SAME_ANSWER_IND,
       ql.proto_question_id,
       ql.valid_question_id,
       ql.answer_txt
  from project_applicant pa, question q, protocol_question pq,
question_logic ql
 where q.proj_nbr = pa.proj_nbr
   AND pq.proj_nbr = q.proj_nbr
   AND pq.question_id = q.question_id
   AND ql.proto_proj_nbr (+) = pq.proj_nbr
   AND ql.protocol_id (+) = pq.protocol_id
   AND ql.proto_question_id (+) = pq.question_id

Counts of tables used:
pa = 370K
ql = 22K
q  = 2K
pq = 4K

My question is:  do we need two views with one calling
another(they never use one view seperatly anyway), or one view
should do the job, or no view is good?    What is the better way
to put FROM clause, view first, or table first ("from
appl_quest_view aq, applicant_answer aa)?

It'll be our greatest appreciation if you can point out the
problem and possible guideline for the coding.

Thanks,

Steve
and we said...
Its not how the queries are coded above -- but rather the types
of questions you might use against them that count.

The above queries may very well be the most performant way to
get what you want -- then again, not knowing the questions you
ask of the views -- they may be very bad.

Without knowing the questions -- its VERY hard to answer --
however, I can suggest that the view:

select aq.PROJ_NBR,
       aq.applicant_id,
       aq.PROTOCOL_ID,
       aq.QUESTION_ID,
       aq.QUESTION_TXT,
       aq.QUESTION_TYPE_CD,
       aq.SAME_ANSWER_IND,
       aq.DISPLAY_ORD_NBR

  FROM appl_quest_view aq, applicant_answer aa

 WHERE aa.proj_nbr (+) = aq.proj_nbr
   AND aa.applicant_id (+) = aq.applicant_id
   AND aa.question_id (+) = NVL(aq.valid_question_id,999999)
   AND aa.answer_txt (+) = NVL(aq.answer_txt,999999)
 GROUP BY aq.PROJ_NBR,
       aq.applicant_id,
       aq.PROTOCOL_ID,
       aq.QUESTION_ID,
       aq.QUESTION_TXT,
       aq.QUESTION_TYPE_CD,
       aq.SAME_ANSWER_IND,
       aq.DISPLAY_ORD_NBR
HAVING COUNT(aa.answer_txt) = 0

could probably be rewritten as:

select aq.PROJ_NBR,
       aq.applicant_id,
       aq.PROTOCOL_ID,
       aq.QUESTION_ID,
       aq.QUESTION_TXT,
       aq.QUESTION_TYPE_CD,
       aq.SAME_ANSWER_IND,
       aq.DISPLAY_ORD_NBR
  FROM appl_quest_view aq
 WHERE NOT EXISTS
      ( select 1
          from applicant_answer aa
         WHERE aa.proj_nbr = aq.proj_nbr
           AND aa.applicant_id = aq.applicant_id
           AND aa.question_id  NVL(aq.valid_question_id,999999)
           AND aa.answer_txt = NVL(aq.answer_txt,999999) )

which appears to be equivalent as long as

aq.PROJ_NBR,aq.applicant_id,aq.PROTOCOL_ID,aq.QUESTION_ID,
aq.QUESTION_TXT,aq.QUESTION_TYPE_CD,aq.SAME_ANSWER_IND,
aq.DISPLAY_ORD_NBR

it unique (it seems it should be to me).

That way, instead of joining EVERY row in the AQ view to the AA
table (all 8.7million of them), this will just do an index read
into AA (assuming a nice index on
application_answer(proj_nbr,application_id,question_id,answer_txt
) or some subset thereof).

That might perform better for you.

If you find that to be equivalent -- it'll be easier to roll the
other view into that query.

If possible you should try to discover if the outer join to QL
is really needed.  It is only needed i there are PQ rows that
have values that might not be in QL.  The outer limits the
optimizers ability to rearrange things.

Getting rid of the group by and having should definitely speed
up the first view above though.  It will allow us to push
predicates down into the view (not possible with those
aggregates) and to get you back the first row of data before we
discover the last row of data (right now we basically have to
answer the entire query before you get the first row).

Give that a try.
October 30, 2000 wallacel -- Thanks for the question regarding "init.ora", version 8.1.6
You Asked
Tom:

1.oracle enterprise manager Database tuning with oracle tuning
pack part No.A76918-01 page 4-13 mention two documents.
one is oracle server reference the other is oracle server tuning

where i can find it?

also at page 5-10, it says set Optimizer search limit to
100/number_of_concurrent_users, does that mean if
number_of_concurrent_users is 100 then optimizer will
only consider one table in the FROM clause?

Last and most important.
is that possible , you send me serveral copy of
your init.ora file so i can have a general feeling of
the parameter setting. I have no feeling now,
I know different system have different setting,
but i just want to got a feeling of it.
Thanks a lot
and we said...
1)
designing and tuning manual:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76992/toc.htm
server reference:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76961/toc.htm

2) least important.  not relevant.  without knowing

o what I do
o why I do it
o what my database is tasked with doing
o what my system configuration is
o how many users I have
o what they do
o how much ram I have
o what else this machine is doing
o what 3rd party apps I might be running
o etc etc etc etc etc etc

it is totally useless.  The sample init.ora's are as generic as
we can get.  As soon as you start customizing it -- it is yours
and yours alone.
October 30, 2000 Kasthuri -- Thanks for the question regarding "Loadjava error", version 8.1.5.1
You Asked
Hi Tom,

 when i try to load a java class i get the following error. The
Class that it refers to (MessageSender) is available in a jar
file thats put in the class path.

loadjava -user oau1dbo/oau1dbo@oau1 AdminSvcMsgSender.class
-verbose -resolve
initialization complete
loading  : com/emplanet/jms/AdminSvcMsgSender
creating : com/emplanet/jms/AdminSvcMsgSender
resolver :
resolving: com/emplanet/jms/AdminSvcMsgSender
Errors in com/emplanet/jms/AdminSvcMsgSender:
    ORA-29521: referenced name com/emplanet/jms/MessageSender
could not be found
loadjava: 1 errors

-Do i have to load the jar file too. I tried that and it gave me
the following error...
ar
loadjava -user oau1dbo/oau1dbo@oau1 jms.jar

Error while processing jar jms.jar
    Exception java.io.IOException: Load Java is unable to handle
compressed entries: com/emplanet/jms/SetPINDataObj.class
loadjava: 1 errors

Can i not just put the jar in the CLASSPATH and then load the
necessary class file and try to use it?

I have the following procedure -

CREATE OR REPLACE PROCEDURE PostAdminServiceMsg( p_url_addr_in
IN varchar2, p_StatusDesc_in IN varchar2, p_flg_in IN varchar2 )
AS LANGUAGE JAVA NAME
'com.emplanet.jms.AdminSvcMsgSenderIntf.postAdminServiceMsg(java.
lang.String, java.lang.Sring, java.lang.String)';
- This gives a Class not resolved error if i try executing the
procedure.

Please let me know as to how i should go about in this.
Thanks & Regards
Kasthuri
and we said...
Consider the database as if it were a "different machine" and
loadjava was "ftp".  You are putting "AdminSvrMsgSender.Class"
onto this other machine but the jar files it needs
(MessageSender) are elsewhere.

We need to have all of the code loaded up.

Loadjava cannot load compressed jar files.  Unjar it
MessageSender and rejar it without compression.  then, load it
into the database.
October 30, 2000 Subhakar -- Thanks for the question regarding "Table Replication", version 8.1.7
You Asked
Hi Tom,

I need to replicate a table in the same instance with a
different name. ie.. I need both the tables in the same
instance. I need to rename the Indexes, constraints, synonyms,
and views on the new table. So, I did an export of the table
(TABLE MODE) and imported it with the index file option and then
renamed the table, Indexes and constraints in the index file.
The problem is in table level export the views, synonyms and
grants(Other than direct grants on table) are not exported. How
do I accomplish this?

Thankx in advance,
Subhakar
and we said...
You'll have to do the views, synonyms and grants manually.  EXP
is not any good at doing this.

The other option would be to copy the entire schema -- that'll
get the views and private synonyms (but not public synonyms)

Only a full database export would get the system level grants
and public synonyms.

You can write a script to extract the views, grants and synonyms
from the data dictionary easy enough.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:683824732911
for how to get the views -- getting the grants and synonyms
would be similar.
October 31, 2000 Loretta -- Thanks for the question regarding "password validation", version 6.0
You Asked
How do I create a logon screen and validate the username and
password from a table.  I've already tried modifying the
"built-in" with no success.
and we said...
Well, you would have to hard code or otherwise make available
some common username and password available to your form so the
form can log in as some known username.

Then, in the on-logon trigger, you would put NULL;  That would
effectively turn it off.

you would log on with that username and password and perform a
query using the username and password.

so, you might build a block, LOGIN_BLOCK with fields

o username (text)
o password (text)
o doit     (button)

the button would have a when button pressed trigger with the
code:

logon( :login_block.username, :login_block.password );

The ON-LOGON form trigger would have code like:

if ( :login_block.username is not null and
      :login_block.password is not null )
then
   logon( some_username, some_password );
   validate( :login_block.username,
             :login_block.password );
end if;
October 31, 2000 Fatai -- Thanks for the question regarding "Ordering interdependent tables using their Primary - Foreign key relationships", version 7.2.3.0.0
You Asked
I have a number of tables in my user_tables dictionary, All of
which are directly or indirectly dependent on each other by
virtue of their Primary - Foreign /key relationships.

Is there any code around that can help me order these tables
such that if I want to DELETE or INSERT into these tables, I
will be able to achieve this in the right order without
violating the child - Parent key constraints.

I have tried manually doing this but to no avail.

I also though about using the walking tree method which I don't
think I am doing properly

Please Any help will be appreciated.
and we said...
For the delete, I would implement the foreign keys with ON
DELETE CASCADE and just delete the parent table.

For the inserts -- well, I cannot imagine a situation where I
would not inheritly KNOW what the relationship where when
inserting but ....

In 8.0 and later, i would use deferred constraints.  In that
fashion, I can insert in any order and the validation of the
constraint is deferred until you commit.  Since you have 7.2,
that is not workable for you...

You should be aware that there are cases where you cannot get
the right order.  It is totally possible (common even) for A to
have a foreign key to B and B to A.  In this case -- the only
solution is to insert NULL foreign keys and update them after
the fact -- especially when putting that first row in there!

What might work for you is a query against user_constraints.  We
have to use a temporary table since the connect by won't work on
the join.  We can use a permanent temporary table if you
surround the INSERT+OPEN Query with a savepoint and rollback to
savepoint as I have below.  That way, the temp table always
appears to be empty.

ops$tkyte@ORA8I.WORLD> create table p ( pk int primary key );

Table created.

ops$tkyte@ORA8I.WORLD> create table c1( pk int primary key,
  2                   fk int references p );

Table created.

ops$tkyte@ORA8I.WORLD> create table c2( pk int primary key,
  2                   fk int references c1 );

Table created.

ops$tkyte@ORA8I.WORLD> create table c3( pk int primary key,
  2                   fk int references p );

Table created.

ops$tkyte@ORA8I.WORLD> create table c4 ( pk int primary key,
  2                    fk int references c3 );

Table created.

ops$tkyte@ORA8I.WORLD> create table c5( pk int primary key,
  2                   fk int references c4 );

Table created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> drop table temp;

Table dropped.

ops$tkyte@ORA8I.WORLD> create table temp  ( child varchar2(30),
parent varchar2(30) );

Table created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> savepoint foo;

Savepoint created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> insert into temp
  2  select a.table_name child, b.table_name parent
  3    from user_constraints a, user_constraints b
  4   where a.constraint_type = 'R'
  5     and a.r_constraint_name = b.constraint_name
  6  /

6 rows created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select parent, rpad( '*', level, '*'  )
|| child child
  2    from temp
  3   start with parent = 'P'
  4   connect by prior child = parent
  5  /

PARENT                         CHILD
------------------------------ --------------------
P                              *C1
C1                             **C2
P                              *C3
C3                             **C4
C4                             ***C5

ops$tkyte@ORA8I.WORLD> rollback to foo;

Rollback complete.

ops$tkyte@ORA8I.WORLD>
Review & Followup
Rating: 4
May 15, 2001
Reviewer: Srinivas from Memphis,TN

October 31, 2000 Reji -- Thanks for the question regarding "JDBC Qn", version 8.1.6
You Asked
Tom:
     We have a multi-threaded server using JDBC to get/set data
from the database.  We are using a single connection and sharing
in all these threads ( two threads ).  My qn is Is Oracle's
implementation of JDBC thread safe?  If not, Is it possible to
make it thread safe? If the answer is yes, would you please
point me to some URLs to take a look at some detailed overview
about Oracle's JDBC implementation.

The reason that I am asking this qn is somehow, the server(our
server) is hanging on Solaris env and attached is the stack
trace)

------------STACK TRACE------------------

n[1] where all
main:
  [1] oracle.jdbc.driver.OracleConnection.needLine
(OracleConnection:1150)
  [2] oracle.jdbc.driver.OracleStatement.doExecuteOther
(OracleStatement:1230)
  [3] oracle.jdbc.driver.OracleStatement.doExecuteWithBatch
(OracleStatement:1353)
  [4] oracle.jdbc.driver.OracleStatement.doExecute
(OracleStatement:1760)
  [5] oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout
(OracleStatement:1805)
  [6] oracle.jdbc.driver.OraclePreparedStatement.executeUpdate
(OraclePreparedStatement:322)
  [7] com.apogeenet.system.server.HeartBeatGenerator.beat
(HeartBeatGenerator:149)
  [8] com.apogeenet.system.server.HeartBeatGenerator.beat
(HeartBeatGenerator:131)
  [9] com.apogeenet.rating.engine.EngineController._beat
(EngineController:485)
  [10]
com.apogeenet.rating.engine.EngineController.processRecords
(EngineController:661)
  [11] com.apogeenet.rating.engine.EngineController.<init>
(EngineController:209)
  [12] com.apogeenet.rating.engine.EngineController.main
(EngineController:995)
Thread-2:
  [1] oracle.jdbc.driver.OraclePreparedStatement.sendBatch
(OraclePreparedStatement:390)
  [2] oracle.jdbc.driver.OracleConnection.commit
(OracleConnection:474)
  [3]
com.apogeenet.system.performance.PerformanceMonitor._collectStati
stics (PerformanceMonitor:325)
  [4] com.apogeenet.system.performance.PerformanceMonitor.run
(PerformanceMonitor:71)
Thread-4:
  [1] java.lang.Thread.sleep (native method)
  [2]
com.apogeenet.rating.engine.RatingEngine$UpdateCurrentTime.run
(RatingEngine$UpdateCurrentTime:145)
Thread-5:
  [1] java.net.PlainSocketImpl.socketAccept (native method)
  [2] java.net.PlainSocketImpl.accept (PlainSocketImpl:406)
  [3] java.net.ServerSocket.implAccept (ServerSocket:240)
  [4] java.net.ServerSocket.accept (ServerSocket:224)
  [5] com.apogeenet.system.db.DBEventManager.waitForMessage
(DBEventManager:244)
  [6] com.apogeenet.system.db.DBEventManager.run
(DBEventManager:209)
  [7] java.lang.Thread.run (Thread:479)
main[1]
--------------------END OF STACK TRACE --------------

Thx
Reji
and we said...
Do you have a mutex of some sort around each database call?
They must be syncronized -- you cannot start another jdbc call
while one is in process UNLESS they each have their own
connection.

Yes, it is threadsafe.

No, two threads cannot SIMULTANEOUSLY share a connect -- you
must single thread (syncronize) that access.
October 31, 2000 Eli -- Thanks for the question regarding "Using local temp tablespace", version 8.1.6
You Asked
Hi tom
I read the article in the oracle magazine about LOCAL tablespace
.
I start with TEMP tablespace and I don't see any improvement
with the new option .
I made a test with table called item with the following column
       ITEM_ID
       CUSTOMER_ID
the item table include 110000 rows
The following is what I do:
I run query with user that have ordinary temp tablespace and run
the same query with user that have local temp tablespace.
The TEMP tablespace definition of the ordinary and the local
are:
ORDINARY ------------------------------
CREATE TABLESPACE "TEMP" DATAFILE
'D:\ORANT\ORADATA\ELI\TEMP01.DBF'
SIZE 20971520
AUTOEXTEND ON NEXT 655360  MAXSIZE 33554416K DEFAULT STORAGE "
 "(INITIAL 65536 NEXT 65536 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0)"
 " ONLINE TEMPORARY"
LOCAL ----------------------------------
CREATE TEMPORARY TABLESPACE tempyc
TEMPFILE 'D:\orant\oradata\ELI\tempyc01.dbf' size 6m
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 64K;

I change the value of the sort_area_size to 1
And I run the following query

select item_id,customer_id
from
 item order by item_id,customer_id

ORDINARY temp tablespace
--------------------------

call     count cpu elapsed disk query current  rows
------- ----  ---- ------- ---- ----- -------  ------
Parse   1     0.00 0.00    0    0     0        0
Execute 2     0.00 0.00    0    0     0        0
Fetch   7184  5.21 16.73   3916 3275  173      107741
------- ----  ---- ------ ----- ----- -------  ------
total   7187  5.21 16.73  3916  3275  173      107741

LOCAL tablespce

call    count  cpu  elapsed disk query current rows
------- -----  ---- ------- ---- ----- ------- ------
Parse   1      0.01 0.01    0    0     0       0
Execute 2      0.00 0.00    0    0     0       0
Fetch   7184   4.44 17.44   3935 3275  215     107741
------- -----  ---- ------ ----- ---- ----     -------
total   7187   4.45 17.45  3935  3275 215      107741

Like you see the elapsed  and disk  usage is more high in LOCAL
and we said...
The CPU time is lower and that is what counts in the end.

Lets look at the above and see what conclusions we can draw.
The physical reads from disk are:

3916 vs 3935.  That is not a material difference (less then
1/2%).  They are for all intents and purposes the same.

The query mode blocks gotten are IDENTICAL -- no difference.

the current mode blocks is slightly higher but again, barely
different -- looks like most of them came from the cache
anyway...

What is different however is the CPU time it took.  The locally
managed tablespace use 85% of the CPU as compared to the
dictionary managed one.  that is a pretty large difference.  The
elapsed time however is apparently larger.  That does not mean
this query took longer to execute -- what that means to mean is
that there was CONTENTION for resources on the machine during
the query against the locally managed tablespace that simply was
not present during the dictionary managed query.  That 17.45
elapsed time means it took 17.45 seconds to get our 4.45 seconds
of CPU time and do our 3,935 reads.  If it took 17.45 seconds to
get our 4.45 seconds of CPU time -- it would have taken longer
to get 5.21 seconds of CPU time at that point in time on that
machine.  Meaning -- if you had run the dictionary managed
tablespace query at that exact point in time -- it would have
almost certainly taken longer (elapsed timewise) then the query
you did run.

You need to do this sort of stuff in isolation if you want to do
an unbiased comparision or ignore the elapsed time or remove the
contention so that CPU and elapsed are much closer to eachother.
October 31, 2000 Mohamed -- Thanks for the question regarding "Converting Long to CLOB", version 8.1.5.0
You Asked
Dear Tom,

How does the conversion of a Long Column in a table to CLOB
affects the performance and storage?

Pls. reply soon.

Thanks and Regards,
rafi.
and we said...
It should make it faster and should take about the same amount
of space.

It'll definitely speed up any full scans of the table that
contained the long as the CLOB is stored out of line once it
exceeds about 4k.  A long was stored inline and a full scan had
to read all of it.

It'll be faster to piecewise access random sections of the CLOB
as the individual chunks are indexed -- with a CLOB getting
bytes 1,000,000 to 1,000,005 is very fast.  With a LONG, we
always had to start at byte 1 and read through 1,000,000 bytes
to get your data.

They are generally so much better then LONGs.
October 31, 2000 Ryno -- Thanks for the question regarding "ASP query a ORACLE table", version 8.1.5
You Asked
Hi Tom,

I am tasked to Migrate an MS Access database to an Oracle
database.  This seems to be very easy with "Oracle Migration
assistent for MS Access".

My question is that an ASP will query the Oracle database and
are only interested in a few records (rows) of data at a time.
The web developmer told me that he can use a Limit command with
MS Access to limit the records reteived.  For example: limits
records to 2-9 and it will return records 2 to 9 (8 ROWS).

Can you please give me some SQL to do the limit statement in
Oracle?

Thank you & Regards
Ryno van Rooyen
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:127412348064
...
October 31, 2000 simon -- Thanks for the question regarding "Date processing", version 8.1.6.0.0
You Asked
How can I view the date & time of a date field and then increase
it by 1 hour and 30 minutes. Thanks S.
and we said...
select to_char( date_field, 'dd-mon-yyyy hh24:mi:ss' )
  from T
/

to view it
and to add 1.5 hours:

set date_field = date_field + (1/24 * 1.5)

when you add 1 to a date -- you get 1 day added.

1/24 = 1 hour
1/24/60 = 1 minute
1/24/60/60 = 1 second
October 31, 2000 Serguey -- Thanks for the question regarding "Interaction with user while in DB stored procedure", version 6i
You Asked
Hi Tom!

Can you suggest any solution for my problem?
I have a forms application and some stored procedure. And while
procedure is executing I need to ask user about what to do if
any conditions occur. This kind of dialog must appear in form.
So in other words, is there any possibilty to suspend procedure
flow, ask user a question, retreive an answer and continue
procedure execution?
and we said...
Only by breaking the stored procedure into 2 pieces which can be
done easily using a package.

The package can be used to maintain any "state" you need to
between the invocation of part1 and part2 -- including open
cursors and so on.

If the procedure is a client side procedure (written in forms)
you can put an ALERT up at any point in your processing to get
feedback from them as well.
October 31, 2000 Sarma -- Thanks for the question regarding "Password selection ", version oracle 8.0/forms 4.5
You Asked
if i know the username,how to get the corrct password from
dba_users?

suppose if i am using scott/tiger username/password in one
of the database.
suddenly if someone change the password of that user 'scott'.
i can get the password from dba_users, but if i use that
password
it will not accept, how to get the correct password by knowing
the username?
Can you expalin me in detail
and we said...
That would sort of defeat the purposes of passwords.

If you are

o someone with access to DBA_USERS
o someone with the ALTER USER privelege

There is a way.  It requires changing the target users password
for a moment, logging in as them with this new - known password
-- and then reseting theirs back.  It works well in SQLPlus.  I
use it myself all of the time.

See
http://osi.oracle.com/~tkyte/Misc/su.html
for howto.
October 31, 2000 Reji -- Thanks for the question regarding "Connections/Process", version 8.1.6
You Asked
Tom:
    I have a DB server in a dedicated server mode.  How do I
    find out how many connections per client is using at
    a given time?

   -Thx
   -Reji
and we said...
By definition -- a client is using 1 connection.  That is our
definition of a client.

If you want to find out how many connections a named user
currently has -- you can:

select username, count(*) from v$session group by username;

By program (which can be "flaky") you can add PROGRAM to the
select and group by list.
October 31, 2000 Irshad. -- Thanks for the question regarding "Today's CLOB question.", version 8.1.5
You Asked
Hi,

In one of the answers today (enclosed here), you said CLOB is
stored out of line once it exceeds 4K. What does that mean? A
bit of explanation please.

Irshad.
-----------------------------------

Dear Tom,

How does the conversion of a Long Column in a table to CLOB
affects the performance and storage?

Pls. reply soon.

Thanks and Regards,
rafi.

-----------------------------------------------------------------
---------------
and I said...

It should make it faster and should take about the same amount
of space.

It'll definitely speed up any full scans of the table that
contained the long as the CLOB is stored out of line once it
exceeds about 4k.  A long was stored inline and a full scan had
to read all of it.

It'll be faster to piecewise access random sections of the CLOB
as the individual chunks are indexed -- with a CLOB getting
bytes 1,000,000 to 1,000,005 is very fast.  With a LONG, we
always had to start at byte 1 and read through 1,000,000 bytes
to get your data.

They are generally so much better then LONGs.
and we said...
A lob in general has three pieces

o the pointer (locator) -- the actual LOB itself, what you get
from EMPTY_CLOB() for example

o an index to the chunks of the lob.  the  lob index.

o the lob data itself.  This is pointed to by the lob index, the
lob index is pointed to by the lob pointer (locator)

Lob data may be stored INLINE -- right in the table itself -- or
out of line, in another segment -- even in another tablespace.

You can control this behavior using the "ENABLE|DISABLE storage
in row" clause when setting up the lob columns in the
create/alter statements.
October 31, 2000 Seetharaman -- Thanks for the question regarding "Oracle Calendar", version Oracle 8i
You Asked
Hi Tom,

  Greetings!. and thanks a lot for your immediate previous
replies.

1.  Now, I have an application which has to store the dates of
working days in a calendar..  It should omit saturday and
Sunday, other dates it has to genereated automatically.

  Input parameter will be Year.

2. I have a table with two objects in it.. I now want to create
unique index (primary) key for the Objected (nested) table's one
field.. I tried but in vain,, How to do that?..

  Example

  desc sstest

  id number(3)
  roletab  rolestable

  desc rolestable

  Uniqueid  varchar2(10)
  name      varchar2(30)
  address   varchar2(10)

now I want to make uniqueid as primary key..  Pls. lemme know
this

regards

Seetharaman Srinivasan
and we said...
1) are you asking for a query to return all days in the year
except for saturday and sunday???

If so,

select trunc(sysdate,'yyyy')+r
  from ( select rownum-1 r from all_objects where rownum <= 366
)
 where to_char( trunc(sysdate,'yyyy')+r, 'DY' )
          not in ( 'SAT', 'SUN' )
and trunc( trunc(sysdate,'yyyy')+r,'yyyy') =
       trunc(sysdate,'yyyy')

will do that.

2)

Just index the nested table:

ops$tkyte@DEV816> create type t_type as table of number
  2  /

Type created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create table t        ( x int, y t_type )
  2  nested table y store as y_tab;

Table created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> alter table y_tab add constraint y_tab_unique
unique(column_value);

Table altered.

ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t values ( 1, t_type(1,2) );

1 row created.

ops$tkyte@DEV816> insert into t values ( 2, t_type(2,3) );
insert into t values ( 2, t_type(2,3) )
*
ERROR at line 1:
ORA-00001: unique constraint (OPS$TKYTE.Y_TAB_UNIQUE) violated
October 31, 2000 Baljinder -- Thanks for the question regarding "Timed_statistics parameter", version 8.0.5
You Asked
Tom
If I set "Timed_statistics" parameter as "TRUE" in init.ora file
& restart the instance. Does oracle starts collecting timed
statistics immediately/automatically or it starts when we
request oracle to do that i.e like "alter session set
sql_trace='TRUE' or setting DB_BLOCK_LRU_EXTENTED_STATISTICS
parameter.I am trying to understand this concept deeply please
help me out.

TIA
Howie
and we said...
Timed statistics is turned on as soon as you turn it on.  It
takes no other parameters.

You can turn it on right now via

alter system set timed_statistics=true;

you do not even need to restart.
November 01, 2000 alvaro -- Thanks for the question regarding "Transaction Security on Oracle Developer 2000", version Oracle Server Enterprise Edition 7.3.4.0.0
You Asked
I'm developing a program on developer 6.0 for keeping a record
on all changes mades on a table (updates,inserts and deletes).
The program creates a trigger on the table for storing the
information about the user who mades the changes
(username,machine,date,table,fields ...), and the old and new
values.
The options of the programs are similar when you are creating a
trigger in Developer. You choose :
* the table that you want to audit
* after or before trigger
* update or insert or delete
* for each row or for each instruction
* referencing as :NEW and :OLD ...

The program creates the trigger or generates a file with the
code for creating it.

I want to know if there are any program already made that works
like I've explained above.

If this aplication exist I want to Know if I can get it, and How
can I do it ...

Thanks  ACueto
and we said...
That is almost identical to the script I have at:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:59412348055
It lets you specify

o the table you want to audit.

Other then that -- it ALWAYS uses an AFTER ROW trigger (a before
trigger cannot capture the correct audit information -- you must
use an AFTER ROW trigger to capture row level changes.  The
BEFORE triggers might not see the row as it will ultimately
exist in the database).

The script currently only does UPDATE but is easily extented to
the other dml operations.

It does it for each row always since thats the only way to
capture the fields being modified.

It always uses :NEW and :OLD (it is a generated trigger -- who
cares what we use to reference as the user will never add
additional code to this trigger).

It is not 100% what you want but its pretty close.
November 01, 2000 David -- Thanks for the question regarding "moving a tablespace in production database to a testing database", version 8.0.6
You Asked
Dear Tom,

We need to test an application on our Oracle database but we
don't want to test it on our production database. We want to
move a tablespace from our production database into a testing
datbase. Both of the databases are in the same Sun Server. Can
we do that? How?

Thank you for your help in advance.

Regards

David Li
and we said...
In 8.0 as you have, your choices are limited -- I would look
towards EXP and IMP for this one.

EXP and IMP do not do tablespace level exports in 8.0 and
before.  You will have to discover the tables that are in this
tablespace and use:

exp ... tables=(t1,t2,...tn) ...

Alternatively, if a single user owns all of the objects, you
can:

exp ... owner=that_user ...

In Oracle8i, release 1 and up, you can "transport" a tablespace.
 This allows you to take a tablespace's datafile(s) from one
database and hook them up to another database (indexes and all).
 So, when you upgrade to 8i, that'll be the way to go.
November 01, 2000 Lola -- Thanks for the question regarding "COMMAND LINE", version VERSION8.1.5
You Asked
Hi Tom!
Is there any paskage to get the command line when you are runing
a form?
Thanks in advance
and we said...
host( 'command.com' );

will do it. (or xterm on Unix)

the form has to have been developed with this command -- the
developer of the form would have had to of supplied this
functionality.
November 01, 2000 Rich -- Thanks for the question regarding "1 to 28 check", version Oracle 8.1.5
You Asked
I'm trying to check a field call closing_date to be between 1
and 28th of the month by checking the sysdate; How would i do
that and at the same time were would i code this as a constraint
to a table or as a plsql out site of the table declaration.
Thanks for you help.

Rich
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:967430250916

ops$tkyte@8.0> create table t
  2  ( closing_date date
  3                 check( to_char(closing_date,'dd')
  4                              between 1 and 28 ) )
  5  /

Table created.

ops$tkyte@8.0>
ops$tkyte@8.0>
ops$tkyte@8.0> insert into t values ('01-jan-00' );

1 row created.

ops$tkyte@8.0> insert into t values ('28-jan-00' );

1 row created.

ops$tkyte@8.0> insert into t values ('29-jan-00' );
insert into t values ('29-jan-00' )
            *
ERROR at line 1:
ORA-02290: check constraint (OPS$TKYTE.SYS_C0023894) violated
November 01, 2000 Sambavan -- Thanks for the question regarding "Env setup for java", version 8.1.6
You Asked
Hi Tom,

I have been having trouble in figuring out what unix env, should
I set to develop an application that would be using oracle.* and
javax.* packages. Could you pl. tell me of what are environments
I have to set to successfully compile my application.

My second question is that does oracle copy these packages at
the time of installation of server or client?

Thanx,
Sam
and we said...
I'll assume you want to use JDK version 1.2.x

You should have your path set to include the javac and java
programs which, for me, is /usr/java1.2/bin.  You probably could
have installed this elsewhere.

Here are some of the server-based JAR and ZIP directory
locations. You can download most of these from TechNet and put
them wherever you want, these are where we would put them.  You
will just append the full path name for each JAR and ZIP you
want to your CLASSPATH environment variable.

$ORACLE_HOME/jdbc/lib/
ZIP files for JDBC connectivity
Append classes12.zip and nls_charset12.zip to your classpath

$ORACLE_HOME/rdbms/jlib/
JAR files for replication, advanced queueing, "normal" java
messaging API, etc.

$ORACLE_HOME/jlib
Lots of "standard" JAR files for SSL, XML parsers, etc.

$ORACLE_HOME/sqlj/lib
    runtime.zip and translator.zip are necessary for generating
and using SQLJ
November 01, 2000 Stanley -- Thanks for the question regarding "changing next param of snapshots - user_jobs", version 8.0.5
You Asked
hi tom,
i have a problem with changing the next parameter of
a snapshot.
i execute the following command:

DATOWNER@PROJA SQL>  alter snapshot testa
                     refresh complete with rowid
                    next  NEXT_DAY(TRUNC(SYSDATE),
                         'TUESDAY') + 12/24 + 7/(2*24);

Materialized view altered.

Now i query user jobs as follows:

DATAOWNER@PROJA SQL> SELECT
SUBSTR(what, 35, LENGTH(what) -  38) AS SNAPSHOT,
SUBSTR(TO_CHAR(last_date, 'MM/DD/YY HH24:MI:SS'), 1, 20) AS
LAST_DATE,
SUBSTR(TO_CHAR(this_date, 'MM/DD/YY HH24:MI:SS'), 1, 20) AS
THIS_DATE,
SUBSTR(TO_CHAR(next_date, 'MM/DD/YY HH24:MI:SS'), 1, 20) AS
NEXT_DATE,
job
FROM       user_jobs;

throws up the same row as before executing the alter snap.

TESTA 11/01/00 10:30:20 11/08/00 10:30:20        873

(user_jobs does not show the new date which is 11/07/2000
03:30:00 PM)

can u enlighten me why this is so?

thanks in advance.

Stan
and we said...
You changed the formula the snapshot will use to compute the
NEXT time to run after it next runs -- you did not change the
next time it'll run, you changed the formula it will use to
compute the next time when it DOES run.

Here is an example showing this.  My job queue internal is about
1 minute.

ops$tkyte@8.0> create snapshot t_snap
  2  refresh complete
  3  next sysdate+1/24/60
  4  as
  5  select * from t
  6  /
Snapshot created.

ops$tkyte@8.0> select what, next_date from user_jobs
  2  /

WHAT                           NEXT_DATE
------------------------------ --------------------
dbms_refresh.refresh('"OPS$TKY 01-nov-2000 20:50:11
TE"."T_SNAP"');

ops$tkyte@8.0> alter snapshot t_snap
  2  refresh complete
  3  next sysdate+1
  4  /

Snapshot altered.

ops$tkyte@8.0> select what, next_date from user_jobs
  2  /

WHAT                           NEXT_DATE
------------------------------ --------------------
dbms_refresh.refresh('"OPS$TKY 01-nov-2000 20:50:11
TE"."T_SNAP"');

so, just like you -- the next_date does not change.  but the
formula to calculate it did.  My original formula says to set
the next_date to 1 minute later.  My new one says to set it 1
day later.

We'll wait a minute for the job to run and see what happens...

ops$tkyte@8.0> exec dbms_lock.sleep(90)

PL/SQL procedure successfully completed.

ops$tkyte@8.0> select what, next_date from user_jobs
  2  /

WHAT                           NEXT_DATE
------------------------------ --------------------
dbms_refresh.refresh('"OPS$TKY 02-nov-2000 20:50:13
TE"."T_SNAP"');

That shows the new formula is used the next time the job runs
-- the next run date for this is now tomorrow, not 1 minute from
now

Now, if you want to change the next RUN time for the job, you
would reset the START WITH, not the NEXT.  Continueing with the
same example from above:

ops$tkyte@8.0> alter snapshot t_snap
  2  refresh start with sysdate+1/24;

Snapshot altered.

ops$tkyte@8.0> select what, next_date from user_jobs
  2  /

WHAT                           NEXT_DATE
------------------------------ --------------------
dbms_refresh.refresh('"OPS$TKY 01-nov-2000 21:54:42
TE"."T_SNAP"');
November 01, 2000 Randy -- Thanks for the question regarding "Network routing w/SQLPlus COPY", version 8.1.6
You Asked
Let's say you have three machines:  two of them have instances
on them, and the other is only a client.  Let's then say I run
SQLPlus session from the 3rd (client) machine and issue a COPY
command as follows:

COPY FROM user/pass@instance_1 TO user/pass@instance_2 APPEND
table_1 USING select_stmt

Is Net8 smart enough to route the network traffic b/t the two
machines where the instances reside (instance_1 and instance_2),
or does ALL the data flow through this third machine where the
session is run?

I ask because the connection b/t my two instances is fast, but
it is very slow in and out of this third box.  I suspect this is
killing me, and that I should only run the COPY from either of
the two instances' host machines.

Thanks.
and we said...
It'll all flow between the 3'rd machine.

The sqlplus copy command works like this -- sqlplus is using 2
sessions. Your sqlplus session is connected to instance_1 and it
is connected to instance_2.  Sqlplus fetches from instance_1 and
inserts into instance_2 -- this is how is can do array
processing, commit counts and so on.

Net8 isn't really involved in the implementation of the copy
command.

Now, if you setup a database link from instance_1 to instance_2
(or vice versa) and run the statment:

 insert into t select * from t@instance_2

Then all data will flow between instance_1 and instance_2 and
nothing will come back to the sqlplus client other then a return
code.  You'll lose the ability to commit every N records and so
on (thats what sqlplus the client has been doing) but the
traffic will be point to point, not pull and push.
November 01, 2000 Arun -- Thanks for the question regarding "Inserting New Rows with Old Data", version Oracle 8.1.5
You Asked
How can i insert new rows into a table with the data from this
table itself but with different Primary Keys.

Say i have a table MYTABLE, like this
PK       Col1       Col2 ......
P1       A1         A2
P2       B1         B2
P3       C1         C2
...
...
and so on.

I have a Map file (Excel Sheet)like this
PK_Old         PK_New
P1             N1
P2             N2
P3             N3
...
...
and so on.

Now i want to insert new rows into this table with N1, N2 and
N3
But the Data for each new row will be same as the data
corrosponding to the Mapped key in the Map file

So, the New table after insertion should look like this
PK      Col1      Col2......
P1      A1        A2
P2      B1        C2
P3      B1        C2
...
...
N1      A1        A2
N2      B1        C2
N3      B1        C2
...
...
and so on.

First, how can i load the Data from the Map file to the
table.
Can i do it through some straight query.

Second, What would be the Query to insert new rows with the old
data.

Thanks in Advance,
Arun
and we said...
To load the spreadsheet -- probably easiest to save it in CSV
format and use SQLLDR.

If you get a file like this:

LOAD DATA
INFILE *
INTO TABLE MAP
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(PK_OLD,PK_NEW)
BEGINDATA
P1,N1
P2,N2

You can load it right up with sqlldr.

Then, it is easy to get the new rows. It'll simply be:

insert into T
select map.pk_new, T.col1, t.col2, ....
  from T, MAP
 where t.pk = map.pk_old
/
November 01, 2000 Doug -- Thanks for the question regarding "Error Starting EXPORT program", version 8.1.6
You Asked
Tom,
I'm trying to EXPORT with Net8 using Windows98... however when I
enter:
 exp scott/tiger@myservicename FILE=export.dmp FULL=Y

I get a dialog box pop up that says:
    Error Starting Prorgram
The ORAVSN8.DLL file is linked to missing export
ORACORE.DLL:slzgetvar

I've just re-installed the complete Oracle 8.1.5 client software
and get the same thing...

What am I doing wrong???

Thanks...
and we said...
The Oravsn8.dll file is normally installed on the server (in the
bin directory  under the oracle home directory),  but not the
client software. The remedy for  this situation would be to copy
the missing file over from the server install  at
Oracle_Home\bin to the client into Oracle_Home\bin.

NOTE: Copy the oravsn8.dll from an 8.1.5 server. Do not copy
from an 8.1.6  server. The 8.1.6 oravsn8.dll will not work and
lead to a further error  while looking for a variable from the
ora8core.dll.

The file can be located and extracted from CD if the server is
not available.  The file is located at:

stage\Components\oracle\rdbms\8.1.5.0.0\1\DataFiles\liboes.0.0.ja
r

The oravsn8.dll file can be extracted using winzip (first start
winzip, then open liboes.0.0.jar) -- if you have winzip.  If you
have JDK, you may issue the following command:

    jar xvf liboes.0.0.jar
November 01, 2000 gabriel -- Thanks for the question regarding "Sub querry", version 8.1
You Asked
I have two tables:

Tab1 Detail(Proj, Status, Etc)
Proj    Status
1        Open
1        Closed
2        Working
3        Closed

Tab2 Project(Proj, Etc)
Proj
1
2
3
4
5
6

I want all projects where there is no open or working detail.
However, my querry:

Select Project.proj from project
where Project.proj not in
  (select Detail.proj from detail
    where upper(Detail.status) in ('OPEN', 'WORKING'));

does not return any records.  Clearly Proj 3, 4, 5 and 6 should
have come back.  Any reason why?

gabe
and we said...
Ok, I created your tables with your data above.  Then I ran your
query and got:

ops$tkyte@ORA8I.WORLD> Select Project.proj from project
  2  where Project.proj not in
  3    (select Detail.proj from detail
  4        where upper(Detail.status) in ('OPEN', 'WORKING'));

      PROJ
----------
         3
         4
         5
         6

 which is what you were after.  What i believe is happening
though is that you have a NULL proj in there that is OPEN or
WORKING.  A NULL in a NOT IN is always "unknown" (neither true
nor false).  Hence the query will return 0 records...  Consider:

ops$tkyte@ORA8I.WORLD> insert into detail values ( NULL, 'open'
);

1 row created.

ops$tkyte@ORA8I.WORLD> Select Project.proj from project
  2  where Project.proj not in
  3    (select Detail.proj from detail
  4        where upper(Detail.status) in ('OPEN', 'WORKING'));

no rows selected

Now I get what you do, to "fix" this (its not broken, it is
doing exactly what it is supposed to) we can code:

ops$tkyte@ORA8I.WORLD> select *
  2    from project
  3   where not exists ( select null
  4                        from detail
  5                       where detail.proj = project.proj
  6                         and upper(status) in ('OPEN',
'WORKING') )
  7  /

      PROJ
----------
         3
         4
         5
         6

or

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select *
  2    from project
  3   where proj not in ( select proj
  4                         from detail
  5                        where proj is NOT NULL
  6                          and upper(status) in ('OPEN',
'WORKING') )
  7  /

      PROJ
----------
         3
         4
         5
         6

ops$tkyte@ORA8I.WORLD>
November 02, 2000 Sam -- Thanks for the question regarding "Env java", version 8.1.6
You Asked
Tom,

Thanx for the info. Currently I run java 1.1.8 and I tried to
put all the specs in place and tried executing a simple
application. Now it seems to look for javax packages. I wonder
how to get these packages in the class path. Do they come by
default with jdk 1.1 or is it something that I have to download
and include. If so, where should I look for.

Thanx,
Sam
and we said...
javax is part of java -- the jdk, they are not Oracle specific.

You should append the following files to the classpath:

/usr/java1.1/lib/classes.zip
/usr/java1.1/lib/rt.jar

For me, they are located in /usr/java1.1/lib. Yours might be in
a different location.

Here are the oracle jdbc files that need to be appended to the
classpath:

$ORACLE_HOME/jdbc/lib/classes11.zip
$ORACLE_HOME/jdbc/lib/nls_charset11.zip

What specific javax packages are you looking for? Some more
information is needed to give you an answer.  You should see the
sunsite for more info on this as well --
November 02, 2000 Chee -- Thanks for the question regarding "Size of Host Arrays", version 8.1.6.0.0
You Asked
Hi Tom,

I have declared my host array of size 100. The problem is it
goes into infinite loop at second fetch iteration. But if I
change the array size to something smaller, say 20, everything
is fine.

Also, if I change the order of the column/field fetched in
SELECT statement, everything is fine even with array size 100.

Also, if I keep the old column order (which does not work for
array size 100), but if I call this function first before any
other functions in my .pc file, it is ok.

Any idea?

Many thanks in advanced.

regards,
chee
and we said...
I would have to see the code but it sounds like you could
possible have a bug yourself...

I would suggest in 8i and up -- you don't even bother with host
arrays for fetching in Pro*C.  Rather -- use the precompiler
option PREFETCH which can be set on the command line or in the
source itself.  In that fashion, the complexity of dealing with
the host array is gone, you can easily change the array size
without recoding, and you get the benefits of array fetching.

If you want to persue this -- I would need a test case I can run
on my system to figure out why you are seeing what you are
seeing.
November 02, 2000 greeshma -- Thanks for the question regarding "deletion of recs", version 8.0.6
You Asked
hi!
data is read and then deleted from my tables
by a program developed in VB.
what my requirement is ,after reading the records
they are not to be deleted immeadiately.i want to delete
all the read records only at midnight.is there any way
to do it from oracle end ,instead of at VB end.
thankx.bye
greeshma.
and we said...
Sure, you would update the records in VB -- sort of a flag
delete -- or have some other mechanism in place so that a stored
procedure can tell they have been "read and processed" and are
ready to be deleted.

Then, you would code a stored procedure to do the delete.  You
would use the dbms_job supplied package to schedule this job to
happen every night at midnight.  So, lets say you have created
the stored procedure "delete_data" and want to schedule it to
run every night at midnight.  You would (in sqlplus or some
other tool)

declare
  l_job  number;
begin
  dbms_job.submit( j_job,
                  'delete_data;',
                  'trunc(sysdate)+1' );
end;
/

Make sure to set the init.ora parameters

job_queue_interval
job_queue_processes

as well...
November 02, 2000 KK -- Thanks for the question regarding "DB link", version 8.1.6
You Asked
I have a Pro*C program in 8.1.6 which will call a procedure
which
in turns inserts data in a remote database(7.3.4) vis a DB link.

In the midnight, the remote database will terminate all the
connection for backup purpose.  In the meanwhile, a trace file
is generated in the local database(8.1.6).  How can I
avoid this problem?  I've tried not to call the procedure from
Pro*C at the midnight, but the trace file is still generated...

The following error is extracted from the trace file:
'SQL*Net break/reset to dblink'
and we said...
See the command:

alter session close database link <linkname>;

You can use that to shutdown the link after you aren't using it
to avoid getting terminated by the other server.

(that 7.3 instance should do a hot backup.  You shouldn't
shutdown your database every night, that'll clear the shared
pool and cache and you'll spend half of the next day warming it
up again...)
November 03, 2000 Thiruvaiyaru -- Thanks for the question regarding "Selecting rows with value '%' in them", version 8.1.6
You Asked
Tom,

I need to select rows that have % embedded in them
from a table. For eg:-
I do the following :

SQL> create table temp (name varchar2(100));

SQL> insert into temp values('abcd%efgh');
SQL> insert into temp values('zyxwvu');
SQL> insert into temp values('zywvuts%mnopqr');

When I do a :

SQL> select * from temp where name like '%%%';

I get all three rows, Whereas I need to get only  2 rows
that have '%' in the 'name' column. I tried several different
ways , but none of them worked. Your help in this would be
greatly appreciated.

Thanks
Sai
and we said...
select * from temp where name like '%\%%' escape '\';
November 03, 2000 Prashant -- Thanks for the question regarding "Global Variables", version Forms 6
You Asked
Dear sir,

I am working on forms 6. My Problem is I have created a login
form and the login is done from table. I want to track the
username of form throughout my multiform application so that
whenever the user enters any data his username should be
tracked.

In other words the first form I have developed is login form in
which the user enters a user name and password. the password is
verified from the table in the database and then after
authentication he is allowed to enter the data entry forms from
where he can enter data. Now what I want to do is keep his
username in some variable like global.variable so that whenever
he enters data from other forms his username should be
retrievable.

I think it is possible by using global variable or by passing
parameter to all the forms( which is less useful). Please tell
me how to keep alive any such variable throughout the session of
the user so that his username can be retrieved any time in the
session of the user.

NB> the username I am taking about is not database loginname and
password. I want to maintain separate userid which is retrieved
from the table I have created.
and we said...
Well, you can use global variables:

A global variable is a Form Builder variable whose value is
accessible to triggers and subprograms in any module that is
active during the current session.  A global variable stores a
character string of up to 255 characters in length.
Global variables are not formally declared the way PL/SQL local
variables are.  Rather, you initialize a global variable the
first time you assign a value to it:

:GLOBAL.my_var := TO_CHAR(:order.total * .85);

To reference a global variable, prefix the variable name with
the word GLOBAL and a colon.  The following example shows a
global variable passed as an actual parameter to a procedure
call:

calculate_discount(TO_NUMBER(:GLOBAL.my_var));

Referencing a global variable that has not been initialized
through assignment causes a runtime error.
To destroy a global variable and release its memory, use the
ERASE built-in procedure:

Erase('GLOBAL.my_var');

Or, you can pass it as a parameter to other forms.
Review & Followup
Rating: 5
Where to define Global Variable July 30, 2003
Reviewer: Vijay Ahire from Boston
Hi A'm new to form do you where to define Globle Variable & how to define.

November 03, 2000 islam ahmed -- Thanks for the question regarding "connecting developer 2000 to an oracle database", version developer R2.1 , and oracle 8.0.4
You Asked
hello ,i'm asking if u can help me with the following subject i
got developer 2000 and i failed to make it connecte to personal
oracle 8.0.4 , can u help me ,i always get error message  with
number ora-03121
and we said...
If the d2k is installed in a different oracle home from the
database or is a different release of the required support files
( i would need to know the version of forms like 5.0.xxx or
6.0.xxxx to tell you what RSF's it uses), you need to use
SQLNet.

You need to configure the listener in the 8.0.4 oracle home and
configure the tnsnames.ora file in the d2k oracle home in order
to connect and use user/password@database when logging in.
November 03, 2000 Sriv -- Thanks for the question regarding "Inter Media", version 8.1.6
You Asked
Tom,

I Intially installed oracle sw without intermedia options, then
i created db and later i updated the oracle sw with intermedia.
Do I need to execute some scripts to make the intermedia work.

When will CTXSYS user gets created. Is there any role associated
for intermedia.

Thanks

Sriv
and we said...
Assuming that you have installed the interMedia Text software,
all you need to do is run the Database Configuration Assistant
to install interMedia Text in your database.

1)  Start Database Configuration Assistant
2)  Click the radio button "Change database configuration"
3)  Select your desired database instance and enter
    your internal Password
4)  Check the checkbox "Oracle interMedia"
5)  Click the Finish button.
November 03, 2000 manmohan -- Thanks for the question regarding "how to trace the sql statements coming through net", version 8.1.6.0.0
You Asked
Hi Tom,

 Please tell me how can i trace the sql statements coming over
the net as well as the backend side.
 I need to know which statements are being fired over the net to
our database.And can i locate those ip through which these are
being fired.

 Thanks and regards
 Manmohan
and we said...
You can enable SQL_TRACE which will generate trace files on the
server.  These trace files will show all SQL activity.  They
will not show you the ip address -- they show you the database
session associated with that trace file.

You can enable auditing (audit connects) and the ip information
will be captured into the database.   You can then get the ip
address based on the session.
November 03, 2000 Willy -- Thanks for the question regarding "How to check if installed Oracle8 Server software is 32 or 64 bits", version 8.0.5
You Asked
Hi Tom,

Will appreciate if u can tell me how to check if the installed
Oracle8 Server software is 32bits or 64bits. Seen somewhere to
check a oracle file in $ORACLE_HOME/bin directory. Is it true ??
If it is, how do I make sure that it is 32 or 64 bits.

Thanks and Regards
Willy
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:364418037604
....
November 03, 2000 -- Thanks for the question regarding "XML", version version 7
You Asked
I need to store and of course query XML documents, did the
Oracle database offers any (easy) solution for this?
Regards:
Llorenç Chiner
System Analyst
Fihoca
Barcelona
Spain
and we said...
see
http://technet.oracle.com/tech/xml/
...
November 03, 2000 MD -- Thanks for the question regarding "DATABASE PROBLEM", version ORACLE 8
You Asked
 sir,

 I created new database using create database command in oracle
server. Now I  want to mount two databases at a time. One is
original one provided by oracle corporation and another one is
created by me. Your oracle database name is  orcl and my new
database name is "aptorcl". I want to share the data from both
the databases at a time. Both databases are in same server.
 awaiting your reply.

 my e-mail id is

 habibpersonal@usa.net

 thanking you sir,

 habib
and we said...
You have a misunderstanding of how separate databases work in
Oracle.  You are probably used to using SQLServer or Informix
which have the concept of a database in a database.  We do not
share that concept.

A database is a physical collection of files -- datafiles, redo
log files, control files, initialization files.

An instance is a physical set of processes (DBWR, LGWR and so
on) and a shared memory segment (SGA).

An instance can mount and open at MOST 1 database at a time.

A database can be (in special conditions) mounted by more then 1
instance (each instance is on a separate machine).  This is
known as parallel server and is used in clustered environments.

If you are trying to mimick the "database in a database" of
SQLserver, you should just create another user.  We use schemas
in the way they used databases.  You would remove the database
you just created (your requirement to share the data from both
databases and have them in the same instance preclude the use of
2 separate databases).  You would create a schema (a user) to
hold new tables.  You would typically add a couple of
tablespaces to this database for this new user and its objects.

You can create more then one database on a physical server
machine and start up more then one instance to have more then 1
oracle database on a given server.  They can in fact even share
data transparently using a distributed query and distributed
transactions -- however -- if the data is frequently shared, the
overhead of doing tons of distributed transactions would not be
a good thing to introduce.

I believe you want a single database with many schemas in it.
November 03, 2000 Naren -- Thanks for the question regarding "prevent multiple login", version forms4.5
You Asked
Hi Tom,
I have a question regarding Developer2000 forms4.5.
I have a login form through which user can log to other system
module.My problem is that user can open multiple login form and
open multiple session from single pc.I want to restrict   them
to open only one login form at a time.I know the use of profile
to restrict the session per user. But I want to know some other
way to achive the same goal.Is it possible to restict the user
after opening and login the first login forms.So as when second
time user try to  open the login form it detect the first login
forms and exit immediatly.
Thanks
NP
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:368618111895
it shows how to set up forms on windows to prevent multiple
forms sessions from begin started.  I believe that will help.

Another option is to allow them to start up multiple login
windows but after you login to the database -- you would use the
builtin package:

dbms_application_info.set_client_info()

To set the username (your concept of a username) in the
v$session table.  Then, after logging in, you would:

select count(*) into l_cnt from v$session where client_info =
:that_username

if the l_cnt > 1 then you would "fail" right then and exit_form.
November 03, 2000 Praveen -- Thanks for the question regarding "Datafiles in v$datafile", version 8.1.5
You Asked
Hi Tom,
After I have dropped a datafile using the command
alter database datafile '/t022/oradata/GPSORI58/data1.dbf'
offline drop ;
I can still see the file in the v$datafile with the offline
status.
What is the way to drop a datafile and also it should not be
seen in the v$datafile?
The database is in NOARCHIVELOG mode.
Please advise
Thanks in advance
Praveen
and we said...
Ahhg!  offline drop is a command of last resort.  Something you
do to bring a database up when someone has inadvertantly removed
a file at the OS level.  You do this right before you DROP the
tablespace that contains that file.  there is no way to remove a
datafile from a database once attached short of dropping the
tablespace.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:515222144417
for lots more detail.
November 03, 2000 Sarah -- Thanks for the question regarding "WebDB and ASP", version 2.2
You Asked
I need to use asp (I think) to retrieve a user's IP address when
they enter my webdb form.  Is there a way to include this code?
Can I use PL/SQL?  Thank you.
and we said...
use:

  ip_address := owa_util.get_cgi_env('REMOTE_ADDR');

you can put an owa_util.print_cgi_env in there to see whats
available to you.
November 03, 2000 Arun -- Thanks for the question regarding "Copy one Row's Data to Other", version Oracle 8.1.5
You Asked
Tom,
      Thanks for the answer to my previous questions. Yout
answers really helped me a lot in performing my tasks easily and
effectively.

I am wondering if the thing i want to do now would be done in a
simple straight query.

The problem is, Say i have two tables
CATALOG
PK        Col1        Col2       Col3.......
----------------------------------------
PK1        A1          A2         A3
PK2        B1          B2         B3
PK3        C1          C2         C3
PKA        D1          D2         D3
PKB        E1          E2         E3
PKC        F1          F2         F3
........
.......
and so on.

And i have a Map table
MAPTBL
OLD Key                 New Key
--------------------------------
PK1                     PKA
PK2                     PKB
PK3                     PKC
....
....
and so on.

What i want to do is For each row in Map Table-
Read the Data corresponding to OLD Key and Copy that data to the
Data in the New Key

So my CATALOG table will then look like this

PK        Col1        Col2       Col3.......
----------------------------------------
PK1        A1          A2         A3
PK2        B1          B2         B3
PK3        C1          C2         C3
PKA        A1          A2         A3
PKB        B1          B2         B3
PKC        C1          C2         C3
........
.......
and so on.

Thanks in Advance,
Arun
and we said...
Sure, I setup the following example:

ops$tkyte@DEV816> create table catalog
  2  ( pk       varchar2(3) primary key,
  3    col1     varchar2(2)
  4  )
  5  /
Table created.

ops$tkyte@DEV816> create table map
  2  ( old_key varchar2(3),
  3    new_key varchar2(3),
  4    constraint new_key_unique unique(new_key)
  5  )
  6  /
Table created.

ops$tkyte@DEV816> select * from catalog;

PK  CO
--- --
PK1 1
PK2 2
PK3 3
PKA -1
PKB -2
PKC -3

6 rows selected.

So, at the end i would like the negative rows to be positive.
To do that I can:

ops$tkyte@DEV816> update
  2   ( select a.col1 a_col1, b.col1 b_col1
  3       from catalog a, map, catalog b
  4      where a.pk = map.old_key
  5        and map.new_key = b.pk
  6   )
  7  set b_col1 = a_col1
  8  /

3 rows updated.

ops$tkyte@DEV816> select * from catalog;

PK  CO
--- --
PK1 1
PK2 2
PK3 3
PKA 1
PKB 2
PKC 3

6 rows selected.

ops$tkyte@DEV816>

Note that the PRIMARY key on catalog and the UNIQUE CONSTRAINT
on map are mandatory for this update to work.


Subject | Article | Last Updated (East coast time)
row movement in partition table with LOB column | article only | Nov 05, 2000 08:31 pm
DBMS_OUTPUT | article only | Nov 06, 2000 09:59 am
table related | article only | Nov 06, 2000 10:01 am
using pl/sql in a template | article only | Nov 06, 2000 01:57 pm
reading data from stand by database which is in recovery mode | article only | Nov 06, 2000 01:59 pm
ODBC call failed | article only | Nov 06, 2000 04:44 pm
Loading CLOB from a file without defining a DIRECTORY object | article only | Nov 06, 2000 08:26 pm
Using Oracle Thin Driver | article only | Nov 06, 2000 08:44 pm
how do I use a routine | article only | Nov 06, 2000 09:00 pm
exp directly onto tape (using tar) | article only | Nov 07, 2000 08:55 am
WebDb 2.2 Dynamic html pages parameters question | article only | Nov 07, 2000 09:29 am
Timing | article only | Nov 07, 2000 09:40 am
CASCADE DELETE AND TRIGGERS | article only | Nov 07, 2000 09:59 am
Last Row Inserted in Table and Database | article only | Nov 07, 2000 10:08 am
Data Loading through Forms | article only | Nov 07, 2000 10:39 am
app names | article only | Nov 07, 2000 11:04 am
Internal Password | article only | Nov 07, 2000 11:06 am
lockes in the database -- preventing 2 sessions from inserting the same record | article only | Nov 07, 2000 11:16 am
Partitioned Indexes and Block Checking | article only | Nov 07, 2000 11:35 am
dbms_sql.parse | article only | Nov 08, 2000 09:16 am
sort_area_size | article only | Nov 08, 2000 10:28 am
Rollback Segments -- writes & gets | article only | Nov 08, 2000 10:41 am
Day to day activities | article only | Nov 08, 2000 10:49 am
index | article only | Nov 08, 2000 11:01 am
Connecting Forms& Reports 6i to MS SQL Server | article only | Nov 08, 2000 11:03 am
table owner | article only | Nov 08, 2000 11:06 am
some non-urgent questions | article only | Nov 08, 2000 11:31 am
how to extract content of a blob datatype into a file without disturbing its own format. | article only | Nov 08, 2000 12:39 pm
Proc*c extract header file | article only | Nov 09, 2000 07:27 pm
row(s) 1 - 29 of 29
November 05, 2000 minnie -- Thanks for the question regarding "row movement in partition table with LOB column", version oralce 8i
You Asked
Hi, Tom
First, thank you very much for your help, I learn a lot of from
you, Thanks.

today's question is :
when i update key column in a table with LOB Columns, each
partition physically locate in different disks and LOB Column of
each partition locate in different disks too, I notice that
ROWID changed and knew those rows were moved to correspending
disks. But I'm not sure whether LOB columns and index moved to
corresponding disks too, If yes , how to check it?

Thanks from heart.

Minne

example Table
create table test
(
mediol_case_id        number(10),
series_id                 number(3),
slicetype                 number(1),
image_info        blob
)
PARTITION BY RANGE (slicetype)
    ( PARTITION slice_FLAIRAXL VALUES LESS THAN (2)
        TABLESPACE IMG_BETA_TS1  --disk u01
        LOB (image_info) store as
            (TABLESPACE IMG_BLOB_TS1 --disk u06
             Enable storage in row
                          pctversion 5
             cache),
    PARTITION slice_FLAIRCOR VALUES LESS THAN (3)
        TABLESPACE IMG_BETA_TS2 --disk u02
        LOB (image_info) store as
            (TABLESPACE IMG_BLOB_TS2 --disk u07
             Enable storage in row
                          pctversion 5
             cache));

alter table test enable row movement;
and we said...
It moves the lob. Perhaps the easiest way to see this is to
offline tablespaces and query the object and see what error we
get back. I changed your create to disable inline storage of
lobs and disable caching -- to make it so the lob must be in the
lob tablespace and won't be found in the sga.

So, my create table was:

tkyte@TKYTE816> create table test
  2  (
  3  mediol_case_id        number(10),
  4  series_id                 number(3),
  5  slicetype                 number(1),
  6  image_info   blob
  7  )
  8  PARTITION BY RANGE (slicetype)
  9      ( PARTITION slice_FLAIRAXL VALUES LESS THAN (2)
 10          TABLESPACE tools
 11          LOB (image_info) store as
 12              (TABLESPACE users
 13               disable storage in row
 14                            pctversion 5
 15               nocache),
 16      PARTITION slice_FLAIRCOR VALUES LESS THAN (3)
 17          TABLESPACE indx
 18          LOB (image_info) store as
 19              (TABLESPACE drsys
 20               disable storage in row
 21                            pctversion 5
 22               nocache));

Table created.

tkyte@TKYTE816>
tkyte@TKYTE816> alter table test enable row movement;

I put a row in there:

tkyte@TKYTE816> insert into test values ( 1, 1, 1, hextoraw(
rpad('00',2000,'00') ) );

1 row created.

tkyte@TKYTE816> commit;

Commit complete.

and queried it out:

tkyte@TKYTE816> select rowid, mediol_case_id,
dbms_lob.getlength(image_info) from test;

ROWID              MEDIOL_CASE_ID DBMS_LOB.GETLENGTH(IMAGE_INFO)
------------------ -------------- ------------------------------
AAAFNvAAFAAAAAXAAA              1                           1000

then I offlined the blob tablespace I expect the blob to be in
right now:

tkyte@TKYTE816> alter tablespace users offline;

Tablespace altered.

tkyte@TKYTE816> select rowid, mediol_case_id,
dbms_lob.getlength(image_info) from test;
select rowid, mediol_case_id, dbms_lob.getlength(image_info)
from test
                              *
ERROR at line 1:
ORA-00376: file 3 cannot be read at this time
ORA-01110: data file 3: 'C:\ORACLE\ORADATA\TKYTE816\USERS01.DBF'
ORA-06512: at "SYS.DBMS_LOB", line 506
ORA-06512: at line 1

and sure enough -- it fails.  It is in the users tablespace,
putting that back online and updating the row to move it:

tkyte@TKYTE816> alter tablespace users online;

Tablespace altered.

tkyte@TKYTE816> update test set slicetype = 2;

1 row updated.

tkyte@TKYTE816> select rowid, mediol_case_id,
dbms_lob.getlength(image_info) from test;

ROWID              MEDIOL_CASE_ID DBMS_LOB.GETLENGTH(IMAGE_INFO)
------------------ -------------- ------------------------------
AAAFNwAAGAAAAADAAA              3                           1000

We can see by the rowid changing that the row moved.  In fact,
we now alter the tablespace we expect the row to be in
offline:

tkyte@TKYTE816> alter tablespace drsys offline;

Tablespace altered.

tkyte@TKYTE816> select rowid, mediol_case_id,
dbms_lob.getlength(image_info) from test;
select rowid, mediol_case_id, dbms_lob.getlength(image_info)
from test
                              *
ERROR at line 1:
ORA-00376: file 7 cannot be read at this time
ORA-01110: data file 7: 'C:\ORACLE\ORADATA\TKYTE816\DR01.DBF'
ORA-06512: at "SYS.DBMS_LOB", line 506
ORA-06512: at line 1

and sure enough, this tablespace is the one with the blob
November 06, 2000 Richard -- Thanks for the question regarding "DBMS_OUTPUT", version 8.1.6
You Asked
The following is a message I posted on Oracle Metalink's PL/SQL Forum for which
they are seemingly unwilling to put effort into finding out a reason why this is
occurring.  If you have any insight into why this may be occurring it would very
helpful.

**********

Oracle8i Enterprise Edition Release 8.1.6.0.0 With the Partitioning Option
JServer Release 8.1.6.0.0
NLS_CHARACTERSET = US7ASCII
(Operating System: SunOS 5.7)

SQL*Plus Release 8.1.6.0.0
(Operating System: WindowsNT Workstation 4.0 SP6)

I had been trying to find any way to bypass the 1,000,000 output character limit
imposed when using DBMS_OUTPUT and in doing so I stumbled across a rather
interesting phenomenon. No matter what the length of the data I can not reach
the 1,000,000 character output limit, it fails long before ever reaching that
total. For particular ranges of output lengths the number of lines capable of
being written by DBMS_OUTPUT.PUT_LINE seems to be fixed with the amount of
characters written dependent on the length of the data being written times the
fixed number of lines capable for the range. My data is as follows:

Output Length Lines
------------- -----
42 - 46       20000
47 - 52       18000
53 - 59       16000
60 - 68       14000
69 - 80       12000
81 - 96       10000
97 - 122       8000
123 - 164      6000
165 - 248      4000

I have read that DBMS_OUTPUT uses the SGA for storing output but if such a
dependency exists since these numbers are reproducible irregardless of time of
day, meaning the amount of activity occurring within the database, and that the
amount of SGA memory used remains constant, with most of the SGA free, as well
as the fact that the high end output characters for the ranges continues to
increase up to 992,000 (for 248 characters), it does not hold that the SGA is
the limiting factor. It appears that there is some rather interesting coding
related to the DBMS_OUTPUT package and/or SQL*Plus that is causing this issue.
Below is the script I used with the variable v_const being modified for various
output lengths. The default linesize is 80 in SQL*Plus but since DBMS_OUTPUT is
not affected by this as such, as it is possible with this script to write output
longer that the linesize without truncation or error, that similarly seems to
have no affect on this issue. The script has the DBMS_OUTPUT.DISABLE in order to
reset the DBMS_OUTPUT package to allow the number of characters to be printed
thereafter. If you comment out the DBMS_OUTPUT.DISABLE and DBMS_OUTPUT.ENABLE
all the output gets generated up to the maximum number of lines for the range.

----------

set serveroutput on size 1000000 format wrapped;

declare
  v_const varchar2( 256 );
  v_temp varchar2( 256 );
  v_tot number;

  procedure writer( x in varchar2, z in out number ) is
  begin
    dbms_output.put_line( x );
    z := z + length( x );
  exception
    when others then
      null;
  end;
begin
  v_const :=
'12345678901234567890123456789012345678901234567890123456789012345678901234567890
1';
  v_tot := 0;

  for i in 1..25000 loop
    writer( v_const, v_tot );
  end loop;

  dbms_output.disable;
  dbms_output.enable( 1000000 );
  dbms_output.put_line( to_char( v_tot ) );
end;
/

Any enlightenment on this matter would be most appreciative. I realize that
UTL_FILE, short of the line length limit, allows for unlimited output, I still
would like to find out why DBMS_OUTPUT does not reach the posted maximum length
of 1,000,000 output characters.
and we said...
It is reaching that maximum HOWEVER they count not only the bytes you put in
there but the bytes they put in there.

Each of your lines is actually encoded into a bigger buffer.  The maximum total
number of lines in this bigger buffer is set based upon your "set serveroutput
on size xxxxxx" setting.  Their buffer will be:

  idxlimit := trunc((buf_size+499) / 500);

They tend to not "wrap" YOUR lines in this bigger buffer.

What you are seeing is that when you use a certain size line, you get X
lines/internal buffer.  Going up by 1 byte (from 46 to 47 for example) causes
them to get 1 less of YOUR lines per their line.

So, they are storing the data like this:

their_buffer(1) = ' NNNyour data here NNNyour data here...';
their_buffer(2) = ' NNNyour data here NNNyour data here...';

So, they add 4 bytes to each of your lines for the length and a space.  At 46
bytes that is 50 characters - they buffer 500 bytes so they have 500/50 = 10
lines of your data on each line.  When you goto 47 bytes, you have 51 bytes
really, 500/51 = 9 of your lines per their line.  At a serveroutput of 1,000,000
-- their maximum buffer line they will keep is 2000.

So, at 46 bytes with 10 lines / line, you get 2,000 * 10 = 20000.
    at 47 bytes with  9 lines / line, you get 2,000 *  9 = 18000.

and so on.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:146412348066
for some possible solutions.
November 06, 2000 amanullah -- Thanks for the question regarding "table related", version 7.3
You Asked
why can't we delete colum/columns from a table? what is a theory

behind it?
and we said...
It is simply a feature that is not implemented until Oracle8i
release 8.1.

It just wasn't implemented prior to that.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:842827107711
for how to "drop" a column before that.
November 06, 2000 Sarah -- Thanks for the question regarding "using pl/sql in a template", version 2.2
You Asked
I have a template that has a link on it.  When the user enters
this page, I want the template to have code that will check to
see what the user's ip address is.  Once it finds this
information out, I want it to go to 2 different pages, depending
on what the ip address is.  When creating an unstructured
template in WebDB, I've only found one place to enter your code,
which is a block of HTML.  Will I be able to incorporate my
pl/sql into this?  What tags do I use when inserting in my html?
Thank you.
and we said...
What I would do is this -- Have the LINK goto a constant
location (a plsql routine).  This routine will inspect the users
IP address and either

o run the correct routine for them

o return a owa_util.redirect_url() to the correct page

o use a Meta-Refresh to redirect them

The template is just a template -- it does not get executed.  It
is just HTML.
November 06, 2000 gurupal -- Thanks for the question regarding "reading data from stand by database which is in recovery mode", version 8.1.5
You Asked
I want to allow users to read from the standby database while
the standby database is in constant recovery state.
and we said...
Cannot be done.  In order to read the standby database, you must
open it in read only mode.  during this time, it is a frozen
point in time picture of the other site (it is not in recovery
mode any more).  When you close it, you would start it back up
in recovery mode again.

A standby database is either:

o not doing anything (shutdown)
o open in READ ONLY mode
o doing recovery

The three options are mutually exclusive.
November 06, 2000 Arun -- Thanks for the question regarding "ODBC call failed", version Database v 8.0.5.2.1
You Asked
Hi Tom,
Can you please help me out in this .
I executing a query from MSACCESS database using ORACLE
database tables(Linked tables).
When I try to execute this query I am getting an error
ODBC call failed. The detailed description of the error is given
below. The log file is showing like this ?.

This is the output generated by the tracew file.

Can you please help me how to handle this ?

Thanks in advance.
Arun

CQOasis         139:119    EXIT  SQLSetStmtOption  with return
code 0 (SQL_SUCCESS)
        HSTMT               0x092e2230
        UWORD                        3 <SQL_MAX_LENGTH>
        UDWORD              2147483646

CQOasis         139:119    ENTER SQLExecDirect
        HSTMT               0x092e2230
        UCHAR *             0x00217a54 [      -3] "SELECT
SLS_ORD_VER_HDR.ORDER_ID S_ORDER_ID,ORD_DATES.JOB_CD
S_JOB_CD,ORD_DATES.JEOPARDY_CD
S_JEOPARDY_CD,ORD_DATES1.COMPLETED_DT
S_COMPLETED_DT1,ORD_DATES2.COMPLETED_DT
S_COMPLETED_DT2,ENGG.ORDER_ID E_ORDER_ID,ENGG.JOB_CD
E_JOB_CD,ENGG.JEOPARDY_CD E_JEOPARDY_CD,ENGG.COMPLETED_DT
E_COMPLETED_DT FROM SLS_ORD_VER_HDR SLS_ORD_VER_HDR,ORD_DATES
ORD_DATES,ORD_DATES ORD_DATES1,ORD_DATES ORD_DATES2,(SELECT
E_ORD_VER_HDR.ORDER_ID ORDER_ID,E_ORD_DATES.JOB_CD
JOB_CD,E_ORD_DATES.JEOPARDY_CD
JEOPARDY_CD,E_ORD_DATES.CURRENT_ACTIVE_IND
CURRENT_ACTIVE_IND,E_ORD_DATES1.COMPLETED_DT
COMPLETED_DT,E_ORD_DATES1.LAST_CMPLT_JOBSTEP_IND
LAST_CMPLT_JOBSTEP_IND,E_ORDER_HEADER.ORDER_STATUS_CD
ORDER_STATUS_CD,E_ORDER_HEADER.RELATED_ORDER_ID RELATED_ORDER_ID
FROM ENG_ORD_VER_HDR E_ORD_VER_HDR,ORD_DATES
E_ORD_DATES,ORD_DATES E_ORD_DATES1,ORDER_HEADER E_ORDER_HEADER
WHERE E_ORD_VER_HDR.ORDER_ID = E_ORD_DATES.ORDER_ID AND
E_ORD_DATES.ORDER_ID = E_ORD_DATES1.ORDER_ID AND
E_ORD_DATES1.ORDER_ID =E_ORDER_HEADER.ORDER_ID AND
E_ORD_DATES.CURRENT_ACTIVE_IND = 'T' AND
E_ORD_DATES1.LAST_CMPLT_JOBSTEP_IND = 'T' AND
E_ORDER_HEADER.ORDER_STATUS_CD= 'OPN' )ENGG WHERE
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES.ORDER_ID AND
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES1.ORDER_ID AND
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES2.ORDER_ID AND
ORD_DATES.CURRENT_ACTIVE_IND = 'T' AND
ORD_DATES1.LAST_CMPLT_JOBSTEP_IND = 'T' AND ORD_DATES2.JOB_CD =
'ODDE' AND ENGG.RELATED_ORDER_ID(+)=SLS_ORD_VER_HDR.ORDER_ID AND
ORD_DATES.ORDER_ID
IN(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,11111111,11111111,17570338,22498247,22507690,22507691,225
16403,22516404,22522100,22522101,22531459,22548683,22557250,22611
556,23026986,23098573,23098859,23146741,23150991,23200712,2324512
5,23245142,23247122,23300848,23300849,23304474,23304498,23305140,
23305141,23308221,23319838,23323243,23396917,23397363,23398459,23
401073,23413111,23413618,23413942,23419107,23420839,23422162,2342
3591,23431239,23431249,23492412,2349..."
CQOasis        SDWORD
                 -3

CQOasis         139:119    EXIT  SQLExecDirect  with return code
-1 (SQL_ERROR)
        HSTMT               0x092e2230
        UCHAR *             0x00217a54 [      -3] "SELECT
SLS_ORD_VER_HDR.ORDER_ID S_ORDER_ID,ORD_DATES.JOB_CD
S_JOB_CD,ORD_DATES.JEOPARDY_CD
S_JEOPARDY_CD,ORD_DATES1.COMPLETED_DT
S_COMPLETED_DT1,ORD_DATES2.COMPLETED_DT
S_COMPLETED_DT2,ENGG.ORDER_ID E_ORDER_ID,ENGG.JOB_CD
E_JOB_CD,ENGG.JEOPARDY_CD E_JEOPARDY_CD,ENGG.COMPLETED_DT
E_COMPLETED_DT FROM SLS_ORD_VER_HDR SLS_ORD_VER_HDR,ORD_DATES
ORD_DATES,ORD_DATES ORD_DATES1,ORD_DATES ORD_DATES2,(SELECT
E_ORD_VER_HDR.ORDER_ID ORDER_ID,E_ORD_DATES.JOB_CD
JOB_CD,E_ORD_DATES.JEOPARDY_CD
JEOPARDY_CD,E_ORD_DATES.CURRENT_ACTIVE_IND
CURRENT_ACTIVE_IND,E_ORD_DATES1.COMPLETED_DT
COMPLETED_DT,E_ORD_DATES1.LAST_CMPLT_JOBSTEP_IND
LAST_CMPLT_JOBSTEP_IND,E_ORDER_HEADER.ORDER_STATUS_CD
ORDER_STATUS_CD,E_ORDER_HEADER.RELATED_ORDER_ID RELATED_ORDER_ID
FROM ENG_ORD_VER_HDR E_ORD_VER_HDR,ORD_DATES
E_ORD_DATES,ORD_DATES E_ORD_DATES1,ORDER_HEADER E_ORDER_HEADER
WHERE E_ORD_VER_HDR.ORDER_ID = E_ORD_DATES.ORDER_ID AND
E_ORD_DATES.ORDER_ID = E_ORD_DATES1.ORDER_ID AND
E_ORD_DATES1.ORDER_ID =E_ORDER_HEADER.ORDER_ID AND
E_ORD_DATES.CURRENT_ACTIVE_IND = 'T' AND
E_ORD_DATES1.LAST_CMPLT_JOBSTEP_IND = 'T' AND
E_ORDER_HEADER.ORDER_STATUS_CD= 'OPN' )ENGG WHERE
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES.ORDER_ID AND
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES1.ORDER_ID AND
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES2.ORDER_ID AND
ORD_DATES.CURRENT_ACTIVE_IND = 'T' AND
ORD_DATES1.LAST_CMPLT_JOBSTEP_IND = 'T' AND ORD_DATES2.JOB_CD =
'ODDE' AND ENGG.RELATED_ORDER_ID(+)=SLS_ORD_VER_HDR.ORDER_ID AND
ORD_DATES.ORDER_ID
IN(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,11111111,11111111,17570338,22498247,22507690,22507691,225
16403,22516404,22522100,22522101,22531459,22548683,22557250,22611
556,23026986,23098573,23098859,23146741,23150991,23200712,2324512
5,23245142,23247122,23300848,23300849,23304474,23304498,23305140,
23305141,23308221,23319838,23323243,23396917,23397363,23398459,23
401073,23413111,23413618,23413942,23419107,23420839,23422162,2342
3591,23431239,23431249,23492412,2349..."
CQOasis        SDWORD
                 -3

        DIAG [S1000] [Oracle][ODBC][Ora]ORA-01795: maximum
number of expressions in a list is 254
 (1795)

CQOasis         139:119    ENTER SQLErrorW
        HENV                0x092e11a0
        HDBC                0x092e1248
        HSTMT               0x092e2230
        WCHAR *             0x0012f33c (NYI)
         SDWORD *            0x0012f3ac
        WCHAR *             0x0012ef3c
        SWORD                      512
        SWORD *             0x0012f3c2

CQOasis         139:119    EXIT  SQLErrorW  with return code 0
(SQL_SUCCESS)
        HENV                0x092e11a0
        HDBC                0x092e1248
        HSTMT               0x092e2230
        WCHAR *             0x0012f33c (NYI)
         SDWORD *            0x0012f3ac (1795)
        WCHAR *             0x0012ef3c [      77]
"[Oracle][ODBC][Ora]ORA-01795: maximum "
        SWORD                      512
        SWORD *             0x0012f3c2 (77)

CQOasis         139:119    ENTER SQLErrorW
        HENV                0x092e11a0
        HDBC                0x092e1248
        HSTMT               0x092e2230
        WCHAR *             0x0012f33c (NYI)
         SDWORD *            0x0012f3ac
        WCHAR *             0x0012ef3c
        SWORD                      512
        SWORD *             0x0012f3c2

CQOasis         139:119    EXIT  SQLErrorW  with return code 100
(SQL_NO_DATA_FOUND)
        HENV                0x092e11a0
        HDBC                0x092e1248
        HSTMT               0x092e2230
        WCHAR *             0x0012f33c (NYI)
         SDWORD *            0x0012f3ac
        WCHAR *             0x0012ef3c
        SWORD                      512
        SWORD *             0x0012f3c2

CQOasis         139:119    ENTER SQLFreeStmt
        HSTMT               0x092e2230
        UWORD                        1 <SQL_DROP>

CQOasis         139:119    EXIT  SQLFreeStmt  with return code 0
(SQL_SUCCESS)
        HSTMT               0x092e2230
        UWORD                        1 <SQL_DROP>

CQOasis         139:119    ENTER SQLAllocStmt
        HDBC                0x092e1248
        HSTMT *             0x01568f28

CQOasis         139:119    EXIT  SQLAllocStmt  with return code
0 (SQL_SUCCESS)
        HDBC                0x092e1248
        HSTMT *             0x01568f28 ( 0x092e2230)

CQOasis         139:119    ENTER SQLGetStmtOption
        HSTMT               0x092e2230
        UWORD                        0
        PTR                0x0012f3d0

CQOasis         139:119    EXIT  SQLGetStmtOption  with return
code 0 (SQL_SUCCESS)
        HSTMT               0x092e2230
        UWORD                        0
        PTR                0x0012f3d0

CQOasis         139:119    ENTER SQLSetStmtOption
        HSTMT               0x092e2230
        UWORD                        0 <SQL_QUERY_TIMEOUT>
        UDWORD                    60

CQOasis         139:119    EXIT  SQLSetStmtOption  with return
code 0 (SQL_SUCCESS)
        HSTMT               0x092e2230
        UWORD                        0 <SQL_QUERY_TIMEOUT>
        UDWORD                    60

CQOasis         139:119    ENTER SQLGetStmtOption
        HSTMT               0x092e2230
        UWORD                        3
        PTR                0x0012f3d0

CQOasis         139:119    EXIT  SQLGetStmtOption  with return
code 0 (SQL_SUCCESS)
        HSTMT               0x092e2230
        UWORD                        3
        PTR                0x0012f3d0

CQOasis         139:119    ENTER SQLSetStmtOption
        HSTMT               0x092e2230
        UWORD                        3 <SQL_MAX_LENGTH>
        UDWORD              2147483646

CQOasis         139:119    EXIT  SQLSetStmtOption  with return
code 0 (SQL_SUCCESS)
        HSTMT               0x092e2230
        UWORD                        3 <SQL_MAX_LENGTH>
        UDWORD              2147483646

CQOasis         139:119    ENTER SQLExecDirect
        HSTMT               0x092e2230
        UCHAR *             0x00217a54 [      -3] "SELECT
SLS_ORD_VER_HDR.ORDER_ID S_ORDER_ID,ORD_DATES.JOB_CD
S_JOB_CD,ORD_DATES.JEOPARDY_CD
S_JEOPARDY_CD,ORD_DATES1.COMPLETED_DT
S_COMPLETED_DT1,ORD_DATES2.COMPLETED_DT
S_COMPLETED_DT2,ENGG.ORDER_ID E_ORDER_ID,ENGG.JOB_CD
E_JOB_CD,ENGG.JEOPARDY_CD E_JEOPARDY_CD,ENGG.COMPLETED_DT
E_COMPLETED_DT FROM SLS_ORD_VER_HDR SLS_ORD_VER_HDR,ORD_DATES
ORD_DATES,ORD_DATES ORD_DATES1,ORD_DATES ORD_DATES2,(SELECT
E_ORD_VER_HDR.ORDER_ID ORDER_ID,E_ORD_DATES.JOB_CD
JOB_CD,E_ORD_DATES.JEOPARDY_CD
JEOPARDY_CD,E_ORD_DATES.CURRENT_ACTIVE_IND
CURRENT_ACTIVE_IND,E_ORD_DATES1.COMPLETED_DT
COMPLETED_DT,E_ORD_DATES1.LAST_CMPLT_JOBSTEP_IND
LAST_CMPLT_JOBSTEP_IND,E_ORDER_HEADER.ORDER_STATUS_CD
ORDER_STATUS_CD,E_ORDER_HEADER.RELATED_ORDER_ID RELATED_ORDER_ID
FROM ENG_ORD_VER_HDR E_ORD_VER_HDR,ORD_DATES
E_ORD_DATES,ORD_DATES E_ORD_DATES1,ORDER_HEADER E_ORDER_HEADER
WHERE E_ORD_VER_HDR.ORDER_ID = E_ORD_DATES.ORDER_ID AND
E_ORD_DATES.ORDER_ID = E_ORD_DATES1.ORDER_ID AND
E_ORD_DATES1.ORDER_ID =E_ORDER_HEADER.ORDER_ID AND
E_ORD_DATES.CURRENT_ACTIVE_IND = 'T' AND
E_ORD_DATES1.LAST_CMPLT_JOBSTEP_IND = 'T' AND
E_ORDER_HEADER.ORDER_STATUS_CD= 'OPN' )ENGG WHERE
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES.ORDER_ID AND
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES1.ORDER_ID AND
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES2.ORDER_ID AND
ORD_DATES.CURRENT_ACTIVE_IND = 'T' AND
ORD_DATES1.LAST_CMPLT_JOBSTEP_IND = 'T' AND ORD_DATES2.JOB_CD =
'ODDE' AND ENGG.RELATED_ORDER_ID(+)=SLS_ORD_VER_HDR.ORDER_ID AND
ORD_DATES.ORDER_ID
IN(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,11111111,11111111,17570338,22498247,22507690,22507691,225
16403,22516404,22522100,22522101,22531459,22548683,22557250,22611
556,23026986,23098573,23098859,23146741,23150991,23200712,2324512
5,23245142,23247122,23300848,23300849,23304474,23304498,23305140,
23305141,23308221,23319838,23323243,23396917,23397363,23398459,23
401073,23413111,23413618,23413942,23419107,23420839,23422162,2342
3591,23431239,23431249,23492412,2349..."
CQOasis        SDWORD
                 -3

CQOasis         139:119    EXIT  SQLExecDirect  with return code
-1 (SQL_ERROR)
        HSTMT               0x092e2230
        UCHAR *             0x00217a54 [      -3] "SELECT
SLS_ORD_VER_HDR.ORDER_ID S_ORDER_ID,ORD_DATES.JOB_CD
S_JOB_CD,ORD_DATES.JEOPARDY_CD
S_JEOPARDY_CD,ORD_DATES1.COMPLETED_DT
S_COMPLETED_DT1,ORD_DATES2.COMPLETED_DT
S_COMPLETED_DT2,ENGG.ORDER_ID E_ORDER_ID,ENGG.JOB_CD
E_JOB_CD,ENGG.JEOPARDY_CD E_JEOPARDY_CD,ENGG.COMPLETED_DT
E_COMPLETED_DT FROM SLS_ORD_VER_HDR SLS_ORD_VER_HDR,ORD_DATES
ORD_DATES,ORD_DATES ORD_DATES1,ORD_DATES ORD_DATES2,(SELECT
E_ORD_VER_HDR.ORDER_ID ORDER_ID,E_ORD_DATES.JOB_CD
JOB_CD,E_ORD_DATES.JEOPARDY_CD
JEOPARDY_CD,E_ORD_DATES.CURRENT_ACTIVE_IND
CURRENT_ACTIVE_IND,E_ORD_DATES1.COMPLETED_DT
COMPLETED_DT,E_ORD_DATES1.LAST_CMPLT_JOBSTEP_IND
LAST_CMPLT_JOBSTEP_IND,E_ORDER_HEADER.ORDER_STATUS_CD
ORDER_STATUS_CD,E_ORDER_HEADER.RELATED_ORDER_ID RELATED_ORDER_ID
FROM ENG_ORD_VER_HDR E_ORD_VER_HDR,ORD_DATES
E_ORD_DATES,ORD_DATES E_ORD_DATES1,ORDER_HEADER E_ORDER_HEADER
WHERE E_ORD_VER_HDR.ORDER_ID = E_ORD_DATES.ORDER_ID AND
E_ORD_DATES.ORDER_ID = E_ORD_DATES1.ORDER_ID AND
E_ORD_DATES1.ORDER_ID =E_ORDER_HEADER.ORDER_ID AND
E_ORD_DATES.CURRENT_ACTIVE_IND = 'T' AND
E_ORD_DATES1.LAST_CMPLT_JOBSTEP_IND = 'T' AND
E_ORDER_HEADER.ORDER_STATUS_CD= 'OPN' )ENGG WHERE
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES.ORDER_ID AND
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES1.ORDER_ID AND
SLS_ORD_VER_HDR.ORDER_ID = ORD_DATES2.ORDER_ID AND
ORD_DATES.CURRENT_ACTIVE_IND = 'T' AND
ORD_DATES1.LAST_CMPLT_JOBSTEP_IND = 'T' AND ORD_DATES2.JOB_CD =
'ODDE' AND ENGG.RELATED_ORDER_ID(+)=SLS_ORD_VER_HDR.ORDER_ID AND
ORD_DATES.ORDER_ID
IN(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,11111111,11111111,17570338,22498247,22507690,22507691,225
16403,22516404,22522100,22522101,22531459,22548683,22557250,22611
556,23026986,23098573,23098859,23146741,23150991,23200712,2324512
5,23245142,23247122,23300848,23300849,23304474,23304498,23305140,
23305141,23308221,23319838,23323243,23396917,23397363,23398459,23
401073,23413111,23413618,23413942,23419107,23420839,23422162,2342
3591,23431239,23431249,23492412,2349..."
CQOasis        SDWORD
                 -3

        DIAG [S1000] [Oracle][ODBC][Ora]ORA-01795: maximum
number of expressions in a list is 254
 (1795)

CQOasis         139:119    ENTER SQLErrorW
        HENV                0x092e11a0
        HDBC                0x092e1248
        HSTMT               0x092e2230
        WCHAR *             0x0012f33c (NYI)
         SDWORD *            0x0012f3ac
        WCHAR *             0x0012ef3c
        SWORD                      512
        SWORD *             0x0012f3c2

CQOasis         139:119    EXIT  SQLErrorW  with return code 0
(SQL_SUCCESS)
        HENV                0x092e11a0
        HDBC                0x092e1248
        HSTMT               0x092e2230
        WCHAR *             0x0012f33c (NYI)
         SDWORD *            0x0012f3ac (1795)
        WCHAR *             0x0012ef3c [      77]
"[Oracle][ODBC][Ora]ORA-01795: maximum "
        SWORD                      512
        SWORD *             0x0012f3c2 (77)

CQOasis         139:119    ENTER SQLErrorW
        HENV                0x092e11a0
        HDBC                0x092e1248
        HSTMT               0x092e2230
        WCHAR *             0x0012f33c (NYI)
         SDWORD *            0x0012f3ac
        WCHAR *             0x0012ef3c
        SWORD                      512
        SWORD *             0x0012f3c2

CQOasis         139:119    EXIT  SQLErrorW  with return code 100
(SQL_NO_DATA_FOUND)
        HENV                0x092e11a0
        HDBC                0x092e1248
        HSTMT               0x092e2230
        WCHAR *             0x0012f33c (NYI)
         SDWORD *            0x0012f3ac
        WCHAR *             0x0012ef3c
        SWORD                      512
        SWORD *             0x0012f3c2

CQOasis         139:119    ENTER SQLFreeStmt
        HSTMT               0x092e2230
        UWORD                        1 <SQL_DROP>

CQOasis         139:119    EXIT  SQLFreeStmt  with return code 0
(SQL_SUCCESS)
        HSTMT               0x092e2230
        UWORD                        1 <SQL_DROP>

CQOasis         139:119    ENTER SQLDisconnect
        HDBC                0x092e1248

CQOasis         139:119    EXIT  SQLDisconnect  with return code
0 (SQL_SUCCESS)
        HDBC                0x092e1248

CQOasis         139:119    ENTER SQLFreeConnect
        HDBC                0x092e1248

CQOasis         139:119    EXIT  SQLFreeConnect  with return
code 0 (SQL_SUCCESS)
        HDBC                0x092e1248

CQOasis         139:119    ENTER SQLDisconnect
        HDBC                0x092e1a38

CQOasis         139:119    EXIT  SQLDisconnect  with return code
0 (SQL_SUCCESS)
        HDBC                0x092e1a38

CQOasis         139:119    ENTER SQLFreeConnect
        HDBC                0x092e1a38

CQOasis         139:119    EXIT  SQLFreeConnect  with return
code 0 (SQL_SUCCESS)
        HDBC                0x092e1a38

CQOasis         139:119    ENTER SQLFreeEnv
        HENV                0x092e11a0

CQOasis         139:119    EXIT  SQLFreeEnv  with return code 0
(SQL_SUCCESS)
        HENV                0x092e11a0
and we said...
ORA-01795: maximum number of expressions in a list is 254

You have more then 254 (increased to 1,000 in 8.1) things in the
IN LIST.  Worse then that - you are not using bind variables!!

see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:139812348065
for a solution that gets over the 254 limit AND uses bind
variables (which are the single most important thing to use with
queries).
November 06, 2000 Lindsay -- Thanks for the question regarding "Loading CLOB from a file without defining a DIRECTORY object", version 8i
You Asked
I was wondering if you can use a qualified os path, as is done
when defining a DIRECTORY, to specify the file to load into a
CLOB.  I have read and tried your responses with regards to
loading CLOBs from a text file with a DIRECTORY.  Can it be done
without the directory object?

Also after defining a DIRECTORY object I received an
"insufficient privileges" error when the directory belonged to
someone else other than who was trying to use it.  What are the
privileges I need to grant to someone wanting to use the
DIRECTORY not owned by them?

Thanks
and we said...
If you want to use the API call "dbms_lob.loadfromfile" you need
to use a directory.  It is possible for you to use UTL_FILE to
read a text file and write it to a CLOB your self -- but even
that will need some setup.  You'll need to set the init.ora
parameter utl_file_dir first.

For the directory object, you can

GRANT READ on DIRECTORY <dirname> to <username>;

to allow access to it.
November 06, 2000 Mohan Kumar -- Thanks for the question regarding "Using Oracle Thin Driver", version 8.1.6
You Asked
Requirement: To Call an Oracle Procedure from The Enterprise
Java Bean Using Oracle Driver (to which we have to pass Array as
Parameter). We are using Web Logic App Server 5.1.

We r using Oracle Thin Driver to Call a Procdure from the
Enterprise Java Bean. But its not at all connecting to the
Database. Is there a way of Using any Oracle Driver to pass Java
Objects to the Enterprise Java Bean. We are using Oracle 8.1.6
Version. By Using Weblogic OCI driver, we are not able to pass
Arrays as parameter to the Procedure.Could U tell me any Oracle
Driver that the WebLogic Supports to Call a Procedure From EJB
that can be Used for our Requirement.
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:331217279811
it demonstrates how you can use a nested table type or varray to
pass an array to a stored procedure.  You can only use nested
tables or varrays currently (not plsql tables).

The example uses the thin driver.
Review & Followup
Rating: 4
March 23, 2001
Reviewer: Eric Ma (eric.ma@home.com) from Berkeley Heights, NJ USA

Rating: 4
March 23, 2001
Reviewer: Eric Ma (eric.ma@home.com) from Berkeley Heights, NJ USA

Rating: 4
WebLogic and returning array from PL/SQL March 23, 2001
Reviewer: Eric Ma (eric.ma@home.com) from Berkeley Heights, NJ USA
In order to use WebLogic 5.1 pooled connections to call Oracle 8.1.6 PL/SQL
stored procedures and return arrays to Java, some modifications to Tom's Java
code have to be made as follows (I am using a JSP page rather than a Java
application or EJB).  If you need to know the reason why, here is the URL:
http://newsgroups.bea.com/cgi-bin/dnewsweb?cmd=article&group=weblogic.developer.interest.jdbc&item=2647
<!-- JSP code start -->
<%@ page import="java.sql.*"%>
<html>
<head>
<title>GetPLSQLArray.jsp</title>
</head>
<body>
<%
  try {
    Class.forName("weblogic.jdbc20.pool.Driver");
    Connection connection =
DriverManager.getConnection("jdbc20:weblogic:pool:oraclePool");
    CallableStatement stmt = connection.prepareCall("{? = call
getSimpleArray()}");
    stmt.registerOutParameter(1, Types.ARRAY, "SIMPLEARRAY");
    stmt.execute();
    Array simpleArray = stmt.getArray(1);
    out.println("Array element type is " + simpleArray.getBaseType() + "<br>");
    String[] values = (String[]) simpleArray.getArray();
    for ( int i = 0; i < values.length; i++ )
      out.println( "row " + i + " = '" + values[i] + "'<br>" );
    stmt.close();
    connection.close();
}
  catch (Exception e) {
    out.println("Error was: " + e);
}
%>
</body>
</html>

<!-- JSP code end -->

You can also use the WebLogic's jts driver for transactional work.

November 06, 2000 Sarah -- Thanks for the question regarding "how do I use a routine", version 2.2
You Asked
I am very new to WebDb and we don't have very many references to
use.  My main purpose is to retrieve my user's ip address to
direct to the appropriate page.  I have a template that has a
url on it.  I wanted to change the url depending on what ip
address they had. I was told it wasn't possible inside of the
template.  You suggested sending the template's url to a routine
and have that decide which page to go to.  I'm not familiar with
routines. How and where would I write one?  And how would I use
the owa_util.redirect_url() method?  My other approach was to
add text to the top of one of the forms.  If the ip address
indicated they needed to go to a different page, I would just
use the meta redirect tag in html.  I used that code in the
header of my form, but it did not work.  Thank you.
and we said...
You would have the link link to a routine that looked like:

create or replace procedure do_link
as
    l_url1 varchar2(255) default
        '
http://aria.us.oracle.com/'
||
              'wa/webdemo/owa/owa_util.print_cgi_env';

    l_url2 varchar2(255) default
        '
http://aria.us.oracle.com/';
begin
    if (owa_util.get_cgi_env('REMOTE_ADDR') like '138.2.92.%')
    then
        owa_util.redirect_url( l_url1 );
    else
        owa_util.redirect_url( l_url2 );
    end if;
end;
/

It would inspect the ip address and decide where to really go.
In the somewhat likely event you hit an issue with the MS
browser hanging on the location redirect (they do not implement
it correctly -- it may or may not happen to you), you can code:

create or replace procedure redirect( p_url in varchar2 )
as
begin
    htp.p( '<HTML><HEAD>
            <META HTTP-EQUIV="Refresh"
            CONTENT="0;URL=' || p_url || '"></HEAD><body>
            <a href="' || p_url || '">Redirecting...</a>
            </body></html>' );
end;
/

create or replace procedure do_link
as
    l_url1 varchar2(255) default
        '
http://aria.us.oracle.com/'
||
              'wa/webdemo/owa/owa_util.print_cgi_env';

    l_url2 varchar2(255) default
        '
http://aria.us.oracle.com/';
begin
    if (owa_util.get_cgi_env('REMOTE_ADDR') like '138.2.92.%')
    then
        redirect( l_url1 );
    else
        redirect( l_url2 );
    end if;
end;
/

instead
November 07, 2000 Bhavesh -- Thanks for the question regarding "exp directly onto tape (using tar)", version Oracle 8i
You Asked
Dear tom,
Wish u happy election day.
We are on Sun/Solaris and we have Oracle 8i.
I JUST do not want to come disk in the picture while I exp
my set of tables. And I want to use tar only (NO dd).

I am trying to push the o/p of exp command to a named pipe
and then read that pipe to tar. It is not going through.
Can you give me hint on how to achive this?

I was not sure if exp recognizes named pipe. So, I tried to
push o/p of exp into a pipe and then read that pipe into wc and
so on (I took help from
.../ask_tom_pkg.display?p_dispid=870027450627 for this). It was
through.

$ uname -a
SunOS TTL450 5.7 Generic_106541-04 sun4u sparc SUNW,Ultra-4
$ mknod my_tmp.pip p

$ ####  /* in the following, i'm trying to push o/p of
$ ####     a pipe to wc and it works fine  */
$ echo size of exp : > size.log
$ wc < my_tmp.pip >> size.log  &
[1]     14812
$ exp userid=scott/tiger tables=emp file=my_tmp.pip

Export: Release 8.1.5.0.0 - Production on Tue Nov 7 10:00:58
2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 -
Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production
Export done in US7ASCII character set and US7ASCII NCHAR
character set

About to export specified tables via Conventional Path ...
. . exporting table                            EMP         14
rows exported
Export terminated successfully without warnings.
$
[1] +  Done                    wc < my_tmp.pip >> size.log  &
$ cat size.log
size of exp :
      37     238    4096
$
$ ####  /* in the following, i'm trying to push o/p of a
$ ####     pipe to tar and it doesn't go throu  */
$
$ tar cvf /dev/rst20 my_tmp.pip &
[1]     26471
$ a my_tmp.pip 0 tape blocks

$ exp userid=scott/tiger tables=emp file=my_tmp.pip

Export: Release 8.1.5.0.0 - Production on Tue Nov 7 10:02:41
2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to: Oracle8i Enterprise Edition Release 8.1.5.0.0 -
Production
With the Partitioning and Java options
PL/SQL Release 8.1.5.0.0 - Production

/* And after waited for long time, I have to kill exp */
$

tia,
Bhavesh Patel
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:882228114156
for how to export to a tape.  TAR would not be appropriate
here. Export can just do this directly.
November 07, 2000 Mitar -- Thanks for the question regarding "WebDb 2.2 Dynamic html pages parameters question", version Oracle8iR2 and webdb 2.2
You Asked
mire wrote:
>
> You probably know that using <ORACLE> here goes pl/sql
code</ORACLE> tags
> you can embed pl/sql code into html page.
>
> Is there a way to pass parameters to these dynamic pages to
reference those
> parameters in pl/sql code and then take some action ?
>
> For example, I'd like to get parameters ragarding name of a
person and take
> all the products he bought. The code is like 'SELECT * from
products where
> name=parName'
> where parName is the value of the name parameter passed to
dynamic html
> page.
>
> Can this be done ?

The book Oracle WebDb Bible by Greenwald says explicitly that
there is
no way to do this.  There is a nasty hack using Javascript on
the client
as a workaround on their website
http://moxie.webdb_bible.com/owb/owb.home
(which seems to be down
today).
and we said...
I think I have a cleaner way to do this.  It involves creating a
package and an application context.  This context may be used to
parameterize any query.  The package and context I suggest would
look like this:

create or replace package oracle_tag
as
    procedure run_page( p_page_name in varchar2,
                        p_parm1     in varchar2 default null,
                        p_parm2     in varchar2 default null,
                        p_parm3     in varchar2 default null );
end;
/

create or replace context oracle_tag_ctx using oracle_tag
/

create or replace package body oracle_tag
as
    procedure run_page( p_page_name in varchar2,
                        p_parm1     in varchar2 default null,
                        p_parm2     in varchar2 default null,
                        p_parm3     in varchar2 default null )
    is
    begin
        dbms_session.set_context
        ( 'oracle_tag_ctx', 'p1', p_parm1 );
        dbms_session.set_context
        ( 'oracle_tag_ctx', 'p2', p_parm2 );
        dbms_session.set_context
        ( 'oracle_tag_ctx', 'p3', p_parm3 );
        execute immediate 'begin ' || p_page_name || '; end;';
    end;
end;
/

So, all the package does is set the parameters (upto 3 but you
can obviously add/remove some) and then run another procedure.
We will use this procedure to run all <ORACLE> tagged pages that
need parameters.  We create this once and never worry about it
again.

Now, I created an <ORACLE> tagged page with html that looks like
this:

<HTML>
<HEAD>
<TITLE>Example</TITLE>
</HEAD>
<BODY>
<H1>Example of A Dynamic Page</H1>
<ORACLE>select * from scott.emp
where ename like
upper( sys_context( 'oracle_tag_ctx', 'p1' ) )</ORACLE>
</BODY>
</HTML>

Now, instead of running that page directly -- i created a form
on top of a procedure -- the procedure being
ORACLE_TAG.RUN_PAGE.  I defaulted the p_page_name to be the name
of the form.show I just created with the oracle tag.  When I run
that, I can enter a parameter and the query uses it.
November 07, 2000 Abdullah -- Thanks for the question regarding "Timing", version 7.3.4 & 8.0.5
You Asked
Hi, Tom

I use Oracle server 7.3.4 on AIX platform and when i put timing
on from the sqlplus from the client on win98, after executing
any statement a received 'real: 990' my q is what the meaning of
real and in which unit the number is it second or what msecond?

 Thank you
and we said...
It is "real" time -- as opposed to cpu time.  It is elapsed
time.

It is in thousands of a second.  that is 0.990 seconds.
November 07, 2000 Fabio -- Thanks for the question regarding "CASCADE DELETE AND TRIGGERS", version 7.3, 8.0.5
You Asked
I have created two tables (T1, T2):
create table T1
(T1_ID number primary key,
 T1_NAME varchar2(80))
/
create table T2
(T2_ID number primary key,
 T2_NAME varchar2(80),
 T2_T1_ID number)
/
alter table T2
add constraint T2_T1_FK foreign key
(T2_T1_ID) references T1 (T1_ID) on DELETE CASCADE
/

and the following triggers on the two tables:
T1_BD_S (before delete statement on T1)
T1_AD   (after delete for each row on T1)
T1_AD_S (after delete statement on T1)
T2_BD_S (before delete statement on T2)
T2_AD   (after delete for each row on T2)
T2_AD_S (after delete statement on T2)

With Oracle 7.3, if a try to delete a row of T1, the triggers
fire as follow:
T1_BD_S
T2_BD_S
T2_AD
T2_AD_S
T1_AD
T1_AD_S

With Oracle 8.0.5, if a try to delete a row of T1:
ORA-03113: end-of-file on communication channel

but if I delete the trigger T1_AD, the triggers fire as follow:
T2_BD_S
T2_BD_S
T2_AD
T2_AD_S
T2_AD_S

Why this differences between the two versions of Oracle?

Thanks fabio.tirapelle@siag.it
and we said...
For handling 3113's in general, please see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:369618129598
I do recall there being an issue with regards to an on delete
cascade and a trigger.  Your issue reproduces in 8.0.5 and 8.1.5
but not 8.0.3.  It is fixed in 8.0.6 and 8.1.6.  In those
releases the output is:

t2_bd_s
t1_bd_s
t2_ad
t1_ad
t2_ad_s
t1_ad_s

The ordering of triggers firing has never been defined or
gauranteed in this case.  Triggers that are dependent on a
specific order of firing should be avoided at all costs.
November 07, 2000 Puneet -- Thanks for the question regarding "Last Row Inserted in Table and Database", version 8.1.5
You Asked
Hello Tom
Happy Diwali and a Gujarati New Year too.
I need to know.....
1). How to find the last inserted row in a table.
2). How to find the last inserted row in the database.
3). I wish to create a view which has all the information about
my DB, for eg. Constraints, Foreign Key Table Name, FK Field
Name, PK, Index Name etc.

I'll eagerly wait for your prompt reply.

Regards to all in your family,

Puneet
and we said...
1) you would need to have a timestamp column or a sequence
column that you maintain (or let us maintain as a default) in
order to do this.  We internally do not remember the "last" row
anywhere.

2) same as above -- you would need to do that on every table.

3) we have that in the data dictionary.  See the SERVER
REFERENCE for descriptions of the views like all_constraints,
all_indexes and so on.  Its already done.
November 07, 2000 Puneet -- Thanks for the question regarding "Data Loading through Forms", version 8.1.5
You Asked
Hello Tom,
I've a severe problem. In my project I've to insert data in some
tables after regular intervals of time which is coming to me in
flat file format. Everytime I've to use SQLLOADER for the same.
I wish to know is there a better option by which I can provide
an interface designed in Forms and then do this porting part,
supposing there's no SQLLOADER on that machine.

Thanks in advance
With warm regards
Puneet
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:322417112080
for an example routine LOAD_DATA.  It uses UTL_FILE but you
would recode it to use TEXT_IO so it can read a CLIENT file
(utl_file is for server io)
November 07, 2000 Allan -- Thanks for the question regarding "app names", version 8.1.6
You Asked
Tom,
When I create a Schema(instance) called mhp that will be the
last tier on a three tier system, accessed by multiple users,
located on a Solaris box, should I also create a Unix user
account for this schema? Should all schema's have an OS account?
 i am trying to take into account using imp and exp to put the
tables , etc in a specific tablespace. Imp does not ask where to
place the tables.
I would think that a seperate tablespace per application would
be reasonable, and would like to assure the ability to load flat
files with sqlload also to the correct tablespace. I hope this
is understandable. Thanks.
....allan
and we said...
Should all schemas have OS accounts?  In my opinion there is no
relationship between a schema in the database and an OS account.
 I would say definitely no -- all schemas do not need an OS
account.

When using IMP to import data -- it will first attemp to put the
data into a tablespace named exactly the same as it was exported
from.  So, if you export table T that was in tablespace X, when
you attempt to import that table -- imp will try to recreate it
in tablespace X.  If that create fails due to:

o tablespace X does not exist
o your user has no privileges to write into tablespace X (eg: a
quota prevents them from writing into that tablespace)

then IMP will rewrite the create table statement using the users
DEFAULT TABLESPACE.

So, if you make it so that the user cannot create objects in any
tablespace except for the one you want them to -- then imp will
put the objects in there (in their default tablespace).
Alternatively you can create the tables ahead of time exactly
where you want them and imp will use them to load into (use
IGNORE=Y on the import command line).

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:47812348053
for how to make it so that imp will import into your choosen
tablespace (also shows how to move any objects that might get
created in the wrong place by accident).
November 07, 2000 Murtaza -- Thanks for the question regarding "Internal Password", version 7.3.4.0.0
You Asked
Hi Tom,

We have oracle 7.3.4 running on Sco openserver 5.0.5. whenever
we load svrmgrl, we can connect as internal and it will not ask
for password. we want that it should ask for a password when we
connect as internal.

Thanks and Regards

Murtaza
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:221413645021
....
November 07, 2000 shmuel -- Thanks for the question regarding "lockes in the database -- preventing 2 sessions from inserting the same record", version 8.0.6
You Asked
Hi,
We have two jobs that try to insert into one table at the same
time but every job perform commit only at the end.
In case of lock(one job insert record that already exist) we
wont to continue and skip that record.
Can we do it ?
and we said...
See the answer to
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:340617419132
for how to create a trigger that will make it so that 2 people
inserting the same primary key won't block eachother (one of the
sessions will get an error they can catch and handle)
November 07, 2000 Andre -- Thanks for the question regarding "Partitioned Indexes and Block Checking", version 8.1.6
You Asked
Hi Tom !

Some questions:

1) What are the advantages and disadvantages of prefixed and
non-prefixed indexes ?

2) Block checked using DB_BLOCK_CHECKING include blocks found in
memory or only I/O blocks ? It seems to me good old
DB_BLOCK_CHECKSUM only worked on I/O blocks. Am I right ?

3) Does DBMS_REPAIR.CHECK_OBJECT operate the same way as
DB_BLOCK_CHECKING ?

Thanks !
and we said...
if after reading:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c09parti.htm#430195
you have further questions -- feel free to followup.  The server
concepts (an under-read document in my experience) covers this
topic in some detail.

the db_block_checking checks blocks that are changed (modified).
 They are not checked when accessed for read, only when they are
modified.

dbms_repair.check_object reads and checks blocks.
db_block_checking verifies blocks upon modification.  The two
operate in different fashions and modes.  They are not the same.
 dbms_repair.check_object is a little more aggresive -- it reads
all blocks and checks them -- very much like analyze table
validate structure does.
November 08, 2000 vishal -- Thanks for the question regarding "dbms_sql.parse", version 8.0.5
You Asked
I have a very long statment to be parsed. The statement is doing
a insert on a table by selecting about 120 columns from a whole
bunch of other tables. The table_name needs to be passed
dynamically. I need an example of how to provide the correct
syntax when a long statement needs to be parsed.

Thanks,

Vishal
and we said...
Statements of upto 32k can be parsed by using the "simple"
dbms_sql.parse that takes a string.

if the statement is larger then 32k, you would use the
alternative form of PARSE:

  procedure parse(c in integer, statement in varchar2s,
                  lb in integer, ub in integer,
                  lfflg in boolean, language_flag in integer);

Parse the given statement in the given cursor.  The statement is
not in one piece but resides in little pieces in the PL/SQL
table "statement". Conceptually what happens is that the SQL
string is put together as follows:

String := statement(lb) || statement(lb + 1) || ... ||
statement(ub);

Then a regular parse follows. If "lfflg" is TRUE then a newline
is inserted after each piece. For further information and for
documentation on the rest of the arguments see the regular parse
procedure.
November 08, 2000 wallacel -- Thanks for the question regarding "sort_area_size", version 8.1.6
You Asked
Tom:

I read a book named oracle performance tuning tips and
techniques
wirtted by  RICHARD J. NIEMIEC , at page 5 , it says that
sort_area_size is a per-user value. my question is if i use
scott/tiger login to a system twice, did system consider it as
one user or two user so give each scott sort_area_size? or give
them both only one sort_area_size?

Regards,
and we said...
It is more accurate to say that sort_area_size is allocated on a
PER SESSION basis.  If you have 1,000 sessions all using the
same credentials -- there are potentially 1,000 sort area sizes.
 The same would be true if they all used their own
username/passwords.

It should be noted that the sort_area_size is dynamically
allocated on an as needed basis in chunks.  It is a maxmium
size, not a minimum and will be shrunk back down to
sort_area_retained_size when the operation that requested it
completes.
Review & Followup
Rating: 2
June 08, 2001
Reviewer: A reader

November 08, 2000 Ruben -- Thanks for the question regarding "Rollback Segments -- writes & gets", version 8.0.5
You Asked
Hi tom :

I'am creating a rollback segments as follows :

SQLPlusdba> create tablespace rbs_bulk_load_ts datafile
  2  '/u01/oradata/sipweb/rbs_bulk_load_ts.dbf' size 1M reuse
autoextend on;

SQLPlusdba> create rollback segment rbs_bulk_load tablespace
rbs_bulk_load_ts
  2  storage(initial 500K next 500K minextents 2 maxextents
150);

I query the next information through :

select n.name "Name", s.extents "Extents", s.rssize "Size",
s.writes "Writes",
from v$rollname n , v$rollstat s
where n.usn = s.usn

and I get :

Name               Extents       Size     Writes       Gets
OptSize    Shrinks    Extends
--------------- ---------- ---------- ---------- ----------
---------- ---------- ----------
SYSTEM                   6     364544     176730        934
               0          0
RBS_BULK_LOAD            2    1040384      76780        457
               0          0

If I had not make any transactions on that rollback segment, why
I get 76780 writes and 457 gets from rbs_bulk_load ?

Thanks in advance

Ruben Badilla
Oracle DBA
and we said...
Well, there is something missing from the above -- the rollback
segment rbs_bulk_load  must be brought online before it'll show
up in your query.

I'll have to assume this is a multi-user system.  In such a
case, all this mean is that in the time between the act of
bringing the rollback segment ONLINE and running your query --
someone used that rollback segment.  There is nothing preventing
others from using this segment once online.

When I do this in isolation:

system@ORA806.WORLD> create rollback segment test tablespace
users
  2  storage(initial 500K next 500K minextents 2 maxextents
150);

Rollback segment created.

system@ORA806.WORLD>
system@ORA806.WORLD> select n.name "Name", s.extents "Extents",
s.rssize "Size",
  2  s.writes "Writes", s.gets "Gets"
  3  from v$rollname n , v$rollstat s
  4  where n.usn = s.usn
  5  /

Name          Extents       Size     Writes       Gets
---------- ---------- ---------- ---------- ----------
SYSTEM             10     811008       5216        559
RBS_01             83    3391488      16938        545
RBS_02             80    3268608      22858        567
RBS_03             25    1015808      10204        550
RBS_04             28    1138688      13326       2064

system@ORA806.WORLD> alter rollback segment test online
  2  /

Rollback segment altered.

system@ORA806.WORLD>
system@ORA806.WORLD> select n.name "Name", s.extents "Extents",
s.rssize "Size",
  2  s.writes "Writes", s.gets "Gets"
  3  from v$rollname n , v$rollstat s
  4  where n.usn = s.usn
  5  /

Name          Extents       Size     Writes       Gets
---------- ---------- ---------- ---------- ----------
SYSTEM             10     811008       5644        565
RBS_01             83    3391488      16938        547
RBS_02             80    3268608      22858        569
RBS_03             25    1015808      10204        552
RBS_04             28    1138688      13326       2066
TEST                2    1056768          0         11

6 rows selected.

system@ORA806.WORLD> alter rollback segment test offline
  2  /

Rollback segment altered.

system@ORA806.WORLD> drop rollback segment test
  2  /

Rollback segment dropped.

I get no writes. If I do this on an active system -- I will.
The gets will be due to the online'ing of the rollback segment.
November 08, 2000 -- Thanks for the question regarding "Day to day activities", version 8.1.6
You Asked
Tom

As a newbie, Would like to know what all tables we need to check
daily in a regular basis.

Can I just go only for hotbackup files and built a new db, if it
is in archivelog mode.  Is it enough if i take ctl file, redo,
datafiles.  Tablespce i will mark it for backup and copy the
datafile but can i copy control file and redo log files , rbs
when the db is up.

What will be the impact of this.
and we said...
I would recommend reading the backup and recovery guide from
cover to cover to understand this better.

For starters -- in archivelog mode -- you NEVER want to
backup your online redo log files!  That is a fatal mistake and
if you ever restored them and used them would break the recovery
process.

You also do not copy your control files.  You back them up using
the alter database command (preferably to trace).

Backup and recovery isn't something you want to learn when you
need it to work -- you might consider using RMAN to help you
automate this process and practice restoring and recovering from
various errors (eg: good errors to mimick are:

o loss of a single datafile
o loss of all online control files
o loss of all online redo logs
o mixtures of the above
o loss of everything

and so on.
November 08, 2000 wallacel -- Thanks for the question regarding "index", version 8.1.6
You Asked
Tom:

indexed columns that have rows containing a null value
will not have an entry in the index.

my question is
when only part of indexed column is null,does that have an
entry in the index?

for example.
create table test ( a int,b int);
create table test_a_b on test(a,b);
insert into test values(1,2);             ----record 1
insert into test values(1,null);          ----record 2
insert into test values(null,2);          ----record 3
insert into test values(null,null);       ----record 4

so only record 4 have no entry at index, am i right?
and we said...
Only totally NULL records are not indexed.. If any component of
the index is not null for a given row -- there is an index entry
made.

This can be seen this way:

ops$tkyte@ORA8I.WORLD> create table test ( a int,b int);

Table created.

ops$tkyte@ORA8I.WORLD> create index test_a_b on test(a,b);

Index created.

ops$tkyte@ORA8I.WORLD> insert into test values(1,2);

1 row created.

ops$tkyte@ORA8I.WORLD> insert into test values(1,null);

1 row created.

ops$tkyte@ORA8I.WORLD> insert into test values(null,2);

1 row created.

ops$tkyte@ORA8I.WORLD> insert into test values(null,null);

1 row created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> analyze index test_a_b validate
structure;

Index analyzed.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> exec print_table( 'select * from
index_stats' );
HEIGHT                        : 1
BLOCKS                        : 64
NAME                          : TEST_A_B
PARTITION_NAME                :
LF_ROWS                       : 3   <<<======
LF_BLKS                       : 1
LF_ROWS_LEN                   : 47
LF_BLK_LEN                    : 7996
BR_ROWS                       : 0
BR_BLKS                       : 0
BR_ROWS_LEN                   : 0
BR_BLK_LEN                    : 0
DEL_LF_ROWS                   : 0
DEL_LF_ROWS_LEN               : 0
DISTINCT_KEYS                 : 3
MOST_REPEATED_KEY             : 1
BTREE_SPACE                   : 7996
USED_SPACE                    : 47
PCT_USED                      : 1
ROWS_PER_KEY                  : 1
BLKS_GETS_PER_ACCESS          : 2
PRE_ROWS                      : 0
PRE_ROWS_LEN                  : 0
-----------------

PL/SQL procedure successfully completed.
November 08, 2000 Murtaza -- Thanks for the question regarding "Connecting Forms& Reports 6i to MS SQL Server", version Developer 6i
You Asked
Hi

Can i use Oracle Developer 6i with MS SQL Server. I mean, i use
developer 6 tools and my tables/data is in SQL Server? If yes,
how do i connect to the SQL Server from forms

Thanking you in advance

Regards

Murtaza
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:218213305850
...
November 08, 2000 Chee -- Thanks for the question regarding "table owner", version 8.1.6.0.0
You Asked
Hi Tom,

I have created few tables and have granted them to other users.
The problem is when the users log in with their user_id, they
can only select from the tables with owner.tablename, eg.

   select * from rrs.products;

How do get rid the owner, I want something like:

   select * from products;

Many thanks in advanced.

chee
and we said...
You can:

o create public synonyms for these objects.  In that fashion,
select * from products would work for all users who have select
on rrs.products.

o create private synonyms.  for each user that wants this
shorthand method, they would "create synonym products for
rrs.products" when logged in in their schema.

o use
  alter session set current_schema = rrs;

  when you log in as the other people.  Now, RRS. will be used
instead of username. to find objects.
November 08, 2000 Hakan -- Thanks for the question regarding "some non-urgent questions", version 8.1.5
You Asked
hi tom,

1) we are getting quota exceed on tablespace error, but we have
no quota on this user and
on this tablespace,
the user has connect and resource priviliges and default profile
is there an implicit limit on tablespaces even the user has no
quota ?
i made it solved by giving the user, unlimited tablespace system
privilige.
is this a bug or am i missing something ?

2) is it possible and reliable to set log_archive_dest and limit
the tape by
set log_archive_dest = /dev/rmt0:100M, i haven't heard this
until my dba buddy told me.

3) as all know, we can select the plan table to get the
execution plan for a specific statement_id by

select decode(id,0,'',
lpad(' ', 2*(level -1))||level||'.'||position)||' '||
  operation||' '||options||' '||object_name||' '||
  object_type||' '||
  decode(id,0,'Cost = '||cost) Query_plan
from plan_table
connect by prior id = parent_id
and statement_id = 'OPERA'
start with id = 0 and statement_id = 'OPERA'

how do i change this query to get the same output for all
statement ids in the plan table,
not the just a specific one.
much more clearly, what i really need is something like that,

STATEMENT_ID QUERY_PLAN
------------ ----------
OPERA        SELECT STATEMENT    Cost = 5
OPERA         2.1 TABLE ACCESS FULL SY_MENU1
YYY          SELECT STATEMENT    Cost = 8
YYY           2.1 TABLE ACCESS FULL SY_MENU2
ZZZ          SELECT STATEMENT    Cost = 89
ZZZ           2.1 TABLE ACCESS FULL SY_MENU3

thank you very much, tom.
btw, my last question about oracle error messages returning
ora-1422 was because of an database error trigger, and support
told that it is buggy on 8.1.5 (if you like to glance it, here
is the TAR Number  1265099.999 )

have a good day.
hakan.
and we said...
1) it depends on how you create the user.  By default, you have
no quota on anything (meaning you cannot create anything) and
would have to be granted that on a tablespace/tablespace basis.
Some roles like resource come with unlimited tablespace but if
you create someone like this:

system@ORACLE8I> create user demo identified by demo;
User created.

system@ORACLE8I> grant create session, create table to demo;
Grant succeeded.

system@ORACLE8I> connect demo/demo

demo@ORACLE8I> create table t ( x int ) tablespace users;
create table t ( x int ) tablespace users
*
ERROR at line 1:
ORA-01950: no privileges on tablespace 'USERS'

demo@ORACLE8I> connect system/manager
Connected.

system@ORACLE8I> alter user demo quota unlimited on users;
User altered.

system@ORACLE8I> connect demo/demo
Connected.

demo@ORACLE8I> create table t ( x int ) tablespace users;

Table created.

demo@ORACLE8I>

they cannot create anything really until they've been assigned a
quota on a tablespace.  This is normal.

2) yes you could in older releases but you really should not.
there used to be a process ARCHMON (archive monitor) that no
longer exists that was part of this equation.  That log arch
dest would tell arch to write 100m and then stop -- arch would
tell archmon to write a message on the console so you would know
to switch tapes.  This is no long part of 8.0 and up.

3) change:
select decode(id,0,'',
lpad(' ', 2*(level -1))||level||'.'||position)||' '||
  operation||' '||options||' '||object_name||' '||
  object_type||' '||
  decode(id,0,'Cost = '||cost) Query_plan
from plan_table
connect by prior id = parent_id
and statement_id = 'OPERA'
start with id = 0 and statement_id = 'OPERA'

into:

select decode(id,0,'',
lpad(' ', 2*(level -1))||level||'.'||position)||' '||
  operation||' '||options||' '||object_name||' '||
  object_type||' '||
  decode(id,0,'Cost = '||cost) Query_plan
from plan_table
connect by prior id = parent_id
and prior statement_id = statement_id
start with id = 0
/

should do it.  You just want to start with EVERYTHING that is
id=0 and connect by the current parent_id,statement_id =
prior(id,statement_id)

(i could not find that tar number in my system)
November 08, 2000 Sudip -- Thanks for the question regarding "how to extract content of a blob datatype into a file without disturbing its own format. ", version 8.1.5
You Asked
Hi TOM,

How'R U??

See I am facing aproblem to extract the content of a .BMP or
.DOC file which stored into a BLOB datatype

Look how it'WAZ created ..

CREATE table files_org(file_id NUMBER, content BLOB);

CREATE or REPLACE Procedure load_a_file( p_file_id      IN
NUMBER,
                                         p_dir          IN
VARCHAR2,
                                         p_file         IN
VARCHAR2 )
      AS
          l_blob  blob;
          l_bfile bfile;
      begin
          INSERT INTO files_org VALUES ( p_file_id, empty_blob()
)
          returning content into l_blob;
          l_bfile := bfilename( p_dir, p_file );
          dbms_lob.fileopen( l_bfile );
          dbms_lob.loadfromfile( l_blob,
l_bfile,dbms_lob.getlength( l_bfile ) );
          dbms_lob.fileclose( l_bfile );
      end;

data was created by :

SQL>   exec load_a_file(1,'FILE_DIR','x1.doc');

the directory 'FILE_DIR' is created previously.

now what do I want is to extract content from files_org where
file_id = 1 into a file x2.doc ( which will keep it the same
content in MSWORD FORMAT) or may be in x1.doc.

Is there any way to do that??

Please responce ASAP.

Good LUCK

Sudip
and we said...
You need to use a 3gl such as Java+JDBC, C+OCI or Pro*C, or
VB+ODBC to do this.  You need to read the blob out in those
procedural languages and use their facilities to create an OS
file and write the raw data to it.

An example in java can be found here:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:682224675732
....
November 09, 2000 Eli -- Thanks for the question regarding "Proc*c extract header file", version 8.0.6
You Asked
Hi
I am developing Pro*c application
I want to know if there was a way to extract (generate) table
header file (include file that map table).
For example I want to develop application that make query's on
the employee table .
I want to know if there was some oracle script or mechanism that
can generate C header file for employee.
The rezone I want such think is that we have a lot of ERD
changes in our project and I want minimal hand changes
I look for some automation way.
The rezone I use pro*c is that I want to use array processing
and in 8.0.6 I can use PL/SQL
and we said...
There is nothing for simple tables however a simple query
against user_tab_columns would be able to generate this.

For object types -- you can use OTT, a comand line tool to build
the complex structures that are needed with objects.


Subject | Article | Last Updated (East coast time)
How to send attachment with your mail program? | article only | Nov 13, 2000 01:33 pm
ORU-10027 | article only | Nov 13, 2000 02:59 pm
combine extents | article only | Nov 13, 2000 04:09 pm
online redo log size | article only | Nov 13, 2000 04:13 pm
temp tablespace | article only | Nov 13, 2000 04:15 pm
row_cache_cursors, checkpoint_process | article only | Nov 13, 2000 04:23 pm
where large_pool_size come from? | article only | Nov 13, 2000 04:27 pm
Error handling | article only | Nov 13, 2000 04:52 pm
Long Raw Data | article only | Nov 13, 2000 04:56 pm
Windows 2000 | article only | Nov 13, 2000 07:18 pm
Using host arrays in the WHERE clause of a SELECT stmt | article only | Nov 13, 2000 07:24 pm
How | article only | Nov 14, 2000 01:30 pm
create a table through forms | article only | Nov 14, 2000 03:06 pm
Size of the temp. tablespace | article only | Nov 14, 2000 03:18 pm
Get resultset as array asynchronous by using OCI | article only | Nov 14, 2000 04:03 pm
Database Migration. | article only | Nov 15, 2000 09:11 am
Who Am I -> determine the procedure/function within a package | article only | Nov 15, 2000 09:18 am
Updating DBF from Oracle forms5.0 | article only | Nov 15, 2000 09:32 am
Making dynamic Charts with OAS? | article only | Nov 15, 2000 09:57 am
Direct PL/SQL access to an Excel spreadsheet | article only | Nov 16, 2000 08:42 am
Solution of AQ and dbms_pipe | article only | Nov 16, 2000 08:52 am
HTML file remains in use after closing the browser | article only | Nov 16, 2000 08:57 am
Read_Image_File Question | article only | Nov 16, 2000 09:10 am
Request | article only | Nov 16, 2000 09:11 am
Connect String | article only | Nov 16, 2000 09:21 am
Changing Tablespaces | article only | Nov 16, 2000 09:24 am
procedure for number conversion into words | article only | Nov 16, 2000 12:24 pm
Index creation | article only | Nov 16, 2000 12:44 pm
Importing objects into Oracle 7 database exported from Oracle 8 database | article only | Nov 16, 2000 12:55 pm
Batch Insert | article only | Nov 16, 2000 01:01 pm
OrdImage java code and more | article only | Nov 16, 2000 02:53 pm
OAS with SQL Server | article only | Nov 17, 2000 10:50 am
Doubts in DBMS_OUTPUT and rollbacksegments problem | article only | Nov 17, 2000 11:00 am
Oracle Error Message | article only | Nov 17, 2000 11:06 am
copy v7 db users to v8 | article only | Nov 17, 2000 03:26 pm
resource | article only | Nov 17, 2000 03:58 pm
row(s) 1 - 36 of 36
November 13, 2000 Venku Reddy -- Thanks for the question regarding "How to send attachment with your mail program?", version 8.1.5
You Asked
Iam trying send data as attachment.I observed that it accepts
only blob variables. I want to send the file as attachment to
process the data  on the other hand. So I have to send the data
as comma or tab delimited format. Is it possible. Mail.send
program can read the files from operating system level.
and we said...
If you have the data in a text variable (varchar or whatnot),
you can use utl_raw.cast_to_raw to convert the text into a raw
type which can be written into a temporary blob.

for example:

ops$tkyte@ORA8I.WORLD> declare
  2          l_tmp blob;
  3          l_str varchar2(20000);
  4  begin
  5          dbms_lob.createtemporary( l_tmp, false );
  6
  7          l_str := rpad( '*', 20000, '*' );
  8
  9          dbms_lob.writeappend( l_tmp, length(l_str),
                              utl_raw.cast_to_raw(l_str) );
 10  end;
 11  /

PL/SQL procedure successfully completed.

UTL_RAW may not be installed on your system.  If not (there
would be a grant execute to public and a public syonym if it is
installed), simply:

o cd $ORACLE_HOME/rdbms/admin
o using SVRMGRL
o connect as INTERNAL or SYS (and only these 2 users, none
other)
o @utlraw
o @prvrawb.plb
November 13, 2000 wallacel -- Thanks for the question regarding "ORU-10027", version 8.1.6
You Asked
Tom:

where can i find information about error message:
ORU-10027

Regards,
and we said...
That one is pretty self explainatory:

ops$tkyte@ORA8I.WORLD> set serveroutput on size 2000
ops$tkyte@ORA8I.WORLD> begin
  2          for i in 1 .. 10 loop
  3             dbms_output.put_line( rpad( '1', 255, '1' ) );
  4          end loop;
  5  end;
  6  /
11111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111
begin
*
ERROR at line 1:
ORA-20000: ORU-10027: buffer overflow, limit of 2000 bytes
ORA-06512: at "SYS.DBMS_OUTPUT", line 106
ORA-06512: at "SYS.DBMS_OUTPUT", line 65
ORA-06512: at line 3

There, I set the buffer size to 2000 bytes but tried to print
out 2,550 bytes.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:1011431134399
for more details as to how this dbms_output buffer is really
handled internally.
November 13, 2000 wallacel -- Thanks for the question regarding "combine extents", version 8.1.6
You Asked
Tom

by using
select segment_name,segment_type ,extents,bytes from
dba_segments where extents>5
I found some table have a lot of extents, but as far as each
extent's size is multiple of
db_block_size*db_file_multiblock_read_count , I am OK, right?

I don't need to combine those extent together to one big
contiguous extent,right?

does periodly combine small extent together help performance?

Regards,
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:421419463648
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:228413960506
for my thoughts on this.  (short answer = many extents is good,
extents should be evenly divisible by multi-block read count,
typically a multiple of 64k)
November
      13, 2000 wallacel -- Thanks for the
      question regarding "online redo log size", version 8.1.6

      You Asked
Tom:

I don't understand why small online redo log decrease time for
recovery.if crash happen, you always need to apply all the redo
log between the last backup to current time, doesn't matter if
it is one big redo or ten small redo log.

Regards,

      and we said...
There are 2 types of crash:

o instance crashes.  Only the online redo log generated since
the last completed check point will be applied.

o media recovery from a failed disk, lost datafile.  All online
and archive redo log from the last backup will be needed.

Instance crashes (from power failures, software failures and so
on) happen frequently.  These are the crashes you can control
the time to recover of via small redo logs.  As each log switch
will initiate a checkpoint, we are checkpointing more frequently
and hence will have less data to apply when we restart.

For media recovery, you can dramatially reduce the time to
recover a file from the last backup by employing incremental
backups as well as the regular old "hot backup".  This will
remove the need to apply ALL archive -- you would restore the
datafile, apply the incremental and then apply the archives
since the incremental.

November 13, 2000 wallacel -- Thanks for the question regarding
      "temp tablespace", version 8.1.6

      You Asked
Tom:

when creating temp tablespace, what's guide line ?
is that better to create multiple temp tablespace
for different users? (say one temp tablespace per 100 user or
something like that)
or just create one for every user. or create one temp tablespace
per usable disk?

Regards,

      and we said...
Depends on your needs and your system.  Having many temp
tablespaces and each assigned to a pool of users is hard to
manage, especially if you do not know the mix of users using the
temp space (you need to manually divy them up to achieve a good
balance.  You have to know that when user1 is using temp,
user100 and user500 are as well typically so they should be
assigned different tablespaces)

Using striped files will achieve a similar spreading out.  With
tons of concurrent users each needing temp, using a round robin
assignment of users to one of a couple of temporary tablespaces
-- each of which is striped -- would work as well.

November 13, 2000 wallacel -- Thanks for the question regarding
      "row_cache_cursors, checkpoint_process", version 8.1.6

      You Asked
Tom:

I heard that
increase row_cache_cursors can decrease recursive calls, but
where is this parameter? show parameter don't show
same to checkpoint_process. is those obsolete parameter?

      and we said...
Both of these are obsolete.

Row_Cache_Cursors was obsoleted with Oracle8i.

Checkpoint process was obsoleted with Oracle8.0 -- checkpoint
process is always true now.

Review &
      Followup

      Rating:
      5
  March 22, 2001
Reviewer:
      A reader
answered my question exactly regarding obsolete parameter in 8.x

November 13, 2000 wallacel -- Thanks for the question regarding
      "where large_pool_size come from?", version 8.1.6

      You Asked
Tom:

where large_pool_size come from ? somebody says that it comes
from WITHIN shared_pool_size, somebody says it comes from
outside physical memory.

based on my understanding, shared_pool was divided by two part,
one is normal, the other one is reserved for large objects.
if the size of object is larger than shared_pool_min_allocation,
it goes to "shared_pool_reserved_size". am i right?
what happen if shared_pool_reserved_size is full and one more
object large than shared_pool_min_allocation comes in?
LRU?

Regards,

      and we said...
It comes from the SGA and is "next to" the shared pool.  If no
large pool is setup, allocations (such as those used in MTS)
will come from the shared_pool.  If a large pool is setup, it is
physically different from the shared_pool but both are in the
SGA.

With the addition of the large pool, it is not necessary to
worry about the reserved size and min allocation in the shared
pool.  Your observations are correct in their usage.  They were
an attempt to prevent fragmentation of the shared pool when used
by processes that needed small, short term chunks of memory and
large, long term chunks of memory.  Now, the small short term
chunks should all come from the shared pool while the larger
long term chunks come from the large pool.

November 13, 2000 V Siva -- Thanks for the question regarding
      "Error handling", version 8.1.6

      You Asked
Hi Tom,

I'he a qustion in pl/sql. I'm writing a code to load data from a
flat file into a large table containing 140 columns, by using
UTL FILE package. Here I'm submitting just the pseudo code, (as
the actual code is very long).

declare
a tab1%rowtype;
...

begin
  a.col1 := col1  -- extracted from flat file
  a.col2 := col2  -- extracted from flat file
....
  insert into tab1(...) values(a.col1, a.col2,...);
end;

Now the problem is as follows: Say a.col2 is a NUMBER, and data
type of col2(extracted from flat file) is CHAR. In such case,
the script fails, and gives an Oracle error, and next statements
are not executed. Now I want find all data type mismatch errors
in the flat file, so that I can create a log file with all such
errors to send back to the people,from where flat file is
recieved, to get next time a corrected file. So is there any way
I can handle this, say by exception handling, so that control
should go to next assignment statement in the code. Note that
there will be around 140 assignment statements. I know one way
is to put each assignment statement in
BEGIN
 assignment statement;
exception
END;

I want to know any better way for this.

Thanks,
Siva

      and we said...
See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:464420312302
it does exactly that.
November
      13, 2000 Joe -- Thanks for the question
      regarding "Long Raw Data", version 7.3.4.4

      You Asked
We have a software program that stores attachments in a database
table. The column where the data is stored is defined as long
raw and the RDBMS is 7.3.4.4. I need to extract all the
attachments to seperate external files in their original format
(ie. Word, Notepad, etc...). Has there been a tip on how to
accomplish this? If not, any help on how to do this would be
appreciated. Thanks ...

      and we said...
I happen to have an OCI (C code) program that does just this.
You give it a query like:

./unload user/pass@db 'select LONG_RAW, FILE_NAME ....'

and it will run that query and fetch the long file into a file
named FILE_NAME (where file_name is some column in the table or
it could be something like

select long_raw, rownum || '.dat' from t

)....

You can get the source code for this from:

http://osi.oracle.com/~tkyte/owarepl/doc/dnld.html
once you get that and unzip / untar it, you are interested in
the code in owarepl/src/unload.

It compiles on UNIX and NT.

November 13, 2000 Vladimir -- Thanks for the question regarding
      "Windows 2000", version 8i

      You Asked
Hi Tom ,
What kind of Oracle Products (Server, Designer, OAS, Forms,
Reports, Perosnal, etc), I can use on Windows 2000 Server
Professional environment

Thanks and regards

Vlado

      and we said...
All of the above.

database 8.1.6 and up.

tools (forms/reports) 6i and up.

iAS (not OAS now) for Oracle8i and up.

Designer 6i.

November 13, 2000 -- Thanks for the question regarding "Using host
      arrays in the WHERE clause of a SELECT stmt", version 8.05

      You Asked
Hi Tom,

I am using ProC* and I am trying to select data into arrays, but
also using a host array in the WHERE clause.

The documentation says that the only way to use host array in
the where clause is by including the select stmt in a subquery

/* host_array = int i[32000] */
I tried the following query, but it did not work
EXEC SQL DECLARE C CURSOR FOR
select col1 from t1
where col1 in (select col1 from t2 where col1 = :host_array );

EXEC SQL OPEN C;

for(;;)
{
EXEC SQL FETCH C INTO :host_result;
...
}

Oracle treats host_array as host_array[0], instead of
considering the 32,000 values

IS IT POSSIBLE TO USE HOST ARRAYS IN THE WHERE CLAUSE AND ARRAY
FETCH at the same time ?

Note:
I can make this work by creating the select stmt dynamically,
but the maximun number of parameters in the "IN" clause is 254,
I am trying to use 32,000 different values

Any suggestion will be appreciated
Thanks

      and we said...
You cannot bind arrays like that.  You can only use them in
subqueries in INSERTS/UPDATES/DELETES, never in the where clause
of a select.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:146012348066
for two methods of doing this, both of which use bind
variables and allow for static sql.

November 14, 2000 menaka -- Thanks for the question regarding
      "How", version 8.0,5

      You Asked
Hi Tom,

I have to create 6 tables with the same definition and same
specification and same contraints same as the existing 6 tables
with different name.How can i do that.
The main purpose is that i have to back up the existing tables
which has got lot of data storing last year and this year
information . i need to back up those table as history tables
and store last year information in the history tables and delete
last year information in the existing original tables.This is
what i need to do
Let me know how can i do that

Thanks,
Menaka

      and we said...
Well, i would definitely suggest you use PARTITIONS to do this
-- not separate tables.

I would create a table partitioned by date.  You can easily
exchange partitions with existing tables so you can create an
empty table and exchange it with a full partition.  The
partitioned table will effectively "lose" this data and the
empty table will effectively "gain" this data.  You can then do
whatever you want with this newly full table of data (archive
it- whatever).  The exchange will be infinitely faster then
moving the data via inserts and deletes.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:728425384831
As for how to create these tables with the same constraints -- I
would keep the ddl in a script file and just change the table
name.  If you do not named the constraints, the system will
generate unique names for them avoiding any collisions.  For
indexes on the table -- I would incorporate the tablename into
the index name itself.

for example:

create table &1
(  x int  primary key,
   y int  unique,
   z int  check ( z > 0 )
)
/

create index &&1._idx1 on &&1.(x,z)
/

and run that in sqlplus anytime you wanted to exchange
partitions.

November 14, 2000 ather -- Thanks for the question regarding
      "create a table through forms", version 7.00

      You Asked
i want to create a table through forms ?

      and we said...
forms_ddl( 'create table t ( x int )' );
November 14, 2000 Ravi -- Thanks for the question regarding "Size
      of the temp. tablespace", version 805

      You Asked
Tom,

I have a table of size 56G. If I would like to analyze the table
with compute statistics option, do I need to have a temp.
tablespace of size 56G.

Oracle Manual says that

"For COMPUTE STATISTICS, enough temporary space to hold and sort
the entire table plus a small overhead for each row is
required."

What is the best method of analyzing without getting involved
into the temp. segment extending problems.

Thanks
Ravi

      and we said...
Use estimate and a small sample size.  On large tables -- a
small sample is typically more then sufficient.
November 14, 2000 H -- Thanks for the question regarding "Get
      resultset as array asynchronous by using OCI", version 8i

      You Asked
Mr Tom:
    I have some problem recently what about how to get resultset as an array
from function by using OCI. (The client side develop platform is MS VC++ 6 and
the database side is Oracle 8i). In the client side, I don't know the struct and
the size of the array, (because there are too many struct in out software and I
cann't predefine all of them in the client program) How Can I get the resultset.
    Now, Suppose I can get the resultset as an array even if I don't know the
struct and the size of it. But the function is to complicated, it will build the
resultset 1 rows each second and take more than half an hour, Is there any way
to get the result asynchronous ? So that the client side needn't wait more then
an hour to get the first row.
    Could you show me the example ? Thanks a lot.

                             2000.11.14
                                             jty H

      and we said...
You would use ref cursors for this and array fetch from them.  You wouldn't want
to use an array.  Using a ref cursor you can set up a host array size and by
describing each of the columns in the ref cursor -- determine their type and
size.  then, you can fetch from this cursor at will.

Now, if the function is really making the data up (so it is not really a result
set from a query but something the procedure is making up) -- what I might do is
one of two things

o use non-blocking oci.  see

http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76975/oci02bas.htm#446515
for details.  I don't like this idea as much as:

o use AQ.  Have your process run on the other end of a queue.  You can then use
asyncronous event notification to let the client "know" when its data is ready
to be read.
November 15, 2000
      Irshad -- Thanks for the question regarding
      "Database Migration.", version 7.3.4 & 8.1

      You Asked
Hi,

I want to migrate an Oracle 7.3.4 database on Novell to (two
boxes) an Oracle 8i database on NT 4.0 and Sun Solaris 2.8 for a
client.

I would like to know the brief outline of how to go about such a
migration.

Regards.

Irshad.

      and we said...
It'll be EXP and IMP in this case.  We must dump the database to
a file and reload it on the other platforms (since we are
switching platforms -- we cannot just backup and restore as
normal).

See

http://technet.oracle.com/doc/oracle8i_816/server.816/a76957/toc.htm
specifically chapter 6.

November 15, 2000 Huberto -- Thanks for the question regarding "Who
      Am I -> determine the procedure/function within a package", version
      8.1.6

      You Asked
Hi,

I want to determine the name of a function/procedure within a
package. Via the callstack it is possible to determine the owner
and name of the package, but how can I retrieve information on
what specific function/procedure it is?

Best regards,

Huberto

      and we said...
You would have to take the line number given to you by the
who_called_me function and do something like:

select text
  from all_source
 where ( upper(text) like '%PROCEDURE%'
         or
         upper(text) like '%FUNCTION%' )
   and line < :that_line_number
   and owner = :that_owner
   and name = :that_name
 order by line desc

that is - you have to read the code to find that name.  The
function names within a package body are not maintained in the
call stack (or anywhere).

A query like the above will be an 80% solution (not a full
solution). It will fail in some cases, for example:

...
procedure real_procedure_here
is
   l_variables ...;

   procedure hidden_procedure_here
   is
   begin
      null;
   end;
begin
   call_procedure_here;
end;

procedure
  another_real_procedure_here
is
begin
  call_procedure_here;
end;
....

If call_procedure_here was to try and find the name of the
procedure in the packge that called it -- it would fail using my
query above.  In the first case, it would find the hidden, local
procedure.  In the second case, it would find "blank" since the
procedure name does not appear on the same line as the procedure
keyword itself.

If you use neither of these constructs AND you have access to
the bodies of all code -- this might work for you (but will be
pretty slow).

November 15, 2000 mubeen -- Thanks for the question regarding
      "Updating DBF from Oracle forms5.0", version 8.0.5

      You Asked
Hai Mr Tom,

Can u pl.help on the following problem.

Here in my company we had a module called inventory in
oracle8.0.5 with forms5.0. But at present Financial Accounting
system is in clipper.  There is a need to update one perticular
DBF file of FA system with data of one/two tables(..of inventory
developed in oracle).  How should I update that DBF with this
data. If possible give reply in detail please.

thanks a lot

regs
mubeen

      and we said...
Forms can access heterogenous data sources via ODBC.  See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:218213305850
for details.
November 15,
      2000 Ali -- Thanks for the question
      regarding "Making dynamic Charts with OAS?", version 4.0.8

      You Asked
We have an intranet application made by OAS 4.0.8, written in
PL/SQL and Java Code.

what we need is to find a tool  or a way to make dynamic charts,
Statistic tools, with PL/SQL code, because our data are mostly
financials data and we need too much this tool for reporting
dynamically.

can you tell us how can do this procedure within the oracle
programming (PL/SQL, Java,...).

there is some packages to do this, chart packages?

thank you in advance.

we need this solution too much!!!.

Ali Kassem.

      and we said...
I use the solution found at
http://www.ve.com/kavachart/
myself.  We have plsql generate
an applet tag with the data to be charted embedded therein.
Review &
      Followup

      Rating: 4
just what i
      needed  December 24, 2001
Reviewer:  amol
       from sweden
Is it poss to see sample code for this.
the samples that i downloaded use a .dat file ?how do you do it?
tia,
-amol

November 16, 2000 Don -- Thanks for the question regarding "Direct
      PL/SQL access to an Excel spreadsheet", version 8.1.6.2

      You Asked
We would like to run an application implemented in PL/SQL that
needs to process an input Excel spreadsheet (referring to an
Oracle database for validation of certain parts of the
spreadsheet data), and then output a revised spreadsheet that
has added information about the processing results.

I suppose one could manually run Excel on both ends to convert
to and from something like CSV format. But I was hoping for a
way to avoid those extra manual steps.

Also, we would like to avoid solutions that involve Excel VBA
programming (though that may be the only realistic option).

So, is there perchance a way for PL/SQL to directly access an
Excel spreadsheet (for reading and writing), such as via some
exotic ODBC adapter?

      and we said...
Not that I am aware of.  One possibility is to load the
spreadsheet as is into the database and have interMedia convert
it into HTML -- easily parsable by plsql.  plsql can then
generate a spreadsheet in sylk format (see

http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:owa_sylk
for how to do that).

Otherwise see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:243814703172
for some methods to load excel into the database.

Review &
      Followup

      Rating: 4
use ODBC but
      backwards  October 10, 2003
Reviewer:  Kevin
      Meade  from USA
One option is to make Oracle do an ODBC lookup to your external data.  Most
people take ODBC client apps and do lookups to the Oracle database via an ODBC
connection.  It is possible to also do the reverse.  That is, define a
datasource external to Oracle and then let Oracle treat it like a table.  I am
not refering to external tables that are now available in 9i, but rather the
older method (heterogenious this and that stuff).  It is however limited in its
application; you need to be on an Oracle server platform that has an ODBC filter
for your intended data (you likely have to buy one), and you have to do some
setup work in tnsnames/listener etc.  I did do it once and it did work with
MS-Access.  My Oracle database got data from MS-Access (as vs. MS-Access getting
data from my Oracle database).  There is lots of info about this on the web and
also in metalink (which is where I figured it all out).  It ain't a short thing
but it can work, good luck.

November 16, 2000 KK -- Thanks for the question regarding "Solution
      of AQ and dbms_pipe", version 8.1.6

      You Asked
I've to develop a distributed application which consists of
several databases.  There are some tasks(procedures) in
the local database.  The tasks will send request to the remote
sites and get the results from the remote database.

Each site may have a Pro*C program which communicate with each
other via TCP/IP socket.

How can I make good use of AQ or pipe to smooth this operation?

      and we said...
AQ and pipes are not the approach to take.  If you need to send
a request (a stored procedure call or SQL statment) to a remote
site -- you need  a database link.  that is all.

Oracle is fully distributed out of the box.  I can invoke a SQL
statement or stored procedure on a remote site as naturally as
on the local site.  The added benefit of two phase commit is
supplied as well.

See

http://technet.oracle.com/doc/oracle8i_816/server.816/a76960/toc.htm
for more information.

November 16, 2000 Bhavesh -- Thanks for the question regarding
      "HTML file remains in use after closing the browser", version 4.0

      You Asked
Hi Tom,
    Thanks for all your help in past. Recently I have started
using OAS 4.0 on NT server and have found the problem of .htm
file which calls a back end PL/SQL Toolkit procedure remains
locked even after I close the web browser. Suppose that I have
following procdeure :
------------------------------------
CREATE OR REPLACE PROCEDURE test (person IN VARCHAR2, X IN
INTEGER DEFAULT 0, Y IN INTEGER DEFAULT 0) IS
     usrfound            INTEGER := 0;
     invalid_user        EXCEPTION;
BEGIN
   select count(*) into usrfound from web_users where
web_username = person;
   if usrfound > 0 then
       HTP.P('Welcome to the World of Oracle ');
   else
       RAISE invalid_user;
   end if;
EXCEPTION
    WHEN invalid_user THEN
       HTP.P('No such User');
END;

and the following htm

<html>
<head>
<title> Test </title>
</head>
<body>
<br>
<FORM METHOD="POST" ACTION="
">http://myserver.com:4444/orix/test">
Please type the name of the user u r looking for :
<INPUT TYPE="text" NAME="person"><P>
To Submit the query press this button :
<INPUT alt=go! border=0 height=19 SRC=/oraimg/go.gif type=image

width=30><P>
</FORM>
</body>

------------------------------------

Now when I run this htm file through browser it works fine but
even after I close the browser I am not able to rename or edit
the .htm file. To rename/edit this .htm file I have to stop and
re-start the listener on the specific port (in this case 4444).
Can you tell me as to what can be the reason for this problem.
Is it something to do with installation of OAS, or we need to do
something so as to ensure that the procedure on the backend is
terminated once we close the browser ? Thanks in advance.
Best Regards,

Bhavesh

      and we said...
This is the way NT works -- the web server is caching the file
so we don't have to re-read it every time a request comes
through.  It is similar to opening a document in word -- no
other process can access that document until word gives it up.

In a production environment -- you want this behaviour as the
performance boost can be tremendous.  In a development
environment you can disable File Caching in the server.
To do this, Set the parameter FileCaching=OFF in the [Server]
section of the listener configuration file.

Review &
      Followup

      Rating: 2
Bigger problems
      than this  January 25, 2002
Reviewer:
      L.Wang  from USA
We use the same OAS for both production & development.  I
can see in the config file where File Caching is turned on.
The problem that I am having is when I modify code and
recompile it the OAS doesn't recognize my changes.  Then
I have to hunt down the systems people to reload the
cartridge(and this usually takes a very long time).
Is there any way to turn off caching at the cartridge
level?

-----Lori

November 16, 2000 Omar -- Thanks for the question regarding
      "Read_Image_File Question", version 6.0.5

      You Asked
Hi tom,
  I am developing a personnel system now , I
used  "Read_Image_file" to load employees photos to the
database, the photos' files are located in my pc, but the size
is getting larger and larger, so I am asking if is it possible
to save the photos first on UNIX remote server then access them
to load them in the database from my pc client.

thanks in advance

      and we said...
Yes, you would put the photos on the unix server and use the
BLOB type in the table and the function dbms_lob.loadfromfile to
load them.

For example, I just ran:

create table demo
( id        int primary key,
  theBlob   blob
)
/

create or replace directory my_files as
'/export/home/tkyte/public_html';

declare
    l_blob  blob;
    l_bfile bfile;
begin
    insert into demo values ( 1, empty_blob() )
    returning theBlob into l_blob;

    l_bfile := bfilename( 'MY_FILES', 'U0020460.jpg' );
    dbms_lob.fileopen( l_bfile );

    dbms_lob.loadfromfile( l_blob, l_bfile,
                           dbms_lob.getlength( l_bfile ) );

    dbms_lob.fileclose( l_bfile );
end;
/
commit;

You would turn the anonymous block into a stored procedure of
course so you could call it and parameterize the file name that
I have hard coded.  When I built a default block on the demo
table -- the picture shows right up.
November 16, 2000 Sowjanya -- Thanks for the question regarding
      "Request", version 8.1.5

      You Asked
Dear Sir,
I would like to ask about what is the difference between
Oracle 7.3 version and Oracle 8i.
I am requested to give a seminar regarding the above topic.
please send the requested answer as early as possible.
kindly do the needfull,

yours sincerely,
Sowjanya Adusumilli.

      and we said...
see

http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
it details all of the new features by release since 7.3 till
8.1.6
November 16, 2000 afaq -- Thanks for the question regarding
      "Connect String", version 8.1.6

      You Asked
Hi Tom

  I have Personal Oracle 8.1.6 & Forms 6i,loaded on the same
machine. Is it neccessary for me to create a service name to
connect to my  local database inspite both the products using
the same communication  protocol i.e Net 8 unlike Developer
Release 2.1 which uses Sql* Net  Protocol.

   Further is service name mandatory even to connect to a local
 database or can it be bypassed

   Look forward to an answer from your end at the earliest

 Thanks in Advance
 Afaq Baig

      and we said...
You need to use net8.  you need to setup the listener under
8.1.6 and configure the tnsnames.ora under forms6i

forms 6i is built on 8.0.5 code

Oracle8i, release 2 is built on 8.1.6 code.

Anytime the versions are different -- we need to use the network
to get them talking.
November 16,
      2000 afaq -- Thanks for the question
      regarding "Changing Tablespaces", version 8.0.3

      You Asked
Hi Tom,

   We have got a few of our objects in the System
tablespace,which we want  to shift to a non system tablespace,is
there any other way out other than
 the import/export utility .

    Looking forward to hear from  u soon.

 Kind Regards
 Afaq Baig

      and we said...
In 8.0.3, export/import is the only reasonable approach.  In 8i,
it is much easier.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:47812348053
for all of the details (8.0 and 8i methods)

November 16, 2000 Neeraj -- Thanks for the question regarding
      "procedure for number conversion into words", version Oracle 8i

      You Asked
Hi Tom,
can u please help  me in writing a program for accepting a
number and converting into words..like 1234 should print as One
thousand two hundred and thirty-four .
thanks.
neeraj

      and we said...
See

http://osi.oracle.com/~tkyte/Misc/SpellANumber.html
for how to do that....
November 16,
      2000 vladimir -- Thanks for the
      question regarding "Index creation", version 8.1.6

      You Asked
Hi, TOM!
Look at my problem!
SQL> create unique index id_u_ent_folder_par_name on ent_folder
(m_parent_id,m_name);
create unique index id_u_ent_folder_par_name on ent_folder
(m_parent_id,m_name)
                                                *
ERROR at line 1:
ORA-01452: cannot CREATE UNIQUE INDEX; duplicate keys found
It is OK!

SQL> create unique index id_u_ent_folder_par_name on ent_folder
(m_parent_id,upper(m_name));
create unique index id_u_ent_folder_par_name on ent_folder
(m_parent_id,upper(m_name))

             *
ERROR at line 1:
ORA-01031: insufficient privileges

What Privileges?

      and we said...
See

http://osi.oracle.com/~tkyte/article1/index.html#how
for what it takes to create a function based index.

You know -- if the first index failed -- the second one will
fail for the same reason.  folding the m_name to uppercase will
possibly increase and never decrease the number of duplicates!
November 16, 2000 Abhinav -- Thanks for the question regarding
      "Importing objects into Oracle 7 database exported from Oracle 8
      database", version 8.0.5

      You Asked
Dear tom,

I am looking after the database administration of Production
database running Oracle 8.0.5 and a development database running
Oracle 7.3.2. Now i have to ocassionally export tables from the
production database into the development database but it fails.
I referred to the docs and it says the exports from version
8.0.5 are backward compatible only till version 7.3.3

Can u suggest any workarounds.

Thanks.

abhinav

      and we said...
See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:820826902083
for more details.  In order to import into 7.3 objects from an
Oracle8.0 database -- you must use the 7.3 EXP utility against
Oracle8.  You will find in the Oracle8 rdbms/admin directory a
catexp7.sql script.  If you run that in your Oracle8 database,
the v7.3 exp tool can export from version 8.  That export can
then be used against v7.  v7.x cannot read ANY v8.x export
files.

Same goes the other way -- you can use the 7.3 import to import
into v8.  Just use SQLNET to let the v7.3 tool do the work.

You might consider the sqlplus copy command as a higher speed,
easier way to copy the data as well.  See

http://osi.oracle.com/~tkyte/Misc/MoveLongs.html
for a quick example.
November 16,
      2000 -- Thanks for the question
      regarding "Batch Insert", version 8.1.6

      You Asked
Hi Tom,

1. The situation is i have a master and a detail table where i
have to insert one record into master and many into the detail
table from EJB. To perform this should i go for an Oracle object
view defined on master-detail tables and insert into the object
view, which will inturn insert into the master and detail tables
by the INSTEAD OF TRIGGERS defined on the view, or go for batch
insert of master and detail records. Which method will be better
for this situation in terms of performance and overhead. What is
the overhead in using Oracle Object View for this situations.
2. Is it possible to use Oracle Thin Driver in BEA Weblogic
server?

Thanks for any help.

      and we said...
I myself would just use straight jdbc.  I would insert the
master record and then prepare statement to insert the details
and set the execute batch to some reasonable number:

    ((OraclePreparedStatement)ps).setExecuteBatch(50);

so that all of the details go over in one network trip when I
call:

    ((OraclePreparedStatement)ps).sendBatch ();

You could use the object types but I believe it would make your
code a little more obscure, and would not add too much value.

As for using the Oracle Thin Driver with BEA Weblogic -- yes, as
long as you setup the right classpaths and such.
November 16, 2000 eli -- Thanks for the question regarding
      "OrdImage java code and more", version 8.1.6

      You Asked
Hi
I have some question regarding LOBS

1) I am looking for java code for upload and download of picture
image using intermedia image option i found code in the TechNet
only for 8.1.7 can you refer me to same example using 8.1.6
InterMedia class's
2)What is your recommendation for using blob :
storing in the dataBase or use BFILES (I know that in media
filer the recovery process cloud take lat of times (I am talk
about lat of pictures))
3) Do oracle compress the images if I load the image to the
database.
4)We want to develop standard application that use ONLY JDBC in
order to communicate with the database (We want  that the class
cloud do blob operation in oracle and in informix databases )
with out the need to import oracle* etc ..

Tnx

      and we said...
1) See

http://technet.oracle.com/sample_code/products/intermedia/htdocs/intermedia_servlet_jsp_samples/intermedia_servlet_jsp_readme.htm
2) I would use blobs. To use bfiles you must have access to the
databases filesystem as we do not WRITE bfiles, only read them.
Therefore, if your webserver is on a different machine from the
dtabase -- bfiles would not work too handily.

3) images in general are already compressed (gif and jpg are
compression techniques) however the image capabilities do allow
us to scale images and such if you want to make them smaller in
size.

4) You'll need to use jdk1.2 in order to do that.  Given a
standard JDBC result set (java.sql.ResultSet) or callable
statement (java.sql.CallableStatement) that includes BLOB or
CLOB locators, you can access the locators by using standard
getter methods, as follows. All the standard and Oracle-specific
getter methods discussed here take either an int column index
or a String column name as input.

n Under JDK 1.2.x, you can use the standard getBlob() and
getClob() methods, which return java.sql.Blob and Clob  objects,
respectively.

n Under JDK 1.1.x, there is no standard BLOB or CLOB
functionality, but you can use the generic getObject() method,
which returns java.lang.Object, and cast the output as desired.

Review &
      Followup

      Rating: 1
Link not
      found  August 28, 2003
Reviewer:  Juan
      Carlos  from Cali, Colombia
Sorry, but the link you propossed not exist on technet. :-(

November 17, 2000 pankaj kumar -- Thanks for the question regarding
      "OAS with SQL Server", version 4.0.8.1

      You Asked
One of my group unit is on SQL Server, We want to put OAS at
different location using Oracle work group server (8i) what will
be the limitation as compared to enterprise version. Also how
SQL Server will talk to OAS.

      and we said...
Chapter 5 of

http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
explains what is in EE and what is in SE.

OAS can run java, java can use jdbc, jdbc can talk to sqlserver.

OAS can run perl.  DBIPerl has sqlserver modules.

and so on.  It is a function of what you are programming in at
the OAS level.
November 17, 2000
      V Siva -- Thanks for the question regarding
      "Doubts in DBMS_OUTPUT and rollbacksegments problem", version 7.3.2

      You Asked
Hi Tom,

I'm trying to delete the entire data from a table having 18000
rows. When I use just delete, it is used to give error Failed to
extend rolloback segment. Later rolbback tablespace is increased
by DBA. Now it is not giving me this error.But taking long time.
Each row avg.size is 2k.

Q1. What could be the reason? Even after 1 hour, nothing
happened? Then I aborted the transaction.

SQL> delete from tab1;
^C

^C

^D
^C
^C
^C
^C
^C
delete from tab1
            *
ERROR at line 1:
ORA-01013: user requested cancel of current operation

Elapsed: 01:41:39.32

-------------
Now I'm trying to delete the interms of chunks of data based
date of creation, using the following code.

DECLARE
  CURSOR cur_qproject IS
    SELECT min(created_dt) min_dt, max(created_dt) max_dt
    FROM   tab1;
  l_min_dt  DATE;
  l_max_dt  DATE;
  l_next_dt DATE;
BEGIN
  DBMS_OUTPUT.ENABLE(1000000);

  FOR l_rec in cur_tab1 LOOP
    l_min_dt := l_rec.min_dt;
    l_max_dt := l_rec.max_dt;

DBMS_OUTPUT.PUT_LINE(to_char(l_min_dt,'MM/DD/YYYY')||'-'||to_char
(l_max_dt,'MM/DD/YYYY'));
  END LOOP;
  l_next_dt := l_min_dt;
  DBMS_OUTPUT.PUT_LINE(to_char(l_next_dt,'MM/DD/YYYY'));

  WHILE (add_months(l_next_dt,1) <= l_max_dt)  LOOP
    DBMS_OUTPUT.PUT_LINE('Period:
'||to_char(l_next_dt,'DD-MON-YYYY')||' -
'||to_char(add_months(l_next_dt,1),'DD-MON-YYYY'));
    DELETE FROM tab1
    WHERE  created_dt BETWEEN l_next_dt and
add_months(l_next_dt,1);
    COMMIT;
    l_next_dt := add_months(l_next_dt,1);
  END LOOP;

  DELETE FROM tab1
  WHERE  created_dt BETWEEN l_next_dt and l_max_dt;
  COMMIT;

  DBMS_OUTPUT.DISABLE;

END;

Q2.  it is not showing the dbms_outputs. I have set the
serveroutput on, timing on before calling the above code from
SQL plus.
     Is it due to COMMIT used in between? But I opened another
session, selecting the count of rows, it is showing decrement in
count.

SQL> select count(*) from qproject;

  COUNT(*)
----------
      9105

Elapsed: 00:00:00.76
SQL> /

  COUNT(*)
----------
      8598

Elapsed: 00:00:00.79
SQL> /

  COUNT(*)
----------
      8219

Elapsed: 00:00:00.66

This code also took 4 and half hours to delete around 11000
records.

Please give an advice on how to delete such data in a reasonable
time.
Note: that the deletion from that table is part of script which
is a batch job should run every night.

Thanks,
Siva

      and we said...
Well, I'll answer backwards.

DBMS_OUTPUT output will NOT be displayed until control returns
to the client.  It is stored in the server memory and returned
to the client when it is complete.  There is no way for PLSQL to
interactively display on the console any sort of messages.  That
explains why you will not see the dbms_output output.

As for the delete.  If you are going to delete all rows, you
might consider using TRUNCATE instead.  Much faster, no
rollback/redo generated. It just zeros out the space map of the
table -- doesn't touch the actual data.  Make sure you
understand the ramifications of this command!  (eg: it will NOT
fire triggers, it will not work if there are child records and
so on)

I do not know the definition of this table but things to look
for:

o does this table have a delete trigger.
o are there lots of indexes on this table.
o is this the parent table in a foreign key relationship?
  o if so, does it have an ON DELETE CASCADE?
    o if so, is the FOREIGN KEY in the child table INDEXED???
      See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:292016138754
      for more info on that.

o have you run SQL_TRACE+TKPROF to see what is going on

Given the large amount of time here (my example below on my
laptop shows this should go much faster) I'm going to guess this
is the parent table in a foreign key relationship and the child
has an unindexed foreign key forcing us to full scan the child
table 18,000 times.  Adding the index will correct the problem.

tkyte@TKYTE816> select table_name, avg_row_len, num_rows from
user_tables where table_name = 'T';

TABLE_NAME                     AVG_ROW_LEN   NUM_ROWS
------------------------------ ----------- ----------
T                                       97      42586

tkyte@TKYTE816> set timing on
tkyte@TKYTE816> delete from t;

42586 rows deleted.

Elapsed: 00:01:61.49
tkyte@TKYTE816>

November 17, 2000 leon -- Thanks for the question regarding "Oracle
      Error Message", version Oracle 8i (1.5)

      You Asked
Hi Tom,

I got the following error message when I did
the query: select * from dba_tablespaces (I
connected to database as internal via Server
Manager).

ORA-01219 database not open: queries allowed on
fixed tables/views only.

I verified that all backgroud processes were up.
The query against v$database was working. That
means the database is open.

Source and Action from Oracle manual for the error are:

Cause: A query was issued against an object not recognized
as a fixed table or fixed view before the database has
been opened.

Action: Re-phrase the query to include only fixed objects,
or open the database.

What is the cause of the problem, how can I fix it?

Thanks,

Leon,

      and we said...
No, that means the database is started, and even mounted but it
is NOT open.

svmgrl> Alter database open;

will correct that.

SVRMGR> startup nomount
ORACLE instance started.
Total System Global Area                         43681036 bytes
Fixed Size                                          70924 bytes
Variable Size                                    39436288 bytes
Database Buffers                                  4096000 bytes
Redo Buffers                                        77824 bytes
SVRMGR> select count(*) from v$datafile;
COUNT(*)
----------
ORA-01507: database not mounted
SVRMGR> alter database mount;
Statement processed.
SVRMGR> select count(*) from v$datafile;
COUNT(*)
----------
         8
1 row selected.
SVRMGR> select count(*) from dba_datafiles;
select count(*) from dba_data_files
                     *
ORA-01219: database not open: queries allowed on fixed
tables/views only
SVRMGR> alter database open;
Statement processed.
SVRMGR> select count(*) from dba_data_files;
COUNT(*)
----------
         8
1 row selected.
SVRMGR>

November 17, 2000 Steven -- Thanks for the question regarding "copy
      v7 db users to v8", version v8

      You Asked
Tom,

I would like to know the easiest way to copy V7 users (over
1000) to V8 db.   I only think about getting all user names to
put them into sql code.   I have someone suggestion, but not
working.

Please help if you are not that busy.

Thanks a lot,

Steve

      and we said...
I've used scripts in the past.  For example, if you:

set heading off
set feedback off
spool create_users.sql

select 'create user ' || user || ' identified by ' ||
       ' values ''' || password || ''';'
  from dba_users
 where user_id < 20;

spool off

that'll get all of the create users with their password intact.

You can get their grants and such by running similar querys
against dba_tab_privs

select 'grant ' || privilege || ' on ' || owner || '.' ||
        table_name || ' to ' || grantee || decode( grantable,
'YES', ' with grant option;', ';' )
from dba_tab_privs;

and dba_sys_privs.
November 17,
      2000 wallacel -- Thanks for the
      question regarding "resource", version 8.1.6

      You Asked
Tom:

if somebody have a process do some thing like:

insert into table test values(1);

then i go to another one, and try to do :
drop table test;

I will get the error message:
Resource busy,

is that possible for me to know which user is the one
locked the table? how?

      and we said...
ops$tkyte@8.0> select username from v$session
  2  where sid in ( select sid from v$lock where id1 =
  3  ( select object_id from
  4        user_objects where object_name = 'T' ) )
  5  /

will do that for you.


Subject | Article | Last Updated (East coast time)
Oracle Architecture | article only | Nov 18, 2000 12:05 pm
SQL * Loader automation Kron Vs Oracle Job | article only | Nov 18, 2000 12:24 pm
PL/SQL release version reporting | article only | Nov 18, 2000 12:27 pm
HELP | article only | Nov 18, 2000 12:40 pm
Full table scan/Rollback Segment Backup | article only | Nov 18, 2000 12:43 pm
What host called Me? | article only | Nov 18, 2000 12:58 pm
procedures | article only | Nov 18, 2000 02:00 pm
table partitioning related | article only | Nov 18, 2000 02:03 pm
More about ORDImage Features | article only | Nov 18, 2000 02:18 pm
session. | article only | Nov 19, 2000 09:54 am
Finding nth Record | article only | Nov 19, 2000 09:59 am
Combined Foreign key | article only | Nov 19, 2000 08:28 pm
utl_smtp | article only | Nov 19, 2000 08:31 pm
temp tablespace+ cpu power | article only | Nov 19, 2000 08:38 pm
download Pro*C | article only | Nov 20, 2000 08:44 am
Tablespace point in time recovery | article only | Nov 20, 2000 09:03 am
Can I update from more than 2 tables | article only | Nov 20, 2000 09:07 am
'CREATE DIRECTORY' performs CT | article only | Nov 20, 2000 09:12 am
BLOB problem ! | article only | Nov 20, 2000 09:17 am
regarding the oracle magazine | article only | Nov 20, 2000 04:09 pm
question on "archival required" | article only | Nov 21, 2000 09:31 am
storage of tables | article only | Nov 21, 2000 10:01 am
upgrading the database | article only | Nov 21, 2000 10:16 am
Reassigning values to an indexed field | article only | Nov 21, 2000 10:23 am
Domain idx's, Oracle 8.1.7, partitioning and IOT's | article only | Nov 21, 2000 10:48 am
Size of a table | article only | Nov 21, 2000 10:56 am
retrieval programatically of database domain name for create database link command | article only | Nov 21, 2000 10:59 am
How many index scan is taking place | article only | Nov 21, 2000 01:50 pm
In a trigger, how do I ascertain the roles to which the invoker belongs? | article only | Nov 21, 2000 02:22 pm
rman | article only | Nov 21, 2000 02:25 pm
one or two query? | article only | Nov 21, 2000 03:00 pm
The Recovery Option | article only | Nov 21, 2000 03:15 pm
Procedures with Dependencies on Tables | article only | Nov 21, 2000 04:09 pm
schema name in pl/sql block | article only | Nov 21, 2000 04:14 pm
Transactions during online backup | article only | Nov 21, 2000 07:19 pm
Save Undo | article only | Nov 21, 2000 07:30 pm
Migrating data | article only | Nov 21, 2000 07:45 pm
BLOB or BFILE fileld on the Web | article only | Nov 21, 2000 07:47 pm
randomly select rows from table | article only | Nov 21, 2000 07:49 pm
Continuing "Save Undo"... | article only | Nov 22, 2000 07:07 am
To return a result Set | article only | Nov 22, 2000 07:26 am
How to show missing date between given range with count absents days | article only | Nov 22, 2000 08:43 am
\types of parameters to db procedures | article only | Nov 22, 2000 08:53 am
Oracle Stored Procedures | article only | Nov 22, 2000 10:25 am
Getting a fixed length file from a script in SQL*PLUS | article only | Nov 22, 2000 10:52 am
Updatable Views | article only | Nov 22, 2000 12:03 pm
Repointing MsAccess application from Sybase to Oracle | article only | Nov 22, 2000 12:38 pm
row(s) 1 - 47 of 47
November 18, 2000 Snehal -- Thanks for the question regarding "Oracle Architecture", version version 8i
You Asked
Explain me in detail oracle Architecture ? How datafiles and
memory structures work together
and we said...
That is the easiest question I've gotten in a while.
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/toc.htm
The server concepts manual, one of the best (and most
under-read) documents out there.

It does all of that.
November 18, 2000 Venkata -- Thanks for the question regarding "SQL * Loader automation Kron Vs Oracle Job", version Oracle8 Enterprise Edition Release 8.0.5.0.0 - Production
You Asked
We have to automate the loader script and anonymous PL/SQL
blocks which are in OS files in HP- UNIX environment.

1. My Q is keeping anonymous PL/SQL blocks in OS files run from
 KRON job
   VS
Converting anonymous PL/SQL blocks into stored PL/SQL Package
and calls the package from oracle JOB?

Please suggest me, which is the best way to do automation?
or Any new idea.

2. How to get a latest file or files from FTP site to UNIX box?
On the ftp site we a folder, which contains all the files latest
and old files. Some shell scripts please.

Thanks and appreciate your Help.

Regards

Venkat
and we said...
In my opinion for Number 1 - i would turn all of the anonymous
blocks into plsql stored procedures and run them via dbms_job.
The reasons:

o don't have to secure any usernames/passwords in scripts this
way (or us OS authenticated accounts)

o the jobs will only run if and when the database is up.  If the
database is not running, neither will the jobs.

o if any errors occur, they are logged in the alert log along
with other database issues.  Only one place to look for issues.
I can query a table to see when the job last ran, when it'll run
next, if it failed and so on.

For #2, not sure what you are asking here. Sort of not a
database problem.  But... If you need to sync two directories
using ftp, one approach is:

#!/bin/csh

chdir a
pwd

chmod a= *
ftp aria <<EOF
cd b
prompt
mget *
quit
EOF
chmod u=rw,og=r *
------------------------------------------

that copies from the remote directory B to the local directory A
all files -- we start by removing all access to the existing
files in A and then asking for all files from B.  Ftp will fail
on the transfer of existing files and continue onto the next.
After we are done, we reset the perms on the files.

$ man netrc

to find out how to automate ftp transfers in a script.
November 18, 2000 Adam -- Thanks for the question regarding "PL/SQL release version reporting", version Oracle 8.1.6 64bit on SunOS 5.7
You Asked
Hi Tom,

I just installed Oracle 8.1.6 64 bit version on Sun Ultra-250
(SunOS 5.7).
I noticed that the PL/SQL release version line doesn't showup
when starting sqlplus or svrmgrl. So instead of something like:

Connected to:
Oracle8 Enterprise Edition Release 8.0.3.0.0 - Production
With the Partitioning and Objects options
PL/SQL Release 8.0.3.0.0 - Production

I'm getting:

Connected to:
Oracle8i Enterprise Edition Release 8.1.6.0.0 - 64bit Production
With the Partitioning option
JServer Release 8.1.6.0.0 - Production

This causes for example dbstart to fail (because it tries to
retrieve version number by using svrmgrl and parsing line
containing PL/SQL).

Is the lack of this line normal for this release, or I am just
missing something? (the Pl/SQL is installed - I tried to compile
and run a procedure)

Are there any other utilities that try to get database version
in  similar way?

Adam
and we said...
dbstart and dbshut are pretty much obsoleted.  I would not
recommend using them.  Many things don't update the oratab and
such -- it is just much easier to have a small custom script for
starting and stopping.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:387218751430
for my approach to this.
November 18, 2000 menaka -- Thanks for the question regarding "HELP", version 8.0.5.0.0
You Asked
Hi Tom,

Thanks for helping me previously.
I need to know the procedure for migrating 8.0.5 to 8i.
What all i need to be taken care of?what procedure i should
follow?Let  me know.

Thanks,
menaka
and we said...
It will depend on your circumstances...

- simply upgrading from 8.0.5 to 8.1.7 on the same machine, one
set of procedures.

- migrating an instance from one OS to another OS at the same
time, another set of procedures.

In either case, we have a manual dedicated to all of the cases.
See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76957/toc.htm
for details.
November 18, 2000 Keith -- Thanks for the question regarding "Full table scan/Rollback Segment Backup", version Oracle8i
You Asked
What is considered a full table scan? Syntax?

Also. All of our rollback segments are maintained in the rbs
tablespace. To backup rollback segments, I would backup the
datafile the the rbs tablespace uses correct?

Thanks.

Keith
and we said...
A full table scan is an access path that may be choosen by the
optimizer.  The optimizer will look at the query, at the
available indexes and such and decide whether to full scan the
table or use some other method to access it.  See the designing
and tuning for performance guide for more details on all access
paths available.

You would backup a rollback segment in the same fashion as any
other object.  You backup the tablespaces they are contained in
(by backing up the underlying datafiles).  So, "yes" you would
backup the datafile(s) for the rollback tablespace(s).
November 18, 2000 Tom -- Thanks for the question regarding "What host called Me?", version 8.0.5
You Asked
Is there some way for a stored procedure to determine the host
name or IP address of the client machine that called it?  We
have several client machines connecting to Oracle with the same
user id, and executing a stored procedure.  I'd like the stored
procedure to be able to determine which client machine invoked
it.
and we said...
for 7.3 - 8.0 see:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:526822275627
for 8i and up, see:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:510222107880
for how to get the ip address of the client connecting to you.
November 18, 2000 jeya -- Thanks for the question regarding "procedures", version 8.0
You Asked
Hello Mr.Tom,

I have one Procedure. In this i have sub procedures also. When i
run this procedure it takes long time. You know the records are
above 50,000. So i want to know how can i decrease the run time
of my procedure?. Most probabily it takes 4-5 hours.

Please advice me!

regars,
jeya.m
and we said...
see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76992/ch14_str.htm#1018
for the tools you need to diagnose this.  You'll be able to use
this to find the sql that is performing poorly.  SQL_TRACE and
TKPROF are generally all you need.
November 18, 2000 amanullah -- Thanks for the question regarding "table partitioning related", version 8
You Asked
I have a table with 1200 rows in it.I want to convert that table
into 3 partitions(p1, p2, p3). Means I want to convert the
existing table into a partitioning table.Is that possible?If yes
than how?
and we said...
A table with 1200 rows?  that would not be a good candidate for
partitioning.

You would have to rebuild the table (eg: create new, insert into
it, drop old, rename for example) in order to partition it.

see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:867027378762
for an example.
November 18, 2000 Kelvin -- Thanks for the question regarding "More about ORDImage Features", version 8.1.6
You Asked
Dear Tom,

Currently, we have store a set of Image File in 300dpi in the
ORDImage Object. Now, we want to convert the stored image to
lower dpi value, e.g. 200dpi. Can I do it with Oracle
Internally.

Thanks.
and we said...
See
http://technet.oracle.com/doc/oracle8i_816/inter.816/a67299/mm_imgre.htm#1039642
for a list of operations you can perform on images using the
ORDImage type.

I do not believe you can change the DPI but you can scale/resize
the image.
November 19, 2000 wallacel -- Thanks for the question regarding "session.", version 8.1.6
You Asked
Tom:

after i killed a session, i can still see the session at
V$session, but the status is killed, when this session wil
totally gone? do i need to reboot the instance?
and we said...
The session is *killed* but it is being cleaned up.  When you
kill a session -- outstanding work must still be cleaned up.  It
may take quite a while for this to occur as it is a relatively
low priority background event.

Also, if the user is still physically connected and idle (eg:
they are sitting at a sqlplus prompt) -- we will wait for them
to contact us so we can give them the error message "you are
killed".

Also, in Oracle8i PMON defers transaction recovery of "killed"
sessions to SMON which may use fast start parallel rollback if
necessary.  This frees up locks held by the killed process
immediately.
November 19, 2000 afaq -- Thanks for the question regarding "Finding nth Record", version 8.0.3
You Asked
Hi Tom,

  We are in need in finding the nth record in a table,the
scenario for which is  as follows

EMPNO   ENAME     SAL
 1000   A         10000
 2000   B         20000

 Now Each time the query runs ,we would like it to prompt for
the record number and display the corresponding record, further
we do not have any column representing the record numbers in the
table.

  Ex:
 Upon running the query and asking record no 2 it should display
the second record that is
  2000   B      20000

 Look forward to hear from you soon.

 Thanks in Advance
 Afaq Baig
and we said...
Well, there is no such thing as a record number really but...
rownum can be used.

In Oracle8i, it can be used with any query.  In 8.0 and before -
with any query that does not involve an ORDER BY.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:587023408954
...
November 19, 2000 -- Thanks for the question regarding "Combined Foreign key", version Oracle 8 Personal Edition
You Asked
I have 2 tables called DODETAIL and GDETAIL. I want to create a
combined foreign key on DONO+ITNO of the GDETAIL table
referencing DONO+ITNO of the DODETAIL table.

Please give me the syntax of doing so, while creating the table
GDETAIL. I am writing
CREATE TABLE GDETAIL(GDNO NUMBER(4) REFERENCES GDHEAD(GDNO) ON
DELETE CASCADE,ITNO NUMBER(4) REFERENCES ITEMMAST(ITNO) ON
DELETE CASCADE,GDQTY NUMBER(4) NOT NULL,GDRATE NUMBER(8,2),DONO
NUMBER(4) NOT NULL,FOREIGN KEY(DONO,ITNO) REFERENCES
DODETAIL(DONO,ITNO));

I am getting an error message: NO MATCHING UNIQUE OR PRIMARY KEY
FOR THIS COLUMN LIST.
and we said...
A foreign key can only point to a set of columns that is a
primary key or has a unique constraint ( a unique index will NOT
do it) on it.

That message indicates that DONO,ITNO in DODETAIL are neither
primary keys nor do they have a unique constraint on them.
November 19, 2000 suan -- Thanks for the question regarding "utl_smtp", version 8.1.6
You Asked
Hi, Tom:
I am using utl_smtp to send e-mails.  However, all information
that will be passed are stored in a table, i.e., I can't hard
coded them.
So the table that utl_smtp will get the information is like
this:

email_tab:
id number, number
email_ddresses varchar2(200),
msg_txt varchar2(200),
process_flag varchar2(2)

My question is :
(1) for the msg_txt, since the RFC 821 requires that the lines
to be terminated by <CR><LF>.  So should I make sure the
email_tab:msg_txt is populated by using chr(13)||char(10).  If
it is populated this way, then should I be able to retrieve it
as it is?
(2) can I pass a array of e-mail addresses to the utl_smtp.rcpt.
in my case, email_tab:email_addresses has stored a list of email
addresses. E.g. smith@hotmail.com, ann@yahoo.com.

Thanks a lot for your help!
-susan
and we said...
1) you can -- the worst that will happen is your email would
turn into 1 big line instead of many lines.

You could:

replace (
   replace( msg_txt, chr(13)||chr(10), chr(10) ),
   chr(10), chr(13)||chr(10) )

if you were not sure the text had cr/lf pairs or not.

2) No you cannot pass the array, the spec for UTL_SMTP doesn't
have such an interface.  Instead you just need to call rcpt once
for each array element in the loop.
November 19, 2000 Praveen -- Thanks for the question regarding "temp tablespace+ cpu power", version 8.1.5
You Asked
Hi Tom,

1)In one of the datawarehouses i manage the TEMP tablespace
which is of type temporary gets filled up.Its size is 5gb.
The only solution i then have is to shutdown the database and
hence bring production down.
Is there any other way that i can free up the temp tablespace.
There is only one useroid in the database and all the
application users(Brio users) login to the database using this
particular userid.Would it help if i make the tablesapace type
as
permanent?

2)We are planning to go for an ERP system with 8000 users.
Someone told me that Oracle says that you need 1 cpu per 70
users that means do we need 8000/70===114 cpu's.Is there a
text/document which talks about how to arrive at the true cpu
power?
Also Since sun gives a max of 64 cpu m/c do we have only the
parallel server option to scale up to this much load?

Thanks and Regards
Praveen
and we said...
1) see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:108812348061
temporary tablespaces are not supposed to look empty.  as they
get used, we keep the space allocated.  If you are truely
running out of space -- that indicates you need yet more temp
space.  Shutting down and restarting only SEEMS to fix it cause
you logged out the users using the space (and they went away and
didn't come right back).  Eventually though you are using more
then 5 gig of temp space -- and not because we have hidden some!

don't make it permanent -- the recursive sql for space
management will really slow you down -- alot!

2) thats concurrently active users.  Typically in a system such
as you describe -- there will be lots of think time involved.
You'll have 8k users connected, however at any point in time,
may 10% or 800 of them will be active.  Now we are into the
realm of 10-20 cpus.  On a system with 8k connected users you
will be using features such as MTS (Multi-threaded server) and
or connection pooling and or connection multiplexing via
connection manager.  These technologies let us connect lots more
users to a database they you could with the dedicated server
mode.  For example, with your ERP application, you do not need
8k processes out there running - you'll have a much smaller pool
of connections -- and the size of this pool will drive the size
of your machine.
November 20, 2000 Balbeer -- Thanks for the question regarding "download Pro*C", version Oracle 8i
You Asked
Dear Tom,

Can you please tell me from where can I download Pro*C for
windows version. I have already installed Oracle 8i, but it
seems to me that there are no precompilers installed.

I have browsed a lotta web sites but could'nt get the right one.
can you please give me some hint or some URL's from where I can
download the pro*C precompilers for windows.

i will really appreciate If you could please do this favour to
me.

Thanks

BAlbeer
and we said...
Pro*C is in the Oracle8i client install.  If you have the
Oracle8i CD or have built a staging area -- you already have the
software.  There is no separate download for "Pro*c" all by
itself.

All you need to do is:

Insert the Oracle8i CD for either Standard or Enterprise
edition.

Click on Install/Deinstall product.

Click on Next. Select the Oracle8i target Oracle home

Click on Next. Select the option that says

"Oracle8i Client 8.1.6.0.0
Installs enterprise management tools, networking services,
utilities, development tools and PRECOMPILERS and basic client
software"

Proceed to install Pro*C -- it is in the client software bundle.
Review & Followup
Rating: 4
March 15, 2002
Reviewer: Andrew from GR
Hi Tom

Your sort answer it was VERY VERY USEFUL for me. I was looking how to install
precompiler to a SUN server and you answer to my search

THANKS
Andrew

November 20, 2000 Pauline -- Thanks for the question regarding "Tablespace point in time recovery", version Version 8.1.5.0
You Asked
Hi Tom,
One of our critical database is 24*7 database and it only has
hot backup. If user by accident drop a table, import and
incomplete recovery are not feasible. The ideal recover strategy
for it should be tablespace point in time recovery. Can you
provid detailed procedure about it ?
Many thanks.

Pauline
and we said...
Basically, in order to do an "automatic" tablespace point in
time recovery, you need to be using RMAN.  If you are using
RMAN, then please see:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76993/ostspitr.htm#430218
for the details.  If you are NOT using RMAN -- you can still do
this, you must do it yourself.  Here is what you can do:

o on another machine (i like to use another machine) restore
your hot backup of SYSTEM, ROLLBACK, TEMP and the tablespace you
want to recover.

o offline drop the other datafiles from this instance.

o do a point in time recovery of this instance to the point in
time you desire.

o export the affected table or tables.  You can use a
transportable tablespace to get the entire tablespace.

o import the objects

This is basically what RMAN is doing under the covers.
November 20, 2000 wu -- Thanks for the question regarding "Can I update from more than 2 tables", version 8i
You Asked
From H.jty
To   Tom
Date: 20001120

Hi Tom£º
   I use:
      update Table1
         set Table1.f1 = Table2.f2
         from Table1, Table2
         where Table1.key = Table2.key
   It's rase error. How can I do this purpose in one statement.
   Tank's in advance.
and we said...
That syntax is specific to SQLServer.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:164612348068
for three standard methods for achieving the same.
November 20, 2000 Maya -- Thanks for the question regarding "'CREATE DIRECTORY' performs COMITT", version 8.0.4
You Asked
Hi,

We are trying to update an image in a table contains BLOB data
type column.

the steps are:
1. delete (without commit)
2. create or replace directory
3. insert a new image

In case that INSERT fails, we want to keep the privious image.
The CREATE DIRECTORY step performs a commit, which cause a loose
of the image.

Is there a way to avoid the commit, or any work around?

Thanks in advance!

Maya
and we said...
In 8.0.4, no, all DDL commits.

I would suggest switching 2 with 1 (actually i would highly
recommend AGAINST doing DDL as a "matter of fact".  DDL should
be done only when needed.  If you are doing the create or
replace directory as a "matter of fact", for each transaction --
you need to rethink that.  DDL is extremely expensive, serial in
nature, and not something you want to do frequently.)

At the very least -- it should be a CREATE -- never OR REPLACE.
Create it once and leave it alone.  Only create new ones when
you need to.  In that way, you'll only create a finite number of
directories an eventually you won't create any more.
November 20, 2000 OP -- Thanks for the question regarding "BLOB problem !", version 8.1.6
You Asked
Dear Tom,

Hi !

How are you doing !

I read the response from you related to CLOB and BLOB.
Yes, the insert statement directly works with CLOB.But
it doesn't work with BLOB ?

As far as BLOB is concerned I have written a small
procedure according to the hints given by you.The
code is as follows.

create or replace procedure p1(t varchar2)
as
TRAW RAW(2000);
begin
TRAW:=utl_raw.cast_to_raw(t);
insert into tempo(j) values(TRAW);
end;

But,the problem is if the data is huge,this is not able to
write all.Can you suggest some alternative for this !!! as
this does'nt seems to be complete ? Do I need to convert
this Raw again into BLOB !!

Also if I have to select the values from the BLOB column,
in that case I must convert raw into varchar ? If Yes,
then what is the opposite function of cast_to_raw.

To summarise,I AM LOOKING FOR A SOLUTION FOR MY DEVELOPER
SO THAT THEY ARE ABLE TO WRITE AND READ DATA FROM A BLOB
DATATYPE.

Kindly Help !

Regards
OP

ADDITIONAL INFORMATION

I am sorry,I forgot to mention the language used by the
Developers.

Few of them want to access BLOB through java+jdbc and few
are working with PL/SQL !

Thanks & Regards
OP
and we said...
The simple answer is see
http://technet.oracle.com/doc/oracle8i_816/appdev.816/index.htm
for specifics. There is a document there

Oracle8i Application Developer's Guide - Large Objects (LOBs)
using PL/SQL

and

Oracle8i Application Developer's Guide - Large Objects (LOBs)
using Java

In PLSQL, they must deal with the blob 32k at a time as this is
a limit of plsql.  PLSQL can process the entire blob, it just
must do it 32k at a time using dbms_lob.read|write.

Java will do it via streams.
November 20, 2000 debabrata -- Thanks for the question regarding "regarding the oracle magazine", version oracle ver 7.3
You Asked
Respected Sir,
I have enrolled for the free subscription of Oracle Magazine. I
have got one issue of September/October .But after that I am not
getting any issue. But it is very important for those who are
working in purely Oracle environment.Please tell my what to do.I
know this is a different question but try to give me the
solution.

thanking you,

debabrata das
and we said...
For subscription questions, use
http://www.oracle.com/oramag/misc/s_and_a.html#customer_svc
or have subscribers send an email to oracle@halldata.com.
There's always a delay in getting subscriptions going,
regardless of whether it's overseas or domestic.
November 21, 2000 Naren -- Thanks for the question regarding "question on "archival required"", version 2.0
You Asked
Hi Tom
I am using Webdb on Oracle 7.3.4.in non archive mode.
I am trying to create web site using it but every time it stops
in middle with error "Oracle archival is required,log can not
created."
Is website creation required auto archival or I am doing
mistake.
Thanks
NP
and we said...
If the error is "archival required" you are NOT in no-archive
log mode.  You have disabled automatic archival but we are STILL
in archive log mode.

Try issuing:

SVRMGR> select log_mode from v$database;
LOG_MODE
------------
ARCHIVELOG

It'll confirm my suspicion that you are in archive log mode.

Either disable archive log mode (it is an alter database command
-- see the admin guide) or enable automatic archival.
November 21, 2000 Tripti -- Thanks for the question regarding "storage of tables", version version 8.2.1
You Asked
How are tables stored in the hard disk? Are they stored as flat
files?
and we said...
see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/toc.htm
covers everything in this area.

short answer = No, they are not stored as flat files.
November 21, 2000 Tripti -- Thanks for the question regarding "upgrading the database", version version 8.2.1
You Asked
Hello Tom

Tom, i've not yet worked with export & import? If the database
tables are present in oracle 7.x.x & now the database needs to
be upgraded to oracle 8.x.x, then how do i do it without any
lose of data?
Can your please give me the entire procedure to do so?

Thanks
and we said...
This document
http://technet.oracle.com/doc/oracle8i_816/server.816/a76957/toc.htm
goes over all of the alternatives in some detail.
November 21, 2000 brian -- Thanks for the question regarding "Reassigning values to an indexed field", version 8.0.5.0.0
You Asked
Looking to reassign a sequence of numbers in a field on a table
per other key fields on the table, without using any hard-coding
of the key fields to be sorted by.

i.e.

field1 field2 field3(NUM)
A      A      1
A      A      2
A      A      5
A      B      1
A      B      3
A      B      7

would become:
field1 field2 field3(NUM)
A      A      1
A      A      2
A      A      3
A      B      1
A      B      2
A      B      3

This would mimick an ON-BREAK command of sorts, but that is for
other languages.

Thanks for your help
and we said...
In 8.1.6 this might be possible with the new analytic features.

In 8.1.5 and before -- a stored procedure with some procedural
code is the only way to do this I can see.

something like:

...
  last_f1 := 'xxx';
  last_f2 := 'xxx';
  cnt     := 1;
  for x in ( select a.*, rowid rid from T order by f1, f2 )
  loop
      if ( x.f1 <> last_f1 or x.f2 <> last_f2 ) then
         cnt := 1;
         last_f1 := x.f1;
         last_f2 := x.f2;
      end if;
      update t set field3 = cnt where rowid = x.rid;
      cnt := cnt + 1;
  end loop;
end;
/
November 21, 2000 Andre -- Thanks for the question regarding "Domain idx´s, Oracle 8.1.7, partitioning and IOT´s", version 8.1.6
You Asked
Hello Tom,

1) What are domain indexes ?

2) Can you briefly describe the new features in 8.1.7,
especially row-level encryption ?

3) Why do DSS systems benefit from local nonprefixed indexes on
partitioned tables ? And why do OLTP systems benefit from global
and local prefixed indexes ?

4) The concept of logical ROWID´s on IOT´s is still a little
confusing to me. How is it formed, and could you elaborate on
the concept of "guess" ?

Thanks !
and we said...
1) domain indexes are indexes not naturally provided by Oracle
(such as b*tree or bitmapped).  They represent some domain
specific method of utilizing the data to retrieve other
information.

For example, interMedia text utilizes a domain index on text
fields.  This domain index organizes keywords into an inverted
list index of sorts to speed the query on keywords in documents.
 They've used their domain knowledge of text to store the
keywords in a way that allows for efficient retrieval.

You can build your own domain indexes if you wish as well.  You
can extend the functionality of the create index command to be
able to create YOUR indexes.

2) field level encryption is a feature of Oracle8i release 2
(8.1.6) actually.  Search for dbms_obfuscation on my site for
some examples.

To read more about enhancements to that package and all of the
new 8.1.7 features -- see:
http://technet.oracle.com/docs/products/oracle8i/doc_library/817_doc/addendum.817/a85455/toc.htm

3) To answer this -- I'll start with a quote from the concepts
manual (8.1.6 server concepts):

...
Importance of Nonprefixed Indexes

Nonprefixed indexes are particularly useful in historical
databases. In a table containing historical data, it is common
for an index to be defined on one column to support the
requirements of fast access by that column, but partitioned on
another column (the same column as the underlying table) to
support the time interval for rolling out old data and rolling
in new data.

Consider the SALES table presented in Figure 11–1 on page 11-3
("SALES Table Partitioned by Week"). It contains a year’s worth
of data, divided into 13 partitions. It is range partitioned on
WEEK_NO, four weeks to a partition. You might create a
nonprefixed local index SALES_IX on SALES. The SALES_IX index is
defined on ACCT_NO because there are queries that need fast
access to the data by account number. However, it is partitioned
on WEEK_NO to match the SALES table. Every four weeks the oldest
partitions of SALES and SALES_IX are dropped and new ones are
added.
....

so, they describe a local non-prefixed index on a SALES table
that is partitioned by WEEK_NO but indexes ACCOUNT_NO.  Every
week/month, a new partition is added and an old partition
removed (sort of a sliding window).  Since the index is a local
index -- only the new partition needs to be indexed -- not the
entire thing (so that is good).  Additionally -- since are are a
DSS site and maybe using parallel query (this is the part they
don't mention), a query like:

  select sum(sale) from table where account_no = 5;

can use a parrallel index range scan on the underlying physical
partitions of the index.  If this index were "prefixed" we would
have to include WEEK_NO in the above query in order to use that
index.

So, a local index is good for the rolling window or adding new
partitions at one end.  The fact that it is non-prefixed means
we do not have to include the partition key in all queries
(which might not be possible -- as in the above, we don't know
what all the weeks are).  The fact that it is partitioned means
we can scan in parallel.

OLTP benefits from prefixed indexes since we can perform index
partition elimination on them.  If we have 100 partitions --
when we use a pre-fixed partition index -- we most likely will
hit 1 partition -- not all 100.  That is the benefit there.

4) The logical rowid is formed as a function of the primary key
or a function of the primary key and the current physical
location of the row.  The "guess" concept says the logical rowid
should include a guess as to the physical location of the row in
it to avoid having to have 2 scans when accessing an IOT via a
secondary index.  This is typically applicable on static code
type tables only as the guess will become stale rapidly in a
table that is modified frequently.
Review & Followup
Rating: 4
local indexes on partitioned table November 08, 2001
Reviewer: Cynthia Pinchot from Denver, CO, USA
I had been trying to figure out which was better
prefixed or non-prefixed local indexes.  The article
was helpful.

November 21, 2000 Tripti -- Thanks for the question regarding "Size of a table", version version 8i
You Asked
Hello tom

what is the size of any table? How much space does a table
occupy on the HArd Disk? What is the size of a new table without
any records in it?

What is the size of the Context Area?

Thanks
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
every table takes at least 2 blocks on disk -- you set the block
size and you set the extent size so you are the only one that
knows what the size of a new table YOU created takes spacewise.

The server concepts manual,
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/toc.htm
has a wealth of this sort of information.
November 21, 2000 Jeff -- Thanks for the question regarding "retrieval programatically of database domain name for create database link command", version 2.2.4
You Asked
Tom,

I need to submit a query via pro*c similar to select table1.col1
minus table2.col2. The catch is, though the first table is in a
schema I am connected to by default, the second table is
probably in a separate schema, and almost as probably in a
separate schema, possibly on a separate machine. All I have for
sure is a username, password, and connect string to the "remote"
instance.

I have determined that using a database link is the only way to
do this query (aside from retrieving both tables separately and
programatically finding the answer by comparing large lists).

I have found further, via experimentation in sql plus 3.3 that
though I may not know the right value to use for the database
link, I generally can get it from the error message which
results from the following create and select statements:

SQL> create database link max_link
  2  connect to maximo
  3  identified by maximo using 'ntclib';

Database link created.

SQL> desc part@max_link;
ERROR:
ORA-02085: database link MAX_LINK.WORLD connects to CLIB.WORLD

Then, this seems to work:

SQL> create database link clib.world

Database link created.

SQL> desc part@clib.world;

Since this is going to run at different customers sites, is
there some way programatically I can retrieve the equivalent of
"clib.world" that will work correctly in a create database link
statement, given that I am in Pro*C and have the connect string,
user name, and password?

Thanks

Jeff Kish
and we said...
You can just issue:

alter session set global_names = false;

since you don't need global names in your case -- that would be
the easiest solution:

ops$tkyte@DEV816> desc dual@foo
ERROR:
ORA-02085: database link FOO.US.ORACLE.COM connects to
ORA8I.WORLD

ops$tkyte@DEV816> alter session set global_names = false;
Session altered.

ops$tkyte@DEV816> desc dual@foo
 Name                                                  Null?
Type
 ----------------------------------------------------- --------
------------------------------------
 DUMMY
VARCHAR2(1)
November 21, 2000 Hetal -- Thanks for the question regarding "How many index scan is taking place", version 8.1.5
You Asked
Hi Tom,
  Thanks for letting me ask a question.
I have a query :
SELECT count(*) from tablea where col_1='XXX' or col_1='xxx' or
col_1='Xxx';
There is an index on this column.
  The explain plan shows that the index on that column is being
used. I would like to know how many times the index scan would
take place - once for all three values or 3 times. I would say
it is taking place only once but the other team members disagree
on it. Can you please let me know what is actually taking place.

I know i could have written the query
SELECT count(*) from tablea where upper(col_1)='XXX' and use
FBI.

Thanks
Hetal Patel

P.S. I find this Ask Tom feature very helpful. I come here once
a week and try to review as many questions as possible. Thanks
for your time. I am sure lots of people are benefitting.
and we said...
The execution plan of such a query will most likely be:

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   SORT (AGGREGATE)
   2    1     CONCATENATION
   3    2       INDEX (UNIQUE SCAN) OF 'SYS_C0034510' (UNIQUE)
   4    2       INDEX (UNIQUE SCAN) OF 'SYS_C0034510' (UNIQUE)
   5    2       INDEX (UNIQUE SCAN) OF 'SYS_C0034510' (UNIQUE)

(or range scan if the index is not unique).  This query is
processed typically much like:

select count(*)
  from ( select 1 from tablea where col_1 = 'XXX'
         union all
         select 1 from tablea where col_1 = 'xxx'
         union all
         select 1 from tablea where col_1 = 'Xxx'
       )

In short -- it'll probe the index 3 times and concatentate the
results together.
November 21, 2000 Dennis -- Thanks for the question regarding "In a trigger, how do I ascertain the roles to which the invoker belongs?", version 8.1.6
You Asked
Dear Tom,

as part of the processing of a trigger, I want to check that the
invoking user -- as opposed the owner of the trigger -- is a
member
of a particular role.

On my first attempt, I tried selecting from SESSION_ROLES, which

didn't return ANY rows.

My second attempt was to query USER_ROLE_PRIVS, which quickly
established
that this returned the privileges of the owner of the trigger,
rather than
those of the invoker.

My third attempt was to query DBA_ROLE_PRIVS, but discovered
pretty
quickly that unless an explicit grant is given to the owner of
the
trigger it won't work. (Unfortunately, this isn't possible.)

My fourth attempt was to try the query from within an EXECUTE
IMMEDIATE
statement, but this returned an ORA-00942, i.e. table doesn't
exist.

Any ideas on how I can sensibly ascertain which roles the
invoker of
a trigger has been granted?

regds,
Dennis Cook
and we said...
A trigger always is compiled with definers rights.  All queries
against the data dictionary will be made under the schema of the
OWNER of the trigger minus any roles that user has (eg: if the
owner of the trigger issues "select count(*) from all_objects"
in sqlplus and then does the same in the trigger -- they will
most likely get a different count since in the trigger their
roles are not active and they can see less objects they with
roles active).

Since roles are disabled in the execution of the trigger --
session_roles (which lists the currently logged in users active
roles) will be empty since they have no active roles in the
trigger.

The dynamic access won't work either since once roles are gone
in the trigger -- they are gone and you cannot get them back
(until you exit the trigger).  Invokers rights procedures won't
help you at all here either.

I'm afraid that your only opportunity to get this information is
to in fact query the DBA_ROLE_PRIVS or related DBA view.  I
would actually suggest not using DBA_ROLE_PRIVS but asking your
admin group to write you a procedure that returns TRUE or FALSE
if a given user has a given privelege (eg: a function like:

create function has_priv( p_user in varchar2,
                          p_priv in varchar2 ) return boolean
....

and granted you execute on that.  I would also suggest they use
a view more like that i have at:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:853427230099
rather then dba_role_privs which can be very expensive to
evaluate.

If you need to know the roles -- you will need access to this
information from the DBA tables.  It is the only way.
November 21, 2000 -- Thanks for the question regarding "rman", version 8.1.6
You Asked
Tom:

sometimes I saw RMAN example didn't explicitily
release channel, is that correct?
if so, at what situation can i not release channel explicitily?

example
run{allocate channel ch1 type disk;
backup datafilecopy '/oracle/copy/a.copy''}
and we said...
The definition of release is:

...
To release a channel while maintaining the connection to the
target database instance. Specify the channel name with the same
identifier used in the allocate channel command. This command is
optional; RMAN automatically releases all channels allocated
when the run command terminates.
.....

so, you don't need to use it unless you want to.  It'll be done
for you.
November 21, 2000 -- Thanks for the question regarding "one or two query?", version 8.1.6
You Asked
Tom:

I have a question like below:

for example i have table a(a int primary key,b int)
table b(d int primary key,e int);

what i want to do is
1.
select a.a,a.b,b.e from a,b
where a.a=1 and b.d=1;

i can do query for that also,
2.
select a.a,a.b from a where a.a=1;
select d,e from b where d=1.

at first thought i think the second one is better,
but since the first one only have one query, and
parse take some times, maybe sometimes one query
is better than two query, can you explain it to me?
and we said...
The first one would be faster and more efficient.

The second one would be more clear.

Apparently there is no relationship between A and B.  You are
using the fact that a(a) and b(d) are the primary keys and the
predicate

  where a.a = 1 and b.d = 1

returns exactly 1 row from each table.  you then cartesian
product these 2 singletons together to produce the result set.

So, either works OK, the second might be less confusing to the
next developer to inherit your code.  The first will be faster
(and if you comment it decently, may not be an issue)
November 21, 2000 sunil -- Thanks for the question regarding "The Recovery Option", version 7.3.4
You Asked
Hi Tom,
   i am running a 7.3.4 version of Oracle Server.  i have Oracle
Applicatins 10.7 running on this server.  we run the database in
archive log mode and take the database hot backups. The question
i am to ask is, suppose i lost all my datafiles and the
controlfile and i am with only the archive log files, the
datafiles from the hotbackup and also the control file from the
hotbackup, would i be able to get the database up to the last
moment it was accessed?
   if not till when i would be able to recover.  If yes then
where does the Oracle keep the last transaction that was made.
   Thanks in advace, tom
sunil.
and we said...
You didn't mention what happend to the online redo log.

Assuming we had the online redo log -- yes, you can get all the
way back to the last committed change.  if you lost the online
redo log as well -- we would lose any changes contained in them
that was not yet archived.

That is the answer to the question "where does Oracle keep the
last transaction".  It is in the online redo log.
November 21, 2000 Greg -- Thanks for the question regarding "Procedures with Dependencies on Tables", version 8.0.6.1.1
You Asked
Tom,

I found your article "Using Packaged Procedures", in the
September/October 2000 Oracle magazine very informative.  We
have an application that uses multiple stand alone procedures
along with packages.  The application does a series of table
drops and renames every day.  When we do these drops/renames the
state of the procedures (and packages) becomes invalid (as
expected) because of the dependencies on the dropped/re-named
tables.  We have settled for waiting ofr the database to
auto-recompile the procs when they are executed).  Is there a
way to avoid having the states of the stored procedures/packages
invalidated when we do a table drop or rename?

Any suggestions would be appreciated.
Thanks,
Greg.
and we said...
Other then by not dropping and renaming -- yes there is.

If you dynamically refer to all objects, using DBMS_SQL in
version 8.0 and before or EXECUTE IMMEDIATE in 8i and up, you
can break the dependency between the PLSQL code and the database
objects.

In 8.0, this is hard to do.  You'll lose the ability to do
cursor for loops, binding is a little harder and so on.

In 8i, this is very easy -- trivial almost.

I would not recommend this in 8.0 as it would be a large recode.
 In 8i it is much more feasible.

If at all possible -- i would solve the problem by NOT dropping
and renaming.  Why not truncate?
November 21, 2000 ken -- Thanks for the question regarding "schema name in pl/sql block", version 8.1.5.0.0
You Asked
Tom,

Your reply will be always be very much appreciated.

I tried to get the column value of a table that is owned by
every user in the database i.e each user has its own copy of
this table with the same structure.  I tried the following:

SQL> DECLARE
  2
  3     v_biller                varchar2(3);
  4     v_fix_string            varchar2(50) := 'Table/Column';
  5     v_string                varchar2(255);
  6     v_count                 number := 0;
  7     v_column_value          varchar2(10);
  8
  9     CURSOR tla is
 10            select lower(owner)
 11            from dba_tables
 12            where table_name = 'T_BILLER' and length(owner) =
3
 13            order by 1 ;
 14  BEGIN
 15
 16
 17     OPEN tla;
 18
 19          loop
 20               fetch tla into v_biller;
 21               EXIT WHEN tla%NOTFOUND;
 22               select c_presentation into v_column_value
 23                from v_biller.t_biller ;
 24               dbms_output.put_line('the string is : ' ||
v_column_value);
 25
 26          end loop;
 27
 28     CLOSE tla;
 29
 30  END;
 31  /
              from v_biller.t_biller ;
                   *
ERROR at line 23:
ORA-06550: line 23, column 20:
PLS-00201: identifier 'V_BILLER.T_BILLER' must be declared
ORA-06550: line 22, column 14:
PL/SQL: SQL Statement ignored

Is there another way of accomplishing the same thing without
having to connect as each user.

Thanks
KQ
and we said...
You have to use dynamic sql to do this.

replace lines 22-23 with:

  execute immediate
  'select c_presentation from ' || v_biller || '.t_biller'
  into v_column_value;

That syntax is valid for Oracle8i and up.  In earlier releases
you would have had to of used the DBMS_SQL package.
November 21, 2000 Keith -- Thanks for the question regarding "Transactions during online backup", version Oracle8i
You Asked
Tom,

If a user/application tries issuing a DML statement just as or
during a online backup, 'alter tablespace * begin backup', takes
place, what happens to that users transaction?

Thanks.

Keith M. Cutler
and we said...
It takes place as normal.  Hot backups in no way impede online
transactions.  They continue as normal.

see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:271815712711
for additional details on what is happening during hot backup
mode.
November 21, 2000 Andre -- Thanks for the question regarding "Save Undo", version 8.1.6
You Asked
Tom,

What is "save undo", and how can it be dealt with ?

Thanks !
and we said...
save undo is undo saved for offlined tablespaces.  It is also
known as deferred rollback

A "Deferred Rollback" segment is created for a tablespace
when a tablespace is taken offline.  Undo records are written
to the deferred rollback segment of a tablespace when undo is
being applied to a tablespace which is offline, hence, the undo
cannot be applied.

The undo stored in the deferred rollback segment is applied when
the tablespace comes back online.  The deferred rollback segment
is automatically removed after the undo has been applied.

Deferred rollback segments always reside in the system
tablespace.

As for "how can it be dealt with" -- i would need to know what
issue you are having with it first.
November 21, 2000 Zsolt -- Thanks for the question regarding "Migrating data", version 8.1.5 for Linux
You Asked
Hi,

1. Is there a tool or a quick method to convert data from d-base
IV tables to Oracle?

2.I have many tables. What is the easiest approach to
make a script that creates all these tables on a different
Oracle server?

3.Is there a way to change a the foreign contraint in an
existing table? I couldn't find in the Dba Studio.

Thank you very much

Zsolt Csillag
and we said...
1) see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:711825134415
also, ODBC can be used.  SQLplus can even use ODBC and you can
use the sqlplus copy command.

2) are these dbase tables?  If so, see above -- it can generate
a create table from a dbase file for you.  If not, please
clarify.

3) We can drop and add constraints on a table.  To "change" a
foreign key involves dropping the old one and creating a new
one.
November 21, 2000 Alessandro -- Thanks for the question regarding "BLOB or BFILE fileld on the Web", version version 8.1.6.0.0
You Asked
Hello Tom!

I'm trying to setup a web site based on Oracle db. I have
successfully created a few ASP pages to view/modify data in
"conventional" tables (that is, with NO BLOB or BFILE fields
:-). Now I have to build a table containing a field of this type
(a GIF file to be displayed on the browser).

I tried using a BFILE field:

create or replace directory floppy_dir as 'A:\';
grant read on directory floppy_dir to ctxsys;
insert into test values (2, 'TEST2', 1, BFILENAME('floppy_dir',
'mygif.gif'));

...but when I load the ASP page to display the gif I receive:

Microsoft OLE DB Provider for ODBC Drivers error '80040e21'

Multiple-step OLE DB operation generated errors. Check each OLE
DB status value, if available. No work was done.

I tried using a BLOB field (test.gif):

declare
l_blob blob;
l_bfile bfile;
begin
insert into test values (1, 'TEST1', 1, EMPTY_BLOB())
returning gif into l_blob;
l_bfile := bfilename('floppy_dir','mygif.gif');
dbms_lob.fileopen(l_bfile);
dbms_lob.loadfromfile(l_blob,l_bfile,dbms_lob.getlength(l_bfile))
;
dbms_lob.fileclose(l_bfile);
end;
/

...and I get the following error:

ERROR at line 1:
ORA-22285: non-existent directory or file for FILEOPEN operation
ORA-06512: at "SYS.DBMS_LOB", line 475
ORA-06512: at line 8

As you understand, I'm an absolute beginner. What am I doing
wrong? Which tools do you suggest me to use to accomplish my
task: WebDb, Oracle/Forms, pure ASP/Java pages, or...? Where can
I find some basic working examples to get started?

TIA for your support and patience (and apologies for this long
post and my poor English!).

Regards, Alessandro.
and we said...
Use 'FLOPPY_DIR', not 'floppy_dir'.

Object names in Oracle are folded to upper case -- the name of
the directory you created is 'FLOPPY_DIR' not 'floppy_dir'.  If
you want to use lower case in the character string constant, you
could:

create directory "floppy_dir" as 'A:\';

The quoted identifier will preserve the case of the object name.
November 21, 2000 Pauline -- Thanks for the question regarding "randomly select rows from table", version Oracle 8.1.5
You Asked
Tom,
Would you please tell how to select rows from one table
randomly?
Thanks.

Pauline
and we said...
Use the SAMPLE builtin.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/ch2.htm#103320
for details.
November 22, 2000 Andre -- Thanks for the question regarding "Continuing "Save Undo"...", version 8.1.6
You Asked
Continuing the following issue from yesterday:

You Asked

Tom,

What is "save undo", and how can it be dealt with ?

Thanks !

-----------------------------------------------------------------
---------------
and I said...

save undo is undo saved for offlined tablespaces.  It is also
known as deferred rollback

A "Deferred Rollback" segment is created for a tablespace
when a tablespace is taken offline.  Undo records are written
to the deferred rollback segment of a tablespace when undo is
being applied to a tablespace which is offline, hence, the undo
cannot be applied.

The undo stored in the deferred rollback segment is applied when
the tablespace comes back online.  The deferred rollback segment
is automatically removed after the undo has been applied.

Deferred rollback segments always reside in the system
tablespace.

As for "how can it be dealt with" -- i would need to know what
issue you are having with it first

====================

Continuing with my question today:

What does not make sense to me is: How can undo be generated for
a tablespace that is offline, since no operations are allowed on
it ?

Thanks again !
and we said...
Fire up 2 sqlplus sessions.  The, execute the following sequence
of events (assuming you are allowed to offline the USERS
tablespace -- if not, find one you can)

TIME     SESSION 1                        SESSION 2
-----    -------------------              -------------------
t1       create table t (x int)
         tablespace users;

t2       insert into t values ( 1 );

t3                                       alter tablespace users
                                         offline;

You can offline a tablespace with pending transactions.  That is
the simple case.  Here the rollback must be preserved so we can
rollback these transactions.

The same can happen if a tablespace goes offline unexpectedly --
due to a disk drive being removed from the system somehow (eg:
fails).  We need to ensure the undo for that tablespace is
preserved.

So, save undo is "saved UNDO" -- undo that was generated in the
normal rollback segments but saved for some reason in the event
it is needed in the future.  We save this in system rather then
burdening the regular rollback segments with this as we use them
in a circular fashion and this saved undo would cause them to
fill up.
November 22, 2000 Gursev -- Thanks for the question regarding "To return a result Set", version 8.1.6.0.0
You Asked
thanks for the last question about mangement sever the documnet
send by you came really handy and i was able to install
Managment server thanks

today i am stuck with a problem as i am not aware of java and
have to create a procedure which can return a result set that is
select * from tab or any other tables.
and can be executed or called from a java  front end.
if  you have somekind of sample also it will be really great.

thanks in advance.
and we said...
See
http://osi.oracle.com/~tkyte/ResultSets/index.html
for exmaples in many environments including java.
November 22, 2000 zam -- Thanks for the question regarding "How to show missing date between given range with count absents days", version 7.3 or 8.0.5
You Asked
Hi
How r u TOM?
Thank u for u r answer of my last question of "How to show
missing date between given range"
Can we show the no of absents in the given date range.
Like

EMPNO      ATTEND_DA absent
---------- --------- ----------
       101 06-JAN-00 1
       101 08-JAN-00 2
       101 15-JAN-00 3
       102 08-JAN-00 1
       102 15-JAN-00 2

I try to get this but I'm fail..

For more feedback please go at
http://osi.oracle.com/wa/ask/owa/ask_tom_pkg.display?p_dispid=1045832114333

      and we said...
In Oracle8i release 8.1.6 you'll be able to do this with the new
analytic functions:

ops$tkyte@DEV816>
ops$tkyte@DEV816> select a.*,
  2         row_number() over ( partition by a.empno
  3                             order by a.attend_date ) rnum
  4    from ( select empno, start_date+r-1 attend_date
  5             from t2,
  6                ( select empno, min(attend_date) start_date,
  7                 max(attend_date)-min(attend_date)+1 num_days
  8                      from t
  9                     group by empno  ) t1
 10            where t2.r <= t1.num_days ) A,
 11         t B
 12   where a.empno = b.empno(+)
 13     and a.attend_date = b.attend_date (+)
 14     and b.attend_date is NULL
 15     and to_char( a.attend_date, 'dy' ) <> 'fri'
 16  /

     EMPNO ATTEND_DA       RNUM
---------- --------- ----------
       101 06-JAN-00          1
       101 08-JAN-00          2
       101 15-JAN-00          3
       102 08-JAN-00          1
       102 15-JAN-00          2

But in 8.1.5 and before, you must procedurally assign this
number as you fetch the data -- reseting a counter in your own
fetch loop.
November 22, 2000
      Aderette -- Thanks for the question
      regarding "\types of parameters to db procedures", version 8i

      You Asked
what types of parameters exist for a db procedure ?
I know the following: number, varchar2. I have an application
which requires an array, like all employees in a certain
department emp.empno How can I return such an array ?

      and we said...
Well, you can use lots of datatypes -- including your own object
types and collections (like arrays) of these.  You can have
collections of simple scalars, or collections of objects (user
defined datatypes).

For returning something like the above however, I would use a
ref cursor.  See

http://osi.oracle.com/~tkyte/ResultSets/index.html
for what that looks like.  If the data is in a table and a query
can be used to collect it -- use that.

For examples of arrays to/from java for example, see

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:712625135727
...
November 22, 2000 Richard -- Thanks for the question regarding
      "Oracle Stored Procedures", version Oracle 7.3.4

      You Asked
I want someone in plain English to explain to me how to write
Oracle Stored Procedures.  Giving an example scripted based on a
"noddy" (simple) database.  This procedure should include
parameters as I want to be able to execute the procedure and
enter parameters.  Can you also tell me how to call it!

      and we said...
Ok, I'll use SQLPlus to do this.  I'll start by creating a user
and granting them the absolute MINIMUM privileges they need to
connect and create a procedure.  It is more common to grant
connect and resource to these people but those roles convey lots
more privs then you absolutely need.

Then, I will create a stored procedure that takes an input and
provides an output.

We'll use the sqlplus method of defining a variable to hold the
ouput result and print it.

It would look like this:

ops$tkyte@ORA734.US.ORACLE.COM> create user demo identified by
demo;

User created.

ops$tkyte@ORA734.US.ORACLE.COM> grant create session, create
procedure to demo;

Grant succeeded.

ops$tkyte@ORA734.US.ORACLE.COM> connect demo/demo
Connected.

demo@ORA734.US.ORACLE.COM> create or replace
    procedure a_procedure( p1 in number, p2 out number )
  2  as
  3  begin
  4          p2 := abs(p1);
  5  end;
  6  /

Procedure created.

demo@ORA734.US.ORACLE.COM> variable p2 number
demo@ORA734.US.ORACLE.COM> set autoprint on

demo@ORA734.US.ORACLE.COM> exec a_procedure( -5, :p2 )

PL/SQL procedure successfully completed.

        P2
----------
         5

November 22, 2000 Shane -- Thanks for the question regarding
      "Getting a fixed length file from a script in SQL*PLUS", version 3.3.2.0.2

      You Asked
Dear Tom,

I am trying to do something that should be simple but I can not
seem to find out how to do it. Maybe you can help.

I need to extract a table to a fixed length file (Oralce8i).
I just want the data in the file, nothing else.
I need to ftp this file to an AS/400. But I have to remove three
lines manually from the file every time. This prevents me from
automating the whole process.

Here's the steps and the problem:
1. At the SQL prompt I enter spool C:\test.txt
2. I then run the script @test.sql (below) and it gives me the
data.
3. I then at the sql prompt enter spool off.

When I look at the txt file produced I get the

  SQL> @test

  GE1EURTY200010AVCINC-GB1  538           500000000000000
  GE1EURTY200010AVCINC-GB1  538           500000000000000
  etc.....
  SQL> spool off

What I want to do is get rid of the "SQL> @test", the following
blank line and the "SQL> spool off" at the end of the file. That
will give me a nice tight file of fixed length data.

I have tried many of the , if not all, relevant SET cmds but I
can not seem to get rid of them. Would you know a way to get rid
of them?

TEST.SQL
*********

set heading off
set pagesize 2000
set linesize 1000
set feedback off
set verify off

select     rpad(NVL(GL_PREFIX,' '),2,' ') ||
           rpad(NVL(GL_COMPANY,' '),1,' ') ||
    rpad(NVL(GL_CURRENCY,' '),3,' ') ||
    rpad(NVL(GL_BAL_TYPE,' '),2,' ') ||
    rpad(NVL(GL_YEAR,' '),4,' ') ||
    rpad(NVL(GL_CODE,' '),14,' ') ||
    rpad(NVL(TRAN_ID,' '),14,' ') ||
    rpad(NVL(VALID_FLAG,' '),1,' ') ||
    LPAD(BROUGHT_FWD,18,'0') ||
          LPAD(ACTMTH1,18,'0') ||
          LPAD(ACTMTH2,18,'0') ||
          LPAD(ACTMTH3,18,'0') ||
          LPAD(ACTMTH4,18,'0') ||
          LPAD(ACTMTH5,18,'0') ||
          LPAD(ACTMTH6,18,'0') ||
          LPAD(ACTMTH7,18,'0') ||
          LPAD(ACTMTH8,18,'0') ||
          LPAD(ACTMTH9,18,'0') ||
          LPAD(ACTMTH10,18,'0') ||
          LPAD(ACTMTH11,18,'0') ||
          LPAD(ACTMTH12,18,'0') ||
    LPAD(CARRIED_FWD,18,'0') ||
    rpad(nvl(USER_PROFILE,' '),10,' ') ||
    rpad(nvl(JOB_NAME,' '),10,' ') ||
    TIMESTAMP
from TEST_EXPORT
/

Script to create the table
***************************

CREATE TABLE TEST_EXPORT (
  GL_PREFIX     VARCHAR2 (2)  NOT NULL,
  GL_COMPANY    VARCHAR2 (1)  NOT NULL,
  GL_CURRENCY   VARCHAR2 (3)  NOT NULL,
  GL_BAL_TYPE   VARCHAR2 (2),
  GL_YEAR       VARCHAR2 (4),
  GL_CODE       VARCHAR2 (14),
  TRAN_ID       VARCHAR2 (14),
  VALID_FLAG    VARCHAR2 (1),
  BROUGHT_FWD   VARCHAR2 (18),
  ACTMTH1       VARCHAR2 (18),
  ACTMTH2       VARCHAR2 (18),
  ACTMTH3       VARCHAR2 (18),
  ACTMTH4       VARCHAR2 (18),
  ACTMTH5       VARCHAR2 (18),
  ACTMTH6       VARCHAR2 (18),
  ACTMTH7       VARCHAR2 (18),
  ACTMTH8       VARCHAR2 (18),
  ACTMTH9       VARCHAR2 (18),
  ACTMTH10      VARCHAR2 (18),
  ACTMTH11      VARCHAR2 (18),
  ACTMTH12      VARCHAR2 (18),
  CARRIED_FWD   VARCHAR2 (18),
  USER_PROFILE  VARCHAR2 (10),
  JOB_NAME      VARCHAR2 (10),
  TIMESTAMP     VARCHAR2 (28))

Script to insert a few lines of data
*************************************INSERT INTO TEST_EXPORT (
GL_PREFIX, GL_COMPANY, GL_CURRENCY, GL_BAL_TYPE, GL_YEAR,
GL_CODE, TRAN_ID,
VALID_FLAG, BROUGHT_FWD, ACTMTH1, ACTMTH2, ACTMTH3, ACTMTH4,
ACTMTH5, ACTMTH6, ACTMTH7, ACTMTH8,
ACTMTH9, ACTMTH10, ACTMTH11, ACTMTH12, CARRIED_FWD,
USER_PROFILE, JOB_NAME,
TIMESTAMP ) VALUES (
'GE', '1', 'EUR', 'TY', '2000', '10AVCINC-GB1', '538', '5',
'0000000000000000 ', '0000000000000000 '
, '000000000000000 ', '000000000000000 ', '000000000000000 ',
'0000000000000000 '
, '000000000000000 ', '000000000000000 ', '000000000000000 ',
'000000000000000 ', '000000000000000 '
, '000000000000000 ', '000000000000000 ', '0000000000000000 ',
'REPORT', 'Trial Bal'
, '2000-08-31-10.13.59.000000');
INSERT INTO TEST_EXPORT ( GL_PREFIX, GL_COMPANY, GL_CURRENCY,
GL_BAL_TYPE, GL_YEAR, GL_CODE, TRAN_ID,
VALID_FLAG, BROUGHT_FWD, ACTMTH1, ACTMTH2, ACTMTH3, ACTMTH4,
ACTMTH5, ACTMTH6, ACTMTH7, ACTMTH8,
ACTMTH9, ACTMTH10, ACTMTH11, ACTMTH12, CARRIED_FWD,
USER_PROFILE, JOB_NAME,
TIMESTAMP ) VALUES (
'GE', '1', 'EUR', 'TY', '2000', '10CLMDC-GB1', '538', '5',
'0000000000000000 ', '0000000000000000 '
, '000000000000000 ', '000000000000000 ', '000000000000000 ',
'0000000000000000 '
, '000000000000000 ', '000000000000000 ', '000000000000000 ',
'000000000000000 ', '000000000000000 '
, '000000000000000 ', '000000000000000 ', '0000000000000000 ',
'REPORT', 'Trial Bal'
, '2000-08-31-10.13.59.000000');
INSERT INTO TEST_EXPORT ( GL_PREFIX, GL_COMPANY, GL_CURRENCY,
GL_BAL_TYPE, GL_YEAR, GL_CODE, TRAN_ID,
VALID_FLAG, BROUGHT_FWD, ACTMTH1, ACTMTH2, ACTMTH3, ACTMTH4,
ACTMTH5, ACTMTH6, ACTMTH7, ACTMTH8,
ACTMTH9, ACTMTH10, ACTMTH11, ACTMTH12, CARRIED_FWD,
USER_PROFILE, JOB_NAME,
TIMESTAMP ) VALUES (
'GE', '1', 'EUR', 'TY', '2000', '10CLMTS-GB1', '538', '5',
'0000000000000000 ', '0000000000000000 '
, '000000000000000 ', '000000000000000 ', '000000000000000 ',
'0000000000000000 '
, '000000000000000 ', '000000000000000 ', '000000000000000 ',
'000000000000000 ', '000000000000000 '
, '000000000000000 ', '000000000000000 ', '0000000000000000 ',
'REPORT', 'Trial Bal'
, '2000-08-31-10.13.59.000000');
INSERT INTO TEST_EXPORT ( GL_PREFIX, GL_COMPANY, GL_CURRENCY,
GL_BAL_TYPE, GL_YEAR, GL_CODE, TRAN_ID,
VALID_FLAG, BROUGHT_FWD, ACTMTH1, ACTMTH2, ACTMTH3, ACTMTH4,
ACTMTH5, ACTMTH6, ACTMTH7, ACTMTH8,
ACTMTH9, ACTMTH10, ACTMTH11, ACTMTH12, CARRIED_FWD,
USER_PROFILE, JOB_NAME,
TIMESTAMP ) VALUES (
'GE', '1', 'EUR', 'TY', '2000', '10LIFA1-GB1', '538', '5',
'0000000000000000 ', '0000000000000000 '
, '000000000000000 ', '000000000000000 ', '000000000000000 ',
'0000000000000000 '
, '000000000000000 ', '000000000000000 ', '000000000000000 ',
'000000000000000 ', '000000000000000 '
, '000000000000000 ', '000000000000000 ', '0000000000000000 ',
'REPORT', 'Trial Bal'
, '2000-08-31-10.13.59.000000');
commit;

Thanks for taking the time to look at this,

Shane Lakes.

      and we said...
To get rid of the @test and SQL> lines, you need to put the
spool command into the @test.sql file itself and use set termout
off.

To get rid of the blank line, you need to "set embedded on"

Here is an example that dumps the scott/tiger EMP table to a
flat file without any of that extra stuff:

Set pagesize 50000
set embedded on
set termout off
set heading off
set feedback off
set verfify off
spool &1
select rpad(ename,30)||to_char(empno,'9999')||to_char(hiredate)
from emp
/
spool off

Now, you would just run:

SQL> @test test.txt

to produce your spool file as you want it.

November 22, 2000 Alexandr -- Thanks for the question regarding
      "Updatable Views", version 8.1.5.0.0

      You Asked
Is it possible to create updatable view on more than one table?
And what is the rules for inserting and updating it.

      and we said...
see

http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c08schem.htm#19229

btw: via INSTEAD OF triggers -- ALL views can be made updatable.
 You just need to "program" them, to "train" them how to
insert/update/delete from the base tables.
November 22, 2000 Amitava -- Thanks for the question regarding
      "Repointing MsAccess application from Sybase to Oracle", version 8.1

      You Asked
In the existing application there are use of temporary tables
through procedure. Present application is pointing towards
sybase.
Following your instruction I tried this procedure:

create or replace procedure test604 as
Begin
execute immediate
'create global temporary table test604a on commit delete rows as

(select
trbn7,cust_name,d.icn,req_num,po_num,ci,d.ln_num,ml,d.drwg
line_drwg,
b.drwg parent_drwg,sub_drwg,d.descr,b.descr
parent_descr,sub_descr,
orig_src_cd,sent_cd,to_char(d_rqsdt,' || 'yyyymmdd' || ')
d_rqsdt,d_shp_stat,d_rel_stat,
'Plan Ship' msg,d.qty,b.qty qty_reqd,b.qty plan_qty,'   '
short_ln,
to_char(d_plsdt,'yyyymmdd') d_plsdt,to_char(d_plsdt,'yyyymmdd')
stadt,
to_char(d_reldt,'yyyymmdd') d_reldt,to_char(d_shpdt,'yyyymmdd')
d_shpdt,carrier,airbill,
prefix,shortage_text,pseudo_ln from  beam.ordhdr@beam97 h,
beam.orddtl@beam97 d,
beam.sbomline@beam97 b where h.icn=d.icn and d.icn=b.icn(+) and
substr(d.ln_num,1,3)=substr(b.ln_num(+),1,3)and h.business =
'STM' and
h.order_type = 'UNI'   and h.icn = '290T513')';
end;

But it gives an error:
7/38     PLS-00103: Encountered the symbol "YYYYMMDD" when
expecting one
         of the following:
         . ( * @ % & = - + ; < / > in mod not rem an exponent
(**)
         <> or != or ~= >= <= <> and or like between into using
         is null is not || is dangling
Can you please suggest me what to do now.

      and we said...
My direction would not be to use "create global temporary table"
in a stored procedure but rather to have the table ALREADY
created and just insert into it.  I would not create the table
in the procedure unless there was some truely compelling reason
otherwise.

In any case, the solution for you is easy.  In a character
string, in order to embed a quote in a string you must double up
the quotes.

stadt,
to_char(d_reldt,''yyyymmdd'') d_reldt,
to_char(d_shpdt,''yyyymmdd'') d_shpdt,carrier,airbill,


Subject | Article | Last Updated (East coast time)
Standby database et prod Oracle 7.3.4 on some NT4 machine. | article only | Nov 27, 2000 12:36 pm
Standby database | article only | Nov 27, 2000 12:39 pm
How to display ORDIMAGE in Web Page | article only | Nov 27, 2000 12:40 pm
ORA-02291: integrity constraint (.) violated | article only | Nov 27, 2000 12:45 pm
CREATE USER within stored procedure | article only | Nov 27, 2000 12:48 pm
Time Difference | article only | Nov 27, 2000 12:56 pm
Failover strategy using Standby DB | article only | Nov 27, 2000 01:06 pm
shared pool SQL blocks | article only | Nov 27, 2000 01:11 pm
rownum | article only | Nov 27, 2000 01:38 pm
RBS and SQL*Loader | article only | Nov 27, 2000 01:59 pm
SQL*Loader and RBS -- reviewed | article only | Nov 28, 2000 07:26 am
Using the 'Timestamp' function from Nov 2000. | article only | Nov 28, 2000 07:30 am
sort passes | article only | Nov 28, 2000 07:48 am
Flush shared pool | article only | Nov 28, 2000 09:45 am
How to find the number of rows users select from certain tables | article only | Nov 28, 2000 09:48 am
How do you call "alter index ..." from PLSQL? | article only | Nov 28, 2000 10:13 am
v$sqlarea | article only | Nov 28, 2000 10:17 am
autotrace | article only | Nov 28, 2000 10:30 am
SQL*Loader, Resource Manager, Locally Manager TS's | article only | Nov 28, 2000 01:24 pm
connection load balancing | article only | Nov 28, 2000 01:27 pm
Is it possible to convert the global index into a local index using rebuild online. | article only | Nov 29, 2000 09:30 am
GETTING A RESULT SET WITHOUT USING ORACLETYPES.CURSOR article | article only | Nov 29, 2000 02:28 pm
Parallel DML/DDL/Query | article only | Nov 29, 2000 02:40 pm
Page breaking via PL/SQL htp.commands or PDF | article only | Nov 29, 2000 05:09 pm
process | article only | Nov 29, 2000 05:17 pm
V$SESSION_LONGOPS | article only | Nov 29, 2000 05:32 pm
WebDB Login user id | article only | Nov 29, 2000 05:36 pm
Seeing one screen at a time | article only | Nov 29, 2000 05:37 pm
FORALL / TYPE ... IS TABLE OF | article only | Nov 29, 2000 05:48 pm
Export -- calling from PLSQL | article only | Nov 29, 2000 07:11 pm
rman cold backup | article only | Nov 30, 2000 08:26 am
Installing PL/SQL Toolkit in different tablespace | article only | Nov 30, 2000 08:40 am
Retrieve duplicate values of a field in a table...... | article only | Nov 30, 2000 08:51 am
v$lock | article only | Nov 30, 2000 09:12 am
Mutating Trigger | article only | Nov 30, 2000 10:00 am
Hints | article only | Nov 30, 2000 10:07 am
Tuning process while applying Equi Join !! | article only | Nov 30, 2000 10:20 am
Using copy in OEM. | article only | Nov 30, 2000 11:36 am
Personal Oracle 8i on Windows ME | article only | Dec 01, 2000 08:57 am
v$sort_segment and v$sort_usage | article only | Dec 01, 2000 09:03 am
Indexes size | article only | Dec 01, 2000 10:38 am
local managed temp tablespace | article only | Dec 01, 2000 10:42 am
maxdatafiles ect . setting in controlfile | article only | Dec 01, 2000 11:14 am
No data in All_Triggers table | article only | Dec 01, 2000 12:30 pm
primary key | article only | Dec 01, 2000 12:42 pm
Is there any command to Unlock a table ! | article only | Dec 01, 2000 12:50 pm
passing array to stored procedure from java | article only | Dec 01, 2000 01:41 pm
row(s) 1 - 47 of 47
November 27, 2000 Nush -- Thanks for the question regarding "Standby database et prod Oracle 7.3.4 on some NT4 machine.", version Oracle 7.3.4
You Asked
Hello!
How can I do with Oracle 7.3.4 a standby on some prod. NT4
machine(instance,service name?), and how can apply the redo logs
automatically on NT4.
Thanks a lot!
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:199412348073
for howto do a standby database on 7.3
November 27, 2000 marc -- Thanks for the question regarding "Standby database", version 7.3.4
You Asked
Hi Tom,
Would it be possible to create a standby database on a NT server
(8.1.6) with a master database (7.3.4) on a Unix machine ?
Thanks for your help
Marc
and we said...
No, not at all.

the physical servers must be running the same exact OS at the
same exact release level.

Going from Unix to NT (or vice versa) is not possible.
November 27, 2000 Kelvin -- Thanks for the question regarding "How to display ORDIMAGE in Web Page", version v4.0.8.1
You Asked
Dear Tom,

I have some image store in the ORDIMAGE format, and now using
the Forms 6i to view the image. How can I display the stored
ORDIMAGE in the Web throught the Oracle Application Server
v4.0.8. The database version is 8.1.6

Thanks
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:232814159006
for one method.
November 27, 2000 David -- Thanks for the question regarding " ORA-02291: integrity constraint (.) violated", version Oracle 7.3
You Asked
Does this completely stop the program when an error is
encountered, or does it skip the record that caused the error
and go on and process the rest?

It would make sense to print a more specific error message as to
which record is in error, and continue to process the rest of
them. Is this possible? Thanks!
and we said...
It depends on the program -- That error is returned to the
"thing doing the insert/update/delete".  It is upto that "thing"
to decide what to do.

If for example, this was SQLLDR -- our data loading tool -- we
would continue processing more input records.  This "bad" record
would goto the bad file and we would keep on loading (until we
hit the max number of errors which you can specify on the
command line).

So -- it is totally upto the program itself to decide what to do
when it encounters an error.  Some will stop -- some will keep
on going.

If this is in reference to an Oracle utility -- feel free to
follow up with another question with more details (eg: the name
of the program and the conditions under which this occurs)
November 27, 2000 Ingo -- Thanks for the question regarding "CREATE USER within stored procedure", version 8.1.6
You Asked
Is there a way to create a new database user (or alter one for
that matter) within a stored procedure or a package?

Ingo
and we said...
Sure, you use dynamic SQL to do this.

In Oracle8i, release 8.1 and up -- it is as easy as:

  ...
  execute immediate 'create user newuser identified by x';
  ...

In Oracle8.0 and before -- you would use DBMS_SQL.  Don't forget
-- with the execption of invokers rights routines (also new with
8i -- see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:961430030094
for some info on them) PLSQL stored procedures execute with
the base privs of the definer (owner) of the routine meaning
that ROLES are not enabled.  See
http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
for more info on that.
November 27, 2000 Rajesh -- Thanks for the question regarding "Time Difference", version 8i
You Asked
1. I need to find the difference between two given times in
minutes and seconds. Is there any built in function for that or
is there any other way? Kindly let me know about it.

2. Is there any way to find out that if insertion into the
database fails? In SQL Server there is a facility to findout.
Kindly let me know about this as well.
and we said...
for #1 see
http://osi.oracle.com/~tkyte/Misc/DateDiff.html
It is as simple as doing arithmetic.  You just subtrace.

For #2, you would simply check the return code or catch the
exception.  For example, in PLSQL I would code:

  begin
      insert into t values ( c1,c2 );
  exception
      when DUP_VAL_ON_INDEX then
           ...
      when NO_DATA_FOUND then
           ....
      when .....
      when OTHERS then
           ....
           dbms_output.put_line( sqlerrm ); -- print out errmsg
           RAISE;
  end;

In Pro*C, I might code:

   exec sql whenever sqlerror do error_routine();
   exec sql insert into T values ( c1, c2 );

(and my function error_routine() would get called and would have
access to the sqlca to find the error code/message).

And so on (similar mechanisms for java, vb, perl, etc etc etc)

How to do it in your language will vary, would need to know what
language you use.
November 27, 2000 Reji -- Thanks for the question regarding "Failover strategy using Standby DB", version 8.1.6
You Asked
Tom:
    We are planning to use Oracle Standby DB concept for
    the DB failover?  My qn is: How can I make this switch
    a client transparent?  Or When the standby DB takes over
    how does the client know how to switch to the standby DB?
    I think all the existing connections to the Main DB will
    fail but then without code change how can I make sure
    the client can connect to the standby DB.

    Please provide most of the commonly used approaches so that
    we can pick one is suitable for the env.

    -Thx
    -Reji
and we said...
You would use the connect time failover configuration in your
tnsnames.ora file:

failover.us.oracle.com=
 (description=
   (failover=on)
     (address=(protocol=tcp)(host=HOST1)(port=1521))
     (address=(protocol=tcp)(host=HOST2)(port=1521))
     (connect_data=(sid=tkyte816))
 )

See the network admin guide for all of the options related to
this.  Basically -- it says "if HOST1 isn't available, try HOST2
before giving up".
November 27, 2000 rob -- Thanks for the question regarding "shared pool SQL blocks", version 8.1.5
You Asked
Tom,

Can 'parts' of SQL statements be stored in the shared pool so
they do not need re-parsing?  For example, I have a script like:

SELECT UNIQUE(colA||colB) FROM tblX
MINUS
SELECT UNIQUE(colA||colB) FROM tblY;

This script will run numerous times with differeing values for
tblX, but always going against the same base table tblY.  I want
to know if there is a way that the portion of the script before
the MINUS can be saved in the shared pool since it is
redundantly executed.

More generally... how can I see if a given SQL block has
remained in the shared pool (and will be utilized for a
subsequent query) once it's been parsed and executed?

Thanks,
Rob S.
and we said...
A statement is what goes into the shared pool -- not a "piece"
of it.

In the above -- the entire statement is the statement -- not
bits and pieces of them.  They are not parsed and optimized
separately but rather as a whole.  If you change the identifiers
in a query (eg: the tablename) then it is a totally different
query -- the entire statement is different, not just a piece of
it.

To see what is in the shared pool sql statement wise -- simply
query against the view v$sql_area
November 27, 2000 GAURANG -- Thanks for the question regarding "rownum", version 8.1.5
You Asked
hi tom.

is rownum is function?

is rownum display physical location of row or
it display the order in which the row derived from database.

thanks
and we said...
Rownum is a "psuedo column", not a function.

From the sql reference:

...
For each row returned by a query, the ROWNUM pseudocolumn returns a number
indicating the order in which Oracle selects the row from a table or set of
joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so
on.
....

it has nothing to do with the physcal location of a row.

It is the order in which the row was selected by a given query plan (eg: given
the same query -- the rownums assigned to rows may very well be different using
the rule based optimizer then the cost based)
November 27, 2000 Andre -- Thanks for the question regarding "RBS and SQL*Loader", version 8.1.6
You Asked
Hi Tom,

I just came across a problem in which I ran out of rollback
space  because of a load. I found out an implicit delete --
because of the REPLACE clause -- caused it. I just changed the
caluse to TRUNCATE and the result was ok. What are the
implications of using REPLACE or TRUNCATE ? Is there any way to
set my load to use a larger batch-ready rollback segment ?

Thanks !
and we said...
In general, you want to use TRUNCATE and not replace.  As you
have discovered, replace uses delete which can take a long time
if you have lots of data and can consume lots of rollback.  We
have replace and truncate for privilege reasons (you need less
privs to delete, you need more for truncate) and because not
every object can be truncated (parent tables in a foreign key
relation for example).

Use truncate.  There is no method to assign sqlldr to a specific
rollback segment.  Since loader commits frequently -- with the
exception of the initial "replace", it needs very little total
rollback
November 28, 2000 Andre -- Thanks for the question regarding "SQL*Loader and RBS -- reviewed", version 8.1.6
You Asked
Hi Tom, (this is an improvement on a previous question, sorry.
My web page was locked when trying to correct it.)

I just came across a problem in which I ran out of rollback
space  because of a load. I found out an implicit delete --
because of the REPLACE clause -- caused it. I just changed the
caluse to TRUNCATE and the result was ok.

-What are the implications of using REPLACE or TRUNCATE ?

-Does the REPLACE make Oracle delete the entire table in one
only transaction before the load ?

-Why would someone prefer REPLACE to TRUNCATE, then ?

-Is there any way to set my load to use a larger batch-ready
rollback segment ?

-Is setting ROWS=n the only way to control rollback usage in a
load ?

Thanks !
and we said...
Replace does a DELETE which will generate tons of rollback if
there is tons of existing data.  TRUNCATE does a TRUNCATE which
uses significantly less rollback (just enough to record the
changes to the data dictionary).  The implication of using
replace is that it will do a DELETE FROM and generate redo and
rollback.  The implication of using TRUNCATE is that it will
not.  You need more privilges to use truncate on other peoples
tables and you cannot truncate a parent table in a foreign key
relationship so you MAY not be able to use truncate (but could
use delete).  Both are available for flexibility.

Yes, REPLACE makes us DELETE FROM T in one big transaction.

Someone would prefer REPLACE to TRUNCATE if they were able to
DELETE FROM T but not TRUNCATE TABLE T.

There is no way to set a rollback segment for a SQLLDR session.
As SQLLDR commits frequently, it in general does not generate
lots of continous rollback (the size of the rollback segments
may be very small).  It is only when using REPLACE that you
might have an issue -- with that initial delete.  If that delete
is so large it would blow out your rollback segments, you want
to make sure you can use TRUNCATE anyway.

Using TRUNCATE instead of replace is the major way to reduce
total rollback needed for a load.  ROWS=N will marginally affect
the rollback generated as sqlldr commits pretty freqently.
Using a larger value for N will increase performance and
marginally increase the need for rollback (but as soon as we
commit we no longer need that rollback and since we use them in
a circular fashion, the total rollback space needed by a load a
very small -- especially when using truncate as opposed to
replace on a table with lots of existing data)
November 28, 2000 Stuart -- Thanks for the question regarding "Using the 'Timestamp' function from Nov 2000.", version 8.1.6.0.0
You Asked
The timestamp and number(17) format instead of dates is nice and
works well. But, how can this user function be used:
  as a default for a column (replacing sysdate)? or
  as a function value to sqlLoader (replacing sysdate)?
Thanks,
Stuart
and we said...
You cannot use the function as a default but rather you would
use a trigger to "default" it in much the same way you would use
a trigger to supply a column with a SEQUENCE.  For example:

create or replace trigger T before insert on T for each row
begin
  if ( :new.column is null ) then
      :new.column := function_call;
  end if;
end;

In SQLLDR, you can call SQL functions simply by including them
in the control file.  For example:

LOAD DATA
INTO TABLE DEPT
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(DEPTNO,
  DNAME,
    LOC,
 TIMESTAMP "function_call"
)
November 28, 2000 Shviaswamy -- Thanks for the question regarding "sort passes", version 8.1.6.0.0
You Asked
Hi Tom.
Could I find out how many sort passes(merges) it is going to
take for a given query in advance, without executing the query.
May be from Explain plan.? If so, how?  I am referring to disk
sort. This is to find out the best query from the view point of
sorting.

Shivaswamy
and we said...
You cannot find out how many disk sorts will take place for a
given query without actually running the query as this is a
function purely of the amount of data returned by the query and
the size of the sort_area_size.

You can see how many SORTS will take place via the explain plan.
 How many of those will be disk sorts vs in memory sorts can
only be determined by running the query with some inputs.  You
will find that for one set of inputs -- the query may do 0 disk
based sorts while for a different set of inputs the query does N
disk based sorts.
November 28, 2000 Wendy -- Thanks for the question regarding "Flush shared pool", version version 7.3.4
You Asked
Dear Tom:
I have question regarding shared pool:
If I issue this command: Execute
dbms_shared_pool.Keep('package1','P'), then another DBA issue:
Alter system flush shared pool, what would happen to package1?
I have another question is how do I display Long column?

Thanks a lot

Wendy
and we said...
The answer to the keep question is the package would still be
there.  That is the function of keep  -- to make sure the code
stays there.  Here is an example demonstrating this:

kyte@ORA734.US.ORACLE.COM> create or replace
  2  procedure toms_procedure
  3  as
  4  begin
  5      null;
  6  end;
  7  /

Procedure created.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> exec sys.dbms_shared_pool.keep( user
|| '.TOMS_PROCEDURE' );

PL/SQL procedure successfully completed.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> select owner, name, kept
  2    from v$db_object_cache
  3   where owner = user
  4     and name = 'TOMS_PROCEDURE';

OWNER    NAME            KEP
-------- --------------- ---
TKYTE    TOMS_PROCEDURE  YES

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> alter system flush shared_pool
  2  /

System altered.

tkyte@ORA734.US.ORACLE.COM>
tkyte@ORA734.US.ORACLE.COM> select owner, name, kept
  2    from v$db_object_cache
  3   where owner = user
  4     and name = 'TOMS_PROCEDURE';

OWNER    NAME            KEP
-------- --------------- ---
TKYTE    TOMS_PROCEDURE  YES

As for how to display a long column, in SQLPlus you use the the
SET LONG directive to specify how much of a long to display.
for example:

tkyte@ORA734.US.ORACLE.COM> set long 1
tkyte@ORA734.US.ORACLE.COM> select text from all_views where
rownum = 1;

T
-
s

tkyte@ORA734.US.ORACLE.COM> set long 10
tkyte@ORA734.US.ORACLE.COM> select text from all_views where
rownum = 1;

TEXT
----------
select
u.n

tkyte@ORA734.US.ORACLE.COM> set long 30
tkyte@ORA734.US.ORACLE.COM> select text from all_views where
rownum = 1;

TEXT
------------------------------
select
u.name, /* OWNER */
nvl

tkyte@ORA734.US.ORACLE.COM>
November 28, 2000 Graham -- Thanks for the question regarding "How to find the number of rows users select from certain tables", version 8.1.6
You Asked
Can you tell me how to monitor the number of rows each user
selects from certain tables, broken up by userid and table?

The users may access the tables by Excel, Oracle forms, MS
access, Oracle Discoverer.

thanks
and we said...
There is no feasible way to do this.

If you enabled database tracing via setting SQL_TRACE=TRUE in
the init.ora file for your database, each and every session will
generate a large, very large, trace file.  This trace file will
have every single query they execute or is executed for them
(recursive SQL) as well as the query plans and number of rows
fetched by the client (or updated or inserted and so on).

This will TRUELY slow your database way down -- excessively.  It
will also tend to fill up your file system rapidly.

This is not something that is feasible to obtain.
November 28, 2000 Carlos -- Thanks for the question regarding "How do you call "alter index ..." from PLSQL?", version RDBMS 8.1.6, OAS 4.0.8
You Asked
Hi Tom-

I have a web (PLSQL cartridge) text-search app using interMedia.
 I need to rebuild the intermedia text index on the bfile column
of the mydocs table that contains the file references every time
I create a new document and insert into the table.

(1) Why doesn't the text index pick this up without having to
rebuild it?

(2) How can I call "alter index rebuild" (i.e. a non-DML
statement) from my PLSQL procedure?

Thanks Tom!
and we said...
(1) it would if you run the ctxsrv process on the database
server.  that enabled automatic index maintenance.  See
http://technet.oracle.com/doc/oracle8i_816/inter.816/a77063/cdefaul6.htm#1000930
for details on this in the "Index Maintenance" section.

(2) you can issue DDL in Oracle8i via the "execute immediate"
directive with dynamic sql.  for example

   ...
   execute immediate 'alter index t rebuild';
   ....

Remember that ROLES are not enabled in a stored procedure (see
http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
for more info) and if you get insufficient privs that means you
probably have the ability to rebuild that index via a role.

You really don't want to REBUILD the index -- hopefully you are
using SYNC as -- but rather SYNC it.  This can be done via an
alter index but in PLSQL it would be easier to call:

   ctx_ddl.sync_index( idx_name );
November 28, 2000 -- Thanks for the question regarding "v$sqlarea", version 8.1.6
You Asked
Tom:

can you tell me what's different between executions and
users_executing in v$sqlarea?
i found a sqltext which have 6,300,000 executions but
0 for users_executing, can you explain to me what's
that mean?
and we said...
From the Server Reference:

EXECUTIONS
The total number of executions, totalled over all the children

USERS_EXECUTING
The total number of users executing the statement over all
children

Your numbers indicate the query was executed in the past 6.3
million times and there are NO users executing it right now.
November 28, 2000 wallacel -- Thanks for the question regarding "autotrace", version 8.1.6
You Asked
Tom:

i set autotrace on at sqlplus.
then i create table test ( a int);
insert into test values(10);

select * from test;

  A
----------
        10

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   TABLE ACCESS (FULL) OF 'TEST'

Statistics
----------------------------------------------------------
          0  recursive calls
          4  db block gets
          1  consistent gets
          0  physical reads
          0  redo size
        360  bytes sent via SQL*Net to client
        424  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          1  rows processed

why 4 db block gets and 1 consistent gets?
the table test occupy 8 blocks, (db block size is 8k).
and we said...
The DB BLOCK GETS are blocks we got in order to process your
query in the first place.  It represents some of the work we did
to make this query "go".

The 1 consistent get represents us reading your actual data.
Even though the table has 8 blocks -- we only ever full scan
upto the high water mark.  In this case, the HWM of the table is
1 block.  If you re-run this test by dropping and recreating the
table and NOT inserting a row -- you'll see that consistent gets
= 0.  the HWM of that table is zero blocks.
November 28, 2000 Andre -- Thanks for the question regarding "SQL*Loader, Resource Manager, Locally Manager TS's", version 8.1.6
You Asked
Hi Tom !!!

A bunch of questions. I hope you don't mind... (If you can shed
some light on them, I'll be very glad. I bet the answers are on
the tip of your tongue)

- What is the use of the FILLER keyword in a SQL*Loader ctl ?

- In Resource Manager, how does muti-level CPU usage work
(emphasis method) ? It's not clear whatsoever in the on-line
books. It is said that when one level is "unable" to use the
resources of one level, then the next level is utilized.

- What's the actual difference between the V$TEMP_EXTENT_MAP and
the V$TEMP_EXTENT_POOL views, regarding locally managed
temporary TS's ?

- Using the MIGRATION utility, what is the use of the MULTIPLIER
parameter ? I know it is used to size the new 8i index, but how
it is done ?

- Is there any "reasonable" explanation why the
QUERY_REWRITE_ENABLED parameter should be set to true in order
to use function-based indexes ?

- I understand dimensions help query rewrites. But how can
constraints be used for query rewrites ?

- I've read about one limitation of stored outlines. You can use
plans created by the CBO and manipulate them -- especially
transporting them. But you cannot "create" your own plan. That
would be a deficiency of this new feature. Is this approach
correct ?

- In version 8.1.6 Oracle discourages the use of the
JAVAUSERPRIV, JAVASYSPRIV and JAVADEBUGPRIV roles, and
encourages the use of direct privileges. Why is that ? These
role make sense to me and enable a considerable amount of
control over the Java resources. How can I grant these isolated
privileges explicitly ?

- I've read there are server-side JDBC drivers in order to
translate the java source code previously published to PL/SQL,
in sort of a "recursive" way. That is, the JVM must communicate
with the SQL engine trhough this "internal" driver. Is that
correct ?

Thanks for your attention and patience.

Warmest regards from sunny Rio de Janeiro, Brazil !
and we said...
o the filler keyword is to map fields that appear in the raw
INPUT field to a non-database field.  One of its primary uses is
to skip fields in a delimited file (if you want to load fields
1, 3 and 5 skipping over 2 and 4 for example).  See
http://osi.oracle.com/~tkyte/SkipCols/index.html
for more info.

o the meaning of "one level is unable to use the resources" is
more simply "when one level is not requesting those resources,
they will be given to the lower levels".

If a consumer-group does not use its CPU-percentage, the
remainder falls through to the next level.

This is superior to a single level plan whereby I would allocate
X% of the CPU to a given group and that is all they would get,
regardless of the usage by other users (even if there was plenty
of leftover resources -- you would not get them).  A multi-level
plan allows resources to be fully utilized whenever possible.

o for the meaning of v$temp_extent_* views:

V$TEMP_EXTENT_MAP
Information for all extents in all locally managed temporary
tablespaces.

V$TEMP_EXTENT_POOL
For locally managed temporary tablespaces: the state of
temporary space cached and used for by each instance

one is a map of the extents, the other shows cache information.
The number of rows in these views should be different typically
as the cached information comes and goes.

o The MULTIPLIER option specifies the initial size of the
Oracle8 i_file#_block# index relative to the Oracle7
i_file#_block# index.  For example,  MULTIPLIER=30 triples the
initial size when the index is created, where no MULTIPLIER
specified, by default, uses the i_file#_block# value of 15,
creating an index for Oracle8 that is 1.5 time larger than the
Oracle7 i_file#_block# index.

o QUERY_REWRITE_ENABLED is what tells us to "trust" other
information.  We use it with materialized views for example to
trust that if we rewrite the query to use a summary table -- the
data in the summary table is Ok and current - it'll get the same
answer.

With function based indexes -- the same thing is true.  You are
explicitly telling us to "trust" that your function is
deterministic, that it does the right thing.  It is a protection
feature -- you must physically enable this feature, you must be
sure you want to use it.

You could for example write a function "random" to return a
random number.  You could create an index a table with this
random() function.  You could then run a query:

select random from T where random = 5;

RANDOM
---------
10000

That happens because random is not deterministic, the answer is
"apparently" wrong but it is in fact correct because at the time
the index entry was made on that row, random returned 5.  This
time it returned 10000.

o See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76994/qr.htm#35006
for when primary key, foreign key, not null constraints are
needed for query rewrite with MV's.

(quote)
....
To determine this, the optimizer may depend on some of the data
relationships declared by the user via constraints and
dimensions. Such data relationships include hierarchies,
referential integrity, and uniqueness of key data, and so on.
....

o It is true you cannot by hand CREATE your own plan.  I do not
myself view this as a deficiency as many of the generated plans
for non trivial queries have dozens, if not hundreds, of pieces
to them (eg: its really HARD to write the plan).

What you do with Query Plan Stability is to stabalize plans to
protect from different plans upon an upgrade or when you just
plain don't want them to change.  They are a mechanism to
"freeze" the existing plan, not to tell the optimizer how to do
the query.  that is what HINTS are for (and you can use hints to
generate the plan you want and "freeze" that plan).

o the JAVAUSERPRIV, JAVASYSPRIV roles are alot like RESOURCE and
DBA -- very broad, very easy to use but they convery SOOOOO much
power.

The new privelege model follows that used by Java and is much
more granular.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:952229840241
for an example using it.

o I don't fully follow this question.  There is a server side
jdbc driver, the kprb driver.  You can read about it at:
http://technet.oracle.com/doc/oracle8i_816/java.816/a81354/advanc4.htm#1001042
it is an optimized jdbc driver that resides in the database for
interacting with the database.
November 28, 2000 -- Thanks for the question regarding "connection load balancing", version 8.1.5
You Asked
Tom:

connection load balancing is only useful under
parallel server environment,
at NON-parallel-server environment, we don't need to config
connection load balancing, am i right?
and we said...
<quote network admin guide>

Connection load balancing improves connection performance by
balancing the number of active connections among multiple
dispatchers. In an Oracle Parallel Server environment,
connection load balancing also has the capability to balance the
number of active connections among multiple instances.

</quote>

So, in an MTS setup (multi-threaded server) connection load
balancing may be relevant as well.
November 29, 2000 Ravi -- Thanks for the question regarding "Is it possible to convert the global index into a local index using rebuild online.", version 815
You Asked
Tom,

I have a  production database, which I cannot bring it down for
some more days. But we would like to convert the global index on
one table to a local index. The primary key constriant is
implemented through the gloabl index. So, I cannot drop and
recreate the index.

Is it possible to convert the global index into local index
using rebuild online option of the alter index command.  Could
you please suggest me a best solution to create the local index
from the global index online.

Thanks in advance.

Regards
Ravi

I am sorry to say that the problem is redefined to me now. There
is a table partiotioned by range value of months. There is no
primary key in the table. It is a huge table. There are some
local indexes in addition to a non partitoned index.

My task is explore the option of coverting the non-partitioned
index into a local partioned index without shutting down the
database. Please give your suggestion.

Regards
Ravi
and we said...
You do not have to shut down the database in order to build an
index however you cannot rebuld a global index into a local
index with an online rebuild.  You can drop the global index and
then build the local index "online"

create index t_idx on partitioned(x,y,z) local online
/
November 29, 2000 Jim -- Thanks for the question regarding "GETTING A RESULT SET WITHOUT USING ORACLETYPES.CURSOR article", version db 8.0.5
You Asked
In the November/December 2000 issue of Oracle, you had an
article "GETTING A RESULT SET WITHOUT USING ORACLETYPES.CURSOR"
which has inspired two questions:

1) I have long wanted to perform this functionality but did not
know how to implement.  The article was very inspiring.  However
I ran into difficulty when trying to create a nested VARRAY
within the table type definition (PLS-00534).  It is possible to
create a table but not a table type with a nested VARRAY?  The
return declaration requires a type in your example, is there an
alternative mechanism so that I can utilize nested VARRAY?
2) I have created a stored fuction similiar to demo_proc2 in the
article.  It works fine for small result sets.  However, when
the result set contains ~4096 rows no data is returned?  I don't
believe there is a problem within the stored function.  Do you
have suggestion where problem could be?
and we said...
1) if you mean you wanted an array of array's -- that is not
possible with Oracle Object Types or PLSQL types.  You can have
only arrays of scalars -- never arrays of other array types.

2) I would need an example, something like this:

tkyte@ORA806.WORLD> create or replace type myTableType as table
of number;
  2  /

Type created.

tkyte@ORA806.WORLD>
tkyte@ORA806.WORLD> create or replace function result_set( p_x
in number ) return myTabletype
  2  is
  3      l_x    myTableType := myTabletype();
  4  begin
  5
  6      for i in 1 .. p_x loop
  7          l_x.extend;
  8          l_x(l_x.count) := i;
  9      end loop;
 10
 11      return l_x;
 12  end;
 13  /

Function created.

tkyte@ORA806.WORLD> select count( a.column_value ),
  2         min(a.column_value),
  3         max(a.column_value)
  4    from THE ( select cast( result_set( 15000 ) as
mytableType )
  5                 from dual ) a
  6  /

COUNT(A.COLUMN_VALUE) MIN(A.COLUMN_VALUE) MAX(A.COLUMN_VALUE)
--------------------- ------------------- -------------------
                15000                   1               15000

tkyte@ORA806.WORLD> select count( a.column_value ),
  2         min(a.column_value),
  3         max(a.column_value)
  4    from THE ( select cast( result_set( 4096 ) as mytableType
)
  5                 from dual ) a
  6  /

COUNT(A.COLUMN_VALUE) MIN(A.COLUMN_VALUE) MAX(A.COLUMN_VALUE)
--------------------- ------------------- -------------------
                 4096                   1                4096

tkyte@ORA806.WORLD>

that shows >4096 seems to be OK.
November 29, 2000 Andre -- Thanks for the question regarding "Parallel DML/DDL/Query", version 8.1.6
You Asked
Hi Tom,

Regarding parallel DML/DDL/Query, what is the precedence order
of these ?

- ALTER SESSION FORCE PARALLEL n
- CREATE TABLE parallel_clause
- parallel hint

Thanks !
and we said...
the hint is the lowest -- hints are hints and are easily
ignored.

the alter session force will override the parallelism specified
in the create table statement.
November 29, 2000 Mike -- Thanks for the question regarding "Page breaking via PL/SQL htp.commands or PDF", version 7.2.3
You Asked
Is there a way to have PL/SQL force page breaks when creating
web reports using HTP Commands?

Is there a way to table a report and then create a PDF File
through PL/SQL?
and we said...
HTML has no concept of a "page break", there are no such things
in HTML.  So, no, there is no way for HTP.<anything> to cause a
page break since the browser doesn't support such a concept.

You cannot create a pdf file via plsql (unless of course you
taught yourself how to write PDF from scratch which would be
quite difficult).  Oracle Reports however can generate pdf files
easily.
November 29, 2000 -- Thanks for the question regarding "process", version 8.1.6
You Asked
Tom:

when oracle define processes, it says that this parameter
determines the maximum number of operating system processes that

can be connected to oracle concurrently. the values of this
parameter must include 5 for the background process and I FOR
EACH USER PROCESS. for example, if you plan to have 50
concurrent users, set this parameter to at least 55.

I think this is true for dedicate server, but for MTS,
1 FOR EACH USER PROCESS  is not true, am i right?
and we said...
It is still 1 for each user process in MTS however in MTS a user
process is shared by many users.

When using dedicated server mode this should be 5 + number of
sessions.

Using MTS, this should be 5 + dispatchers + shared servers
roughly.
November 29, 2000 -- Thanks for the question regarding "V$SESSION_LONGOPS", version 8.1.6
You Asked
Tom:

when i query v$session_longops, i got the following result:

select username ,sid,serial# from v$session_longops;
SYS              12          1
John             28        438
HP_DBSPI         42         39
HP_DBSPI         42         39
HP_DBSPI         40         74

what should i do if i want to kill john's longops?
Alter system kill session '28,438';
ERROR at line 1:
ORA-00030: User session ID does not exist.

when i query v$session,
select username,sid,serial# from v$session where sid=28;
USERNAME                              SID    SERIAL#
------------------------------ ---------- ----------
mike                                   28       3762

and select count(0) from v$session where username='HP_DBSPI'
return 0.
seems it is totally irrelevant between this v$session and
v$session_longops.
and we said...
data in v$session_longops hangs out until those slots are needed for reuse.  You
should approach v$session_longops with specific sid,serial#'s -- you do not
query the table by itself.  You can join this to v$session or whatnot.

You should ignore rows in there that are not for current sessions.  You cannot
clear them.
November 29, 2000 Louise -- Thanks for the question regarding "WebDB Login user id", version 2.2.5
You Asked
After a user logined in to WebDB, where can I get its login user
id so I can pass it to some application forms.

Thanks Tom.
and we said...
the plsql function call:

owa_util.get_cgi_env( 'REMOTE_USER' )

will return that value.
November 29, 2000 George K. -- Thanks for the question regarding "Seeing one screen at a time", version 3.3.4.0.1
You Asked
I came across that problem when using the help command as well
as when the number of selected records was too large to fit in a
screen. Could you please advice me on how I can make SQL show
only one screen at a time and then by presing a button to move
on to the next page? ( Something like the more command on Unix).
I look forward to hearing from you soon.
Thanks in advance.
and we said...
SQL> set pagesize 20
SQL> set pause on

To get a screen full of data -- you will hit ENTER.  Be careful
-- even to get the FIRST screen you must hit enter.  So, after
entering a query like:

SQL> select * from emp;

make sure to hit enter 2 times!
November 29, 2000 Ron -- Thanks for the question regarding "FORALL / TYPE ... IS TABLE OF ", version 8.1.6
You Asked
The 'forall' stmt seems like a good efficiency tool for bulk
maintenance.  But how should the related arrays (TYPE ... IS
TABLE OF) be managed?  If the arrays gets too large won't they
be paged out by Oracle or the OS and all the efficiency lost to
IO?

I can run the foralls every X rows and reuse the arrays.
Frequent reuse will probably keep them in memory, but where is
the point of diminishing or negative returns?

Thank You
Ron Plank
and we said...
Yes, if you put a billion things in the table -- you'll
eventually start swapping the memory at the OS level.

The point of diminishing returns can only be evaluated given
your situation.  How much ram do you have and how many users and
how much ram does each user need -- that'll dictate how much ram
each user should use at most.

Hundreds, upto thousands, of entries in these arrays is not
uncommon.  I have empirically found the "sweet spot" for most
array operations (OCI, Pro*c, plsql) to be around 100 or so.
November 29, 2000 Jon -- Thanks for the question regarding "Export -- calling from PLSQL", version 8.1.6.0.0
You Asked
Hi Tom,

I'm getting an error when I run a stored procedure that has a
call to the export utility.  The call in the stored procedure is
EXECUTE IMMEDIATE 'host exp blah/blah@blahdb.wwg.com
tables=my_delete LOG=export.log';

When I run the same exp command from the DOS prompt and from
SQL*Plus it runs correctly.

The error I'm getting when I try to run the stored procedure
from SQL*Plus is

ERROR at line 1:
ORA-00900: invalid SQL statement
ORA-06512: at "BLAH.ARCHIVE_PKG", line 101 (the call to exp)
ORA-06512: at line 1

The blah's have been changed to protect the innocent ..

Thanks,

Jon
and we said...
PLSQL cannot run host commands like that.  HOST is a
"sqlplus'ism".  HOST is not part of SQL or PLSQL.  HOST is also
available in the forms product where it is part of client side
PLSQL.  PLSQL in the server cannot directly run a program like
that.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:952229840241
for how you can do this in 8.1.6 using Java.

See also
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:666624437405
for other ideas.
November 30, 2000 ted -- Thanks for the question regarding "rman cold backup", version 8.1.6
You Asked
thomas, using rman for cold backup ? Is it necessary to backup
achive log ? it looks redundant ?
thnx ted
and we said...
If you keep rolling backups -- so you have the last 3 or 4
backups available -- you need the archive.  If you do not -- you
don't.

However, if you are not keeping AT LEAST the last 2 backups --
you are setting yourself up for disaster.  Lets say you just use
one tape and keep overwriting it.  You are halfway through your
backup and a disk fails (its happened - it can happen - it will
happen).  Now you have no backup (you were halfway through
overwriting your last backup -- it is no good.  You didn't get
to backup the file on the failed disk).  You are dead in the
water.  You have lost data.

So, I would say, YES -- you need to backup archive log during a
cold backup since you need it to restore and roll forward with
the last cold backup in the event this backup is no good.
November 30, 2000 Bhavesh -- Thanks for the question regarding "Installing PL/SQL Toolkit in different tablespace", version 4.0.2.8
You Asked
Hi Tom,
    I have installed OAS 4.0.2.8 and after installing it I need
to install PL/SQL Toolkit, but while installing the same I got
following error :
OWS - 28200: Oracle Database Error:959
ORA-00959: tablespace 'USERS' does not exists

While creating the database I have created all my tablespaces as
having suffix DB i.e. 'DB_USERS' instead of 'USERS'. Can i
install the PL/SQL toolkit without creating new tablespaces ?
    Thanks in advance.
Regards

Bhavesh
and we said...
support <Note:116409.1> addresses this:

Problem
-------

When installing the PL/SQL Web Toolkit through the Utilities GUI
for OAS 4.0.8.2, you  got the following error message:

"ORA-959: tablespace 'USERS' does not exist"

Solution
--------

MANUAL INSTALL SCRIPT TO CREATE THE PL/SQL WEBTOOLKIT
(this script was taken from NOTE: 99088.1 and modified)
*************************************************************
Run the following script in Server Manager or SQL*PLUS.  If
necessary, change the SYS password and change the path of your
ORACLE_HOME where OAS is installed. Also, this script was
written with default tablespace of USERS_NEW and temporary
tablespace of TEMP_NEW.  Modify those lines to reflect your
custom tablespace names.

-----------------------------------------------------
--Create User oas_public:

    connect sys/change_on_install

--ATTENTION:  The default password for OAS_PUBLIC when the user
is created in the
--normal method is the password of the admin user of the ADMIN
listener.  In this
--example, "manager" is used.

    CREATE USER oas_public identified by manager default
tablespace USERS_NEW
    temporary tablespace TEMP_NEW;
    GRANT  execute on sys.dbms_sys_sql to oas_public;
    GRANT  resource to oas_public;
    GRANT  connect to oas_public;
    GRANT  create public synonym to oas_public;
    GRANT  drop public synonym to oas_public;
    GRANT  create role to oas_public;
    GRANT  drop any role to oas_public;

--Run the install script for oas_public:

    connect oas_public/manager
    @<OAS HOME>\ows\cartx\plsql\admin\ctowasyn

--Create user websys:

    connect sys/change_on_install

    CREATE USER websys identified by manager default tablespace
USERS_NEW
    temporary tablespace TEMP_NEW;
    GRANT  resource to websys;
    GRANT  connect to websys;
    GRANT  create public synonym to websys;
    GRANT  drop public synonym to websys;
    GRANT  create role to websys;
    GRANT  drop any role to websys;

--Run the install script for websys (content services):

    connect websys/manager
    @<OAS HOME>\ows\4.0\admin\sql\content

Explanation
-----------

If you are installing through the GUI, you must have USERS and
TEMP tablespaces in order to install the toolkit.  However, if
you want to install into custom tablespaces, you will have to
install the toolkit manually.
November 30, 2000 Vasan -- Thanks for the question regarding "Retrieve duplicate values of a field in a table......", version Version 8.0.0
You Asked
I would like to retrieve values from a field which have
duplicates within it in a table. ie. the occurence of a value in
the field must be more than once...

For eg:In table T1 with field F1 if i have the
following entries:
i.e in table T1 under field F1:

 1
 1
 1
 2
 3
 4
 4

I would like to retieve only those set of values which
has an entry more than one time in it.
i.e desired result should be:

 1
 1
 1
 4
 4

Thanks in advance

Vasan..
and we said...
Either of:

select *
  from t
 where f1 in ( select f1
                 from t
                group by f1
               having count(*) > 1 )
/

or

select *
  from t t1
 where exists ( select null
                  from t t2
                 where t2.f1 = t1.f1
                   and t2.rowid <> t1.rowid )
/

They will have totally different performance characterists. The
first will tend to get the last row of the result set the
fastest (but makes you wait longer for the first row).  The
second is the opposite -- it'll start getting rows back to you
faster but it'll take longer probably to get the last row.
November 30, 2000 wallacel -- Thanks for the question regarding "v$lock", version 8.1.6
You Asked
Tom:

at one session i
create table test ( a int);
insert into test values (1);
commit;
update test set a=5;

then i go to another session:
alter test set a=6;

when i go to check v$lock;
i got two rows for each session.
and one id1 is object_id for test.
how about the other id1( the big one)? what is that?
and we said...
You must be referring to the TX lock.

These are acquired in an exclusive mode when a transaction
initiates its first change and held until the transaction does a
COMMIT or ROLLBACK.  They are used as a queuing mechanism for
processes waiting for something locks by a transaction's
change to become available again (you might wait on someone
elses TX lock -- when it becomes available, the resource you
wanted is free).

id1 = undo segment number << 16 | slot

meaning, you can look at:

  1  select trunc(id1/power(2,16)) segment_id,
  2        id1 - trunc(id1/power(2,16))*power(2,16) slot
  3*   from v$lock where type = 'TX'
ops$tkyte@DEV816> /

SEGMENT_ID       SLOT
---------- ----------
         5         75
         4         45
         6         50
         4         45
         3         70

to see the rollback segment information for that transaction.
November 30, 2000 Leah -- Thanks for the question regarding "Mutating Trigger", version version 8.1.5
You Asked
We have the following trigger:

CREATE OR REPLACE TRIGGER trg_tsp_cons_app_map_del
AFTER DELETE
ON tsp_consumer_application_map
FOR EACH ROW

DECLARE
vLast number(1);
begin

    select 1
    into vLast
    from tsp_consumer_application_map
    where consumer_sid = :old.consumer_sid;

    /* If there is exactly only one record, then don't delete
consumer record. */
exception

    when too_many_rows then
        null; /* If there is more than one row in
tsp_consumer_application_map then don't delete the consumer row.
*/

    when no_data_found then
        delete tsp_consumer where sid = :old.consumer_sid;
end;

TSP_CONSUMER has a 1:M relationship to
TSP_CONSUMER_APPLICATION_MAP. TSP_CONSUMER_APPLICATION_MAP has
the following definition:

consumer_sid      number(20)  PK, FK
consumer_app_sid  number(20)  PK, FK
created_dt        date

When a delete is issued to TSP_CONSUMER_APPLICATION_MAP, we get
the following error:
ORA-04091: table TSP.TSP_CONSUMER_APPLICATION_MAP is mutating,
trigger/function may not see it

What causes this? We are thinking of writing this as a stored
proc or inline code instead of using a trigger.

Thanks,
Leah
and we said...
see
http://osi.oracle.com/~tkyte/Mutate/index.html
for all of the details on this approach.   There are two issues
with your trigger above

1) it attempts to read in a FOR EACH ROW trigger the table that
fired it.  With the exception of an INSERT into VALUEs (a single
row insert) this is not permitted

2) even if it COULD read the table -- it attempts to then delete
from the parent table.  This would cause the same error.  You
cannot modify the parent table in a trigger on the child.  Even
if you COULD it would fail -- the parent record cannot be
deleted because there still exists child records that map to it
-- we are in the PROCESS of deleting the last child record, we
have not deleted it so even if we COULD do the delete on the
parent, it would fail since the child still exists technically.

So, how to do this in a trigger?  Here is one way.  Please read
the paper at the URL above -- it explains the technique I use:

tkyte@TKYTE816> create table tsp_consumer( sid int primary key
);
Table created.

tkyte@TKYTE816> create table tsp_consumer_application_map
  2  ( consumer_sid int references tsp_consumer,
  3    consumer_app_sid int,
  4    primary key(consumer_sid,consumer_app_sid)
  5  )
  6  /
Table created.

tkyte@TKYTE816> create or replace package state_pkg
  2  as
  3      type myArray is table of char(1) index by
binary_integer;
  4
  5      modified myArray;
  6      empty    myArray;
  7  end;
  8  /

Package created.

tkyte@TKYTE816> create or replace trigger
                        tsp_consumer_appl_map_BD
  2  before delete on tsp_consumer_application_map
  3  begin
  4      state_pkg.modified := state_pkg.empty;
  5  end;
  6  /

Trigger created.

tkyte@TKYTE816> create or replace trigger
                        tsp_consumer_appl_map_ADFER
  2  after delete on tsp_consumer_application_map for each row
  3  begin
  4      state_pkg.modified(:old.consumer_sid):='Y';
  5  end;
  6  /

Trigger created.

tkyte@TKYTE816> create or replace trigger
                      tsp_consumer_appl_map_AD
  2  after delete on tsp_consumer_application_map
  3  declare
  4      idx number;
  5      cnt number;
  6  begin
  7      idx := state_pkg.modified.first;
  8      for i in 1 .. state_pkg.modified.count loop
  9          select count(*) into cnt
 10            from dual
 11           where exists ( select null
 12                            from tsp_consumer_application_map
 13                           where consumer_sid = idx );
 14
 15          if ( cnt = 0 ) then
 16              delete from tsp_consumer where sid = idx;
 17          end if;
 18          idx := state_pkg.modified.next(idx);
 19      end loop;
 20      state_pkg.modified := state_pkg.empty;
 21  end;
 22  /

Trigger created.

tkyte@TKYTE816> insert into tsp_consumer values ( 1 );
tkyte@TKYTE816> insert into tsp_consumer values ( 2 );

tkyte@TKYTE816> insert into tsp_consumer_application_map values
( 1, 1 );
tkyte@TKYTE816> insert into tsp_consumer_application_map values
( 1, 2 );
tkyte@TKYTE816> insert into tsp_consumer_application_map values
( 2, 1 );
tkyte@TKYTE816> insert into tsp_consumer_application_map values
( 2, 2 );

tkyte@TKYTE816> delete from tsp_consumer_application_map where
consumer_sid = 1 and consumer_app_sid = 1;

1 row deleted.

tkyte@TKYTE816> select * from tsp_consumer;

       SID
----------
         1
         2

tkyte@TKYTE816> delete from tsp_consumer_application_map where
consumer_sid = 1 and consumer_app_sid = 2;

1 row deleted.

tkyte@TKYTE816> select * from tsp_consumer;

       SID
----------
         2

tkyte@TKYTE816>
November 30, 2000 Ravi -- Thanks for the question regarding "Hints", version 8.1.6
You Asked
Tom,

Are hints in SQL statements useful?

What are their advantages and disadvantages.

Thanks in advance.
and we said...
They easy answer is yes, of course they are.  You can help a
query get a better plan then without having the hint.  You can
test different plans to see which would be better.

The advantages are obvious -- you can influence the query
execution plan.

The disadvantages are not as obvious.  You might influence us to
use a particular plan that is not as good as the one we would
come up with on our own.  Especially after an upgrade with new
features added.

I use hints only when I have to -- to help a poorly performing
query.  I apply my specific domain knowledge of the underlying
data (something the optimizer doesn't have) and help it along.
It is something to be used infrequently, not as a matter of fact.
November 30, 2000 OP -- Thanks for the question regarding "Tuning process while applying Equi Join !!", version 8.1.6.0.0
You Asked
Dear Tom,
Hi !

Thanks Alot for the previous suggestions.They
really were of immense help.Thanks Alot !!

This Question is related with Tuning process :

Suppose I have two tables :- T1,T2
BOTH THE TABLES HAVE 2 COLUMNS number type.There is
no primary key or foreign key in any of these tables.
First column is common in both the tables.

structure for T1 (i number,j number)

structure for T2 (i number,j number)

Assume that T1 HAS 15000 RECORDS and
T2 HAS 2000 RECORDS .There is a need
to retreive information from both the
tables.

In the select statement will it make any difference
if while writing a Join if in the from clause I
write T1,T2 and second time t2,t1

For example

Ist CASE

select t1.i,t2.j from t1,t2 where t1.i=t2.i

IInd CASE

select t1.i,t2.i from t2,t1 where t2.i=t1.i

Is Processing time is going to be different in both the cases .
If yes what is the reason and what is the best way to write
this Query.Whcih table is the driving table and which one is
driven.

Kindly answer !

Thanks & Regards
OP
and we said...
Guess you really don't want to say whether you allow for any
indexes or not so, I'll assume not.  Indexes would make this
matter.

The difference here probably won't matter.  We'll tend to sort
and merge the two tables.  You can see this easially using
sql_trace and tkprof.

say you run a script like:

set termout off
spool temp
drop table t1;
drop table t2;
create table t1 as select object_id i, object_id j from
all_objects where rownum < 15001;
create table t2 as select object_id i, object_id j from
all_objects where rownum < 2000;
analayze table t1 compute statistics;
analayze table t2 compute statistics;

alter session set timed_statistics=true;
alter session set sql_trace=true;

select /*+ test1-a */ t1.i, t2.j from t1, t2 where t1.i = t2.i;
select /*+ test1-b */ t1.i, t2.j from t2, t1 where t1.i = t2.i;

You'll find:

select /*+ test1-a */ t1.i, t2.j
from
 t1, t2 where t1.i = t2.i

call     count       cpu    elapsed  disk query current  rows
------- ------  -------- ---------- ----- ----- -------  ----
Parse        1      0.01       0.00     0     0       0     0
Execute      1      0.00       0.00     0     0       0     0
Fetch      135      0.29       0.30    33    41      24  1999
------- ------  -------- ---------- ----- ----- -------  ----
total      137      0.30       0.30    33    41      24  1999

Misses in library cache during parse: 1
Optimizer goal: CHOOSE
Parsing user id: 334

Rows     Row Source Operation
-------  ---------------------------------------------------
   1999  MERGE JOIN
   2000   SORT JOIN
   1999    TABLE ACCESS FULL T2
   1999   SORT JOIN
  15000    TABLE ACCESS FULL T1

*****************************************************************
***************

select /*+ test1-b */ t1.i, t2.j
from
 t2, t1 where t1.i = t2.i

call     count       cpu    elapsed  disk query current  rows
------- ------  -------- ---------- ----- ----- -------  ----
Parse        1      0.01       0.00     0     0       0     0
Execute      1      0.00       0.00     0     0       0     0
Fetch      135      0.33       0.35     0    41      24  1999
------- ------  -------- ---------- ----- ----- -------  ----
total      137      0.34       0.35     0    41      24  1999

Misses in library cache during parse: 1
Optimizer goal: CHOOSE
Parsing user id: 334

Rows     Row Source Operation
-------  ---------------------------------------------------
   1999  MERGE JOIN
  15001   SORT JOIN
  15000    TABLE ACCESS FULL T1
   1999   SORT JOIN
   1999    TABLE ACCESS FULL T2

showing it doesn't really matter in this case.
November 30, 2000 Loh -- Thanks for the question regarding "Using copy in OEM.", version 2.0.4.0.0
You Asked
I wanted to schedule a job to copy data from table TEST and append to table
TEST_HISTORY. I am trying out in Oracle Enterprise Manager Console. I created a
job and specified the job task as "Run SQL*Plus Script". In the Parameters tab,
I did not specify anything for the "Run SQL*Plus Script Parameters". I have
checked the Override Preferred Credentials checkbox and specified my username(eg
myid) and password(eg mypw). In
the script text box I wrote:

spool d:\output.lst;
copy from myid/mypw@mydb append test_history using select * from test;
spool off;

This is what I see in my output.lst:

Array fetch/bind size is 15. (arraysize is 15)
Will commit when done. (copycommit is 0)
Maximum long size is 80. (long is 80)

ERROR:
ORA-12154: TNS:could not resolve service name

I copied the command to my SQL*Plus window and run and it was fine. I changed
the copy command to a CREATE TABLE statment in OEM and a table was created. So I
proved that the copy command was valid and I had no connection or write access
problem. But I just could not get the copy command to work in the OEM. In the
permission tab under this job, the administrator "SYSMAN" which I used to log
into OEM was not allowed to change any of the view/modify/full permissions. The
only change I could make was to check/uncheck the notify checkbox. What went
wrong? Please advise. By the way, my OEM is installed on Windows NT.
and we said...
SQLPlus uses the tnsnames file to resolve the @mydb.  OEM is not running on your
machine -- its running on a server somewhere.  You need to add mydb to the
tnsnames.ora file on the server where OEM is running so it can see mydb as well.
December 01, 2000 Dinesh -- Thanks for the question regarding "Personal Oracle 8i on Windows ME", version Personal Oracle 8i
You Asked
Hi,

I want to load personal oracle 8i on my PC having Windows ME
loaded. I tried to load but it's not allowing me to load it on
PC. Can you help me in this matter?

thanks in advance,
dinesh
and we said...
We currently do not support Personal Oracle on WindowsME.

Personal Oracle is supported only on

Win2k
Win95
Win98
WinNT

on the windows platform currently.  This will change in the
future.
Review & Followup
Rating: 4
July 10, 2001
Reviewer: Robson Vasconcelos from Recife, PE BRAZIL

Rating: 3
December 06, 2001
Reviewer: Betty from FL USA
Is this still true on December 6th 2001?

December 01, 2000 wallacel -- Thanks for the question regarding "v$sort_segment and v$sort_usage", version 8.1.6
You Asked
Tom:

for LOCALLY MANAGED TEMPORARY TABLESPACE , what size is
suitable to "uniform size clause", or use autoallocate would
be fine
and we said...
I would use a uniform size clause, not an autoallocate.  The
reasoning is that you typically have one temporary segment that
is used by many people.  Only one person can use an extent at
any given time.  You do not want some small extents and then
bigger and then even bigger extents -- rather you want a pool of
equi sized chunks of temp space to be used by all.

As for the size -- depends on your needs.  If you do tons of
large sorts that request 10meg of space, extent sizes in the
megabytes would not be unreasonable.  Typically, sizes in the
512k - 1m range are used.  Make it some multiple of your
sort_area_size because a process always writes data equal to
SORT_AREA_SIZE to a temporary segment.
December 01, 2000 Cuitlahuac -- Thanks for the question regarding "Indexes size", version 7.3.4
You Asked
How can I know an index size?

Thanks and Regards
and we said...
see my show_space procedure at
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
..
December 01, 2000 wallacel -- Thanks for the question regarding "local managed temp tablespace", version 8.1.6
You Asked
Tom:

I have a very small testing database, in which i created
a Locally managed temp tablespace, and also i set autoextend
on for the temp file, after a while, i saw the temp file
go to some big size, my question is
at real world , is that possible when lots of user accessing
database concurrently that temporay is not enough for them,
so i need to create multiple temporary tablespace.

2. do i need to resize those locally managed temp tablespace
to some "small" size periodly?

3. currently i create only one temporay tablespace and
assign all user to that. i was wondering what did you do
for that? I know you have a big database which have lots of
users.
and we said...
1) You can create multiple temporary tablespaces however --
people are statically assigned to them so now you have the
problem is figuring out how to assign people optimally to these
temporary tablespaces to get an even load.  Typically this is
not possible (unless everyone is always logged in).

OS or database striping of the temporary tablespace will
alleviate most contention issues here.  If you cannot stripe
some files at the OS level, just use many datafiles when
creating the temporary tablespace on different disks to achieve
the same net effect.

2) that is upto you.  Since you do not need to back them up, you
might consider leaving them be.  Unless some really wild
operation made them grow abnormally large -- their size is what
they need to be to support your peak processing (eg: they will
just grow to be that large again anyway).

3) that is what I do.
December 01, 2000 -- Thanks for the question regarding "maxdatafiles ect . setting in controlfile", version 8.1.6
You Asked
Tom:

in oracle8i Administrator's guide page 5-5 , it says that
I probably need to change the setting for maxdatafiles ect.
if the original setting is too low.

on page 10-3, it says that the MAXDATAFILES specifies an initial
size of the datafile portion of the control file,Later, if you
add a file whose number exceeds MAXDATAFILES but LESS THAN OR
EQUAL TO THE VALUE SPECIFIED BY THE "DB_FILES" parameter, the
control file automatically expands to allow the datafile portion
to accommodate more files.

seems to me "DB_FILES" is the true parameter that take control.
we never need to recreate control file simply because
the originaly setting for MAXDATAFILES is too low.
is that correct?
and we said...
The confusion arises from the fact that in Oracle7, the
MAXDATAFILES was the upper bound for DB_FILES whereas in
Oracle8, it is simply the initial amount of space allocated in
the control files.

In Oracle7, if you set DB_FILES > MAXDATAFILES, it would not
work as the control file was a static size.  You would have to
recreate your control files when you hit the upper MAXDATAFILES
limit.

In Oracle8, the control file will "grow" if it can to accomidate
the new datafiles.   There may be cases where the controlfile
cannot grow (eg: it is on a raw partition being used with Oracle
Parallel Server and the partition isn't big enough -- or there
isn't sufficient disk space on a cooked file system to grow it).
 In this case, MAXDATAFILES becomes a hard limit.  You still
might have to recreate or move your control files to get around
it.

So yes, DB_FILES is the parameter that controls this now in
Oracle8.
December 01, 2000 V Siva -- Thanks for the question regarding "No data in All_Triggers table", version 8.1.6
You Asked
Hi Tom,

Something tricky happening in one of our database. I have creted
BEFORE INSERT/UPDATE .. FOR EACH ROW triggers on tables to
update create_user and date, update_user and date.
the table owned by a user 'abc', and 2 other users are abc_sel
for which only select privilege is given, abc_upd which have
update, insert, select, delete privileges on the table through
synonyms.

The following query doesn't return any rows:

select * from all_triggers where owner = 'ABC';

But all triggers are working on all tables. What could be the
problem. I tried this in SQL*PLUS, in Toad -Schema builder,
single trigger on any table is not showing.

Thanks,
Siva
and we said...
If you extract the view definition for all_triggers -- it has in
part:

....
       (
        trigobj.owner# = userenv('SCHEMAID') or
        tabobj.owner# = userenv('SCHEMAID') or
        exists (select null from sys.sysauth$
             where grantee# in (select kzsrorol from x$kzsro)
               and privilege# = -152 /* CREATE ANY TRIGGER */)))
.....

You need to either:

o own the trigger
o own the table the trigger is on
o have the CREATE ANY TRIGGER privilege

To see a trigger.  ALL_TRIGGERS shows you the triggers you
should be able to see -- not "all triggers in the database".
Use DBA_TRIGGERS if you want to see each and every trigger
(regardless of whether you own it or not).
December 01, 2000 -- Thanks for the question regarding "primary key", version 8.1.6
You Asked
Tom:

what's the benefit for a table have a primary key?
if for performance reason, i can define it not null and
then create an index on it.
did every table should have primary key?
what's guide line?

did compare with two number is faster than compare two varchar2?
I have a table test( a varchar2(256) primary key,.......);
also i have serveal table contain "a"
if i modified it to
test(b number primary key, a varchar2(256),.....);
and assign each "a" a unique number b.
and change other table's column from "a" to "b"
do you think it will help performance?

the reason i want to do that is i think compare two number is
faster than compare two varchar2.

do you think it is a good idea?
and we said...
The benefit of a primary key over a NOT NULL and UNIQUE index is
mostly semantics.

A primary key has meaning -- it conveys something about the
data.

A not null constraint plus a unique index does not convey that
same information.

A primary key just happens to create a not null constraint and
an index on the data (may be unique or non-unique index) in
order to enforce itself -- but a not null constraint and index
does not imply "primary key".

Not every table *needs* a primary key but if it has one, it
would be best to use "primary key".  You can only create foreign
keys to primary key or unique constraint columns.  Various tools
can make use of the fact that a primary key is there for display
purposes and such.  It just adds meaning.

As for number versus character string -- it really depends on
the length of the field.  Numbers in Oracle are stored in a
packed decimal "like" field of upto 22 bytes.  They are in fact
a varying length character string.  It take as much work to
compare them as strings in many cases until the string gets very
large.  If the strings in your case are always pretty large --
go for the number, else it really doesn't matter.
December 01, 2000 OP -- Thanks for the question regarding "Is there any command to Unlock a table !", version 8.1.6.0.0
You Asked
Dear Tom,
Hi !

Thanks very much for the very useful tips on tuning process.

My Quest to you is

When I am trying to delete some rows from a table T1
it says "TABLE LOCKED".It doesn't allow me to make
deletion possible.

I am logged in to oracle as user "TEST/TEST".There are
so many developers who are also logged in as TEST/TEST.

1) I there any way to unlock this table ?

2) Is there any way to find out how many users are using
T1 table and for what purpose.

3) How to kill sessions in ORACLE for a USER !

Kindly answer !

Thanks and Regards
OP
and we said...
1) We don't have an error message "table locked" -- a delete
would wait for rows to become unlocked to proceed.  I'd really
need more information to help you out such as the exact error
you are getting and the environment in which you get it
(sqlplus, custom app, forms, etc etc etc)

2) select a.username us, a.osuser os, a.sid, a.serial#
from   v$session a, v$locked_object b, dba_objects c
where  upper(c.object_name) = upper('&tbl_name')
and    b.object_id   = c.object_id
and    a.sid         = b.session_id;

will show you who has locks on the object

3) alter system kill session 'sid,serial#'

where you get the sid and serial# from v$session.
December 01, 2000 ashish -- Thanks for the question regarding "passing array to stored procedure from java", version 8.1.6
You Asked
In the recent issue of Oracle Magazine I saw an example of
array as OUT parameter of a stored procedure.

I could not pass an array to a stored procedure. How is it
possible ? can u give me an example ?

Thanks
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:712625135727
for that example.


Subject | Article | Last Updated (East coast time)
Passing :new, :old values as record parameters from triggers | article only | Dec 03, 2000 09:29 am
Relationship between blocksize and maxextents | article only | Dec 03, 2000 10:00 am
trigger | article only | Dec 03, 2000 10:01 am
Installing Personal Oracle8(TM) Multiple Language Edition | article only | Dec 03, 2000 10:04 am
one transaction | article only | Dec 03, 2000 10:20 am
Calling two databases in a form ? | article only | Dec 03, 2000 10:58 am
"Autoincrement" column | article only | Dec 03, 2000 01:33 pm
Parallel insert - elapsed time - clarification | article only | Dec 03, 2000 01:35 pm
Export as a backup | article only | Dec 04, 2000 08:35 am
Database Date format | article only | Dec 04, 2000 08:48 am
How to deploy application written in Oracle JDeveloper 3.1.1.2 | article only | Dec 04, 2000 09:21 am
BACKUP | article only | Dec 04, 2000 09:35 am
How can we stop Oracle DBA a/c (including SYS/SYSTEM) to see other a/c's DATA | article only | Dec 04, 2000 09:38 am
Accessing datatypes across users . | article only | Dec 04, 2000 10:01 am
about the OCI | article only | Dec 04, 2000 10:04 am
Recovery | article only | Dec 04, 2000 12:57 pm
long query | article only | Dec 04, 2000 07:14 pm
initrans | article only | Dec 04, 2000 07:23 pm
Rownum question | article only | Dec 05, 2000 08:19 pm
Indexes | article only | Dec 05, 2000 08:22 pm
Tablespace Quota | article only | Dec 05, 2000 08:25 pm
row(s) 1 - 21 of 21
December 03, 2000 Dusan -- Thanks for the question regarding "Passing :new, :old values as record parameters from triggers", version 8.1.6
You Asked
Hi Tom,

We try to pass all :new, :old values from a row trigger to
stored procedure. It is possible (in trigger) as :
declare
r table%rowtype;
begin
r.item1 := :new.item1;
r.item2 := :new.item2;
..
call_procedure(r);
end;

This way means more coding for us, as well as maintenance
effort. Is not it possible just pass all :new (:old) values
to stored procedure immediately as record like
call_procedure(record_of_all_new_values); ?

Thanks,

Dusan
and we said...
No, there is no way to do this.  I typically use SQL to write
SQL in order to reduce the amount of code I would have to
otherwise type.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:671424467534
for an example of what I mean by this.
December 03, 2000 Andre -- Thanks for the question regarding "Relationship between blocksize and maxextents", version 8.1.6
You Asked
I´m working on UNIX. I´ve read there is some relationship
between blocksize and maxextents. Is that true ? If so, could
you explain ?
and we said...
There used to be in earlier v7.x releases.  The max number of
extents was dictated by the block size.  You may now have an
unlimited number of extents on objects.
December 03, 2000 -- Thanks for the question regarding "trigger", version 8.1.6
You Asked
Tom:

i need to write a trigger to check some requirement.
like data inputed in col1 must be upper case, if not
my trigger will modify it to upper case,
so i create or replace trigger a before insert or update
on "table" for each row
:new.col1:=upper(:new.col1);

what if i want to reject the row at some situation?
like if i found the string contain substr "aaa",
i will reject the row other wise make it upper case?
and we said...
Use the raise_application_error builtin to fail the insert and
return a custom error code and message to the client
application:

begin
   :new.col1 := upper(:new.col1);
   if ( :new.col1 like '%AAA%' ) then
      raise_application_error( -20001, 'Cannot have AAA' );
   end if;
end;
December 03, 2000 sekhar -- Thanks for the question regarding "Installing Personal Oracle8(TM) Multiple Language Edition ", version 8.0.3
You Asked
Hi Tom,

I'm accessing different Oracle databases from version 7.3.3 to
8.1.6 through my system(Client machine). My machine is Windows95
version 4.00.950B - Dell Windows 95 PC. I never created any
entries in tnsnames.ora file wither by using sql net easy
configuration or manually. And in sqlnet.ora file the following
entry exists.

NAMES.DIRECTORY_PATH= (ONAMES,TNSNAMES)

What is this mean? Is it controlled by using Oracle names
server?
Please provide some insight about how I was able to access
different databases from my system.

I want to install(doing for the forst time) Personal
Oracle8.0.3.0.0 (TM) Multiple language version.

The prodinfo.txt file contains the following data.

PART_NUMBER=TBD
PRODUCT=Personal Oracle8(TM) Multiple Language Edition
VERSION=8.0.3.0.0
SERVER_OPERATING_SYSTEMS=Windows NT, Windows 95
CLIENT_OPERATING_SYSTEMS=Windows NT, Windows 95,
    Windows 3.1 (V7 RSF & SQL*Net components only)

If I install this, can I still be able to access the exsting
databases or not?

Thanks,
Sekhar
and we said...
That names.directory_path says to use an Oracle Names (ONAMES)
server and then, if it could not resolve the name, to use the
local tnsnames.ora file.  You've been using an Oracle Names
server in all probability.

I would not install 8.0.3 but rather would get the latest 8.1.6
or 8.1.7 version.  8.0.3 is pretty old.

Yes, if you install this, the other databases will still be
accessible.  You should install this into an Oracle Home
separate and distinct from the Oracle home that has your current
client software in it.  You'll be able to use the oracle home
selector tool to pick which oracle home should be active at any
point in time.
December 03, 2000 Omar -- Thanks for the question regarding "one transaction", version 6.0
You Asked
Hi Tom,

 I have a form built on table t1 , when a field in this table is
updated and become let us say 1, I want to update , insert on
 another tables ,
  insert into t2 values ...
  update t3 set ....
  insert into t4 values....
  .
  .
how could I ensure that all the DMLs will pass or fail togather,

I mean if updating t3 fails all the previouse transaction rolls
back. Where is the most suitable trigger to put the code, or if
it is possible to create DB trigger to handle the transactions.
Please I need to know as soon as possible.

thanks in advance
and we said...
Read about savepoints, for example:

    savepoint foo;
    begin
       insert into t2
       update t3
       insert into t4
    exception
       when others then
           rollback to foo;
           RAISE;
    end;

will do it.
December 03, 2000 priya -- Thanks for the question regarding "Calling two databases in a form ?", version 8.0.5
You Asked
hai Tom,

Can you please help me...

1) How can I make call to two different databases...ie In a form
one canvas should be based on access database and another is
oracle ? How should I ?

2) How can I make connection to access database from a form ?

3) I have two queries...

  begin
   select qty,price into :global.rqty,:mcpp_idet.price
        from   mcpp_sinvdet
        where part_model_no = :mcpp_invdet.part_model_no
         and inv_no = :mcpp_invmast.inv_no;

       if sql%found then
            begin
          select pdesc into :mcpp_rinvdet.pdesc from mcpp_stock
               where part_model_no = :mcpp_invdet.part_model_no;
            exception when no_data_found then
            null;
            end;
       end if;
 end;

As the result of above code there will be TWO NETWORK CALLS.  I
want the above two queries to be written in a single
query...ONLY ONE NETWORK CALL.

thank you very much......

best regs
priya
and we said...
1) using the exec_sql package and an ODBC connection is one
method.  See the documentation for exec_sl.

2) using ODBC.  see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:218213305850
for more info.

3) a stored function would be the best answer then (and you do
realize that a select into doesn't set the sql%found/notfound --
it would raise an exception -- you would have to have a WHEN
NO_DATA_FOUND exception handler in the above code!!!).  You
could write it as:

select qty,price,NULL into :a, :b, :c
  from   mcpp_sinvdet
 where part_model_no = :mcpp_invdet.part_model_no
   and inv_no = :mcpp_invmast.inv_no
union all
select to_number(null), to_number(null), pdesc
 from mcpp_stock
where part_model_no = :mcpp_invdet.part_model_no
  and not exists ( select null
                     from   mcpp_sinvdet
               where part_model_no = :mcpp_invdet.part_model_no
                 and inv_no = :mcpp_invmast.inv_no )

You'll either get the result of query 1 or, if query 1 returns
no data -- query 2 will return whatever it might find.  You have
to be careful to make the select lists identical in order to use
the union all operation.
December 03, 2000 Zsolt -- Thanks for the question regarding ""Autoincrement" column", version 8.1.5
You Asked
Hi Tom,

I have a column in a table that must have continous values(e.g.
the first 1 the second 2 etc.)
I've made a universal function that is called by a before insert
trigger:

CREATE OR REPLACE  FUNCTION "C_ADMIN"."NextVal" (Table
varchar2,Col varchar2) return number
is Num Number(4) ;
Begin
  Num := 0 ;
  EXECUTE IMMEDIATE 'Select Max(' ||Col|| ') from '|| Table Into
num ;

  return num+1 ;
End ;

This works perfectly using with the trigger but ONLY if the
column doesn't have primary index.

It seems to me that the not null constraint is being executed
prior than the trigger itself.
I even tried to give the column a default value, but the
default value doesn't work for this primary key column,
I always get the error message: "Field... must have a value".

Is there a way to solve this problem?

Another thing: I use Sql*Plus Worksheet that comes with
Oracle Enterprise Manager 2.1.0.1.0 and after executing several
commands often doesn't make anything; I can write in any text
and does nothing. I have to quit and restart to make it good
again. Is this a bug?

T.I.A.

Zsolt Csillag
and we said...
first -- I would very strongly urge you to reconsider the need
for a "continous" set of numbers in a table.  That would be the
worst thing you could ask to do in a relational database.  It
would totally kill concurrency -- one of the primary reasons for
using a database in the first place.  You'll do exactly one
transaction at a time.

I do not see how that procedure could work in general in any
case.  In fact -- it cannot.  It will raise a mutating table
error if used on a row level trigger (and it must be on a row
level trigger in order for it to be able to assign a value to
the :new.pk) and you insert a set of data (eg: this trigger will
limit you to inserting exactly 1 row at a time -- never "insert
into t select * from t2").

Another issue is that it will cause duplicate values to be
generated as there is nothing stopping two sessions from running
the query at exactly the same time (they don't even need to do
it at the same time, just in overlapping transactions) -- both
will recieve the same max number and attempt to insert it.  One
of them will eventually recieve "dup val on index" and fail (so
this is worse even then limiting concurrency -- it'll cause all
concurrent attempts to fail with an ERROR!).

Now, I don't understand where your "field ... must have a value"
error is coming from.  As you have it (once i change TABLE to
tname since TABLE cannot be a variable name) -- it "works".  The
not null constraint is definitely checked AFTER the before for
each row trigger if that trigger modifies the COLUMN on which
the constraint is on:

ops$tkyte@DEV816> CREATE OR REPLACE  FUNCTION Next_val (tname
varchar2,Col varchar2) return number
  2  is Num Number(4) ;
  3  Begin
  4    Num := 0 ;
  5    EXECUTE IMMEDIATE 'Select Max(' ||Col|| ') from '||
                tname Into num ;
  6
  7    return num+1 ;
  8  End ;
  9  /

Function created.

ops$tkyte@DEV816> show err
No errors.
ops$tkyte@DEV816> create table t ( x int primary key, y  int );

Table created.

ops$tkyte@DEV816> insert into t values ( 1, 0 );

1 row created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create or replace trigger t_trigger
  2  before insert on t for each row
  3  begin
  4          :new.x := next_val('t', 'x' );
  5  end;
  6  /

Trigger created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t(y) values ( 1 );

1 row created.

ops$tkyte@DEV816> select * from t;

         X          Y
---------- ----------
         1          0
         2          1

I would suggest however that upon running the above example, you
open another new session and attempting to to "insert into t(y)
values ( 2 )".  That session will BLOCK until the session above
commits and when the session above does commit -- you'll see the
unavoidable

ORA-00001: unique constraint

error issued for that session (they don't even have to do the
query at the same instant -- they only need to attempt to query
the table in overlapping transactions!!).

Also, try executing:

ops$tkyte@DEV816> insert into t(y) select 2 from dual;
insert into t(y) select 2 from dual
            *
ERROR at line 1:
ORA-04091: table OPS$TKYTE.T is mutating, trigger/function may
not see it
ORA-06512: at "OPS$TKYTE.NEXT_VAL", line 5
ORA-06512: at "OPS$TKYTE.T_TRIGGER", line 2
ORA-04088: error during execution of trigger
'OPS$TKYTE.T_TRIGGER'

to see what I mean about only "insert into t VALUES" working on
this table -- you'll never be able to "insert into t SELECT"
with a trigger like this.

Needless to say -- this is not a good thing to try to do.
You'll end up hating this (and so will your end users) in the
end!  If you need to "sequence" things -- use a date field.  Gap
free sequence numbers just don't exist.

If you feel you MUST do this "continous" set of numbers thing
(and I would seriously reconsider that !) you need to do it like
this:

ops$tkyte@DEV816> create table sequences
  2  ( seq_name varchar2(30) primary key,
  3    val int );

Table created.

ops$tkyte@DEV816> insert into sequences values ( 'MY_SEQ', 0 );

1 row created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> create or replace
     function next_val( p_seq_name in varchar2 )
  2  return number
  3  as
  4     l_val number;
  5  begin
  6     update sequences set val = val+1 where seq_name =
                                                  p_seq_name
  7     returning val into l_val;
  8
  9     if ( sql%rowcount = 0 )
 10     then
 11        raise_application_error( -20001, 'no such sequence'
);
 12     end if;
 13     return l_val;
 14  end;
 15  /

Function created.

ops$tkyte@DEV816>
ops$tkyte@DEV816> drop table t;

Table dropped.

ops$tkyte@DEV816> create table t ( x int primary key, y int );

Table created.

ops$tkyte@DEV816> create or replace trigger t_trigger
  2  before insert on t for each row
  3  begin
  4      :new.x := next_val( 'MY_SEQ' );
  5  end;
  6  /

Trigger created.

ops$tkyte@DEV816> insert into t (y) values ( 1 );

1 row created.

ops$tkyte@DEV816> insert into t (y) select 2 from dual;

1 row created.

ops$tkyte@DEV816> select * from t;

         X          Y
---------- ----------
         1          1
         2          2

ops$tkyte@DEV816>

It solves the mutating table issue (by not reading the table you
are modifying) and the ORA-0001 issue as well by making people
UPDATE a single row (and hence serializing) -- instead of
READING a row (which since we have non-blocking reads WON'T
block)....

As for the OEM issue, I'm afraid I'm not familar with it --
haven't heard of that myself.  I do not use that particular tool
so I haven't seen it myself.
Review & Followup
Rating: 5
Excellent May 14, 2001
Reviewer: Gururaj Kulkarni from GA USA
Now this is a complete answer. It helps a lot.

December 03, 2000 Orna -- Thanks for the question regarding "Parallel insert - elapsed time - clarification", version 8.0.6
You Asked
HI,

I got your response on my question regarding direct path inserts
- thanks a lot.

Still - my question regarding the elongated elapsed time using
parallel insert remains unclear to me :

I inserted 800,000 records from table A to table B using a
regular insert, direct insert and a parallel insert.
I did it several times.

I got ( consistent ) VERY high elapsed time ONLY for the
parallel inserts - though its CPU where hundred percents shorter
then both former methods.
Why is that ?

Thanks in advance
Orna
and we said...
if you are using TKPROF -- the trace is for your parent process
and shows only the CPU and elapsed times for the parent.  What
you are missing is the cpu times of the child processes.  Your
parent process was in fact waiting on something -- the child
slave processes that were doing all of the work.  When using PQ
-- its hard to see the cpu/elapsed since the cpu is generally
consumed by the slaves and your not tracing them.
December 04, 2000 Winston -- Thanks for the question regarding "Export as a backup", version 81x
You Asked
What are the main advantages and disadvantages of using export
as a backup.

Thanks,

Winston
and we said...
Well, the disadvantage is that export is not truly a backup
tool.  Export is a tool to extract data from a database at a
point in time.  You cannot roll it forward to recover with.  You
can only import that exact same data (and all changes made to
that data since the export will be lost -- with no chance of
getting them back).

Export should not be considered a backup. It should simply be
considered a point in time copy of the data.  It is not useful
for media recovery (eg: you lose a single disk).  It is not
efficient to recover from (it could take a long time to import a
big export -- much longer then restoring the datafiles and
applying redo log to them).

Export is useful as part of an overall backup strategy.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:879628057806
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:718225234495
for more discussion on this topic

December 04, 2000 Bhavesh -- Thanks for the question regarding
      "Database Date format", version 8i

      You Asked
hi Tom,

I wanted to change my oracle database date from '01-jan-2000'
to '01/01/2000'

i have changed nls_date_format of the init.ora parameter .
and restart the server. then i have execute following command
at sql prompt at server.

select * from dual;

it shows correct date ie '01/01/2000'

then i went to the nt-clinet machine and connect to oracle
database server, then executeed above command at sql prompt

it was showing '01-jan-2000' which is default date.

so i went to registry of nt client machine and
changed the parameter ie nls_date_format and again went
to the sql prompt and executed above command.

it shows correct date ie '01/01/2000'

Can you tell me why we have to do above step since we have
changed database date on server ? why it was not reflecting
new date.

Anyway main thing is we have  ecrm application software
which connect oracle database with the help of odbc.

since we have changed database server date as well as
client nt machine date(ecrm software on the client-nt machine),
default date in the ecrm software is showing the
default date only ie '01-jan-2000'. i don't know why ?

it has to show new date format ie '01/01/2000' within ecrm
application

does any date format odbc setting ?

kindly let me know.

i hope you understand my problem.

waiting for your reply asap

Bye...

      and we said...
See

http://osi.oracle.com/~tkyte/Misc/NLSDateFormat.html
for the reason and a possible solution using an on-logon trigger
in the database.

Be VERY careful changing the format from

dd-mon-rr

(which is the default, not dd-mon-yyyy as you have) to

dd/mm/yyyy

As that is 1 byte longer then the other format and your off the
shelf software package might have a problem with this unexpected
size.  Also -- they may be expecting the default date format to
be in place.   Changing the database date format on them may not
work.  You should contact them for advice as well.
December 04, 2000 Nerissa -- Thanks for the question regarding "How
      to deploy application written in Oracle JDeveloper 3.1.1.2", version
      JDeveloper 3.1.1.2

      You Asked
Some of my questions may be trivial however I would greatly
appreciate if you could please give me some guidance and
direction on the following:
1)Application developed in JDeveloper 3.1.1.2 - Can they be
deployed in the web directly from Oracle8i release 8.1.6
(running On Compaq Unix) without using another layer of
application such as OAS or WebDB as per Oracle Datasheet?
2)  How do we deploy/activate JDeveloper developed applications
so that they could be accessed from the internet?
3)Is there any technical forum that are involved in discussion
on JDeveloper 3.1.1.2?  I would appreciate the URL address
please.

Our current development environment:
RDBMS: Oracle 7.3.4
platform: Compaq Unix (tru64)
O/S:   OSF1,  release V4.0
OAS:   4.0.8.1.0 Enterprise Edition (Oracle Application Server -
May be upgrading to the supported version shortly)using PL/SQL
cartridge only.
Oracle Developer/2000: version 1.3.2

Our Target environment:
(a) RDBMS: Oracle8i 8.1.6
(b) O/S:   Compaq Unix (tru64)
(c) Oracle Developer/2000: 1.3.2 (stay the same if possible
       otherwise move to Developer/2000 version 1.6)
(d) Development Tool (running in Windows NT and Win2000):
       JDeveloper 3.1.1.2 using JDK 1.2.2 (or JDK 1.1.8.) We are
restricted due to constraints of many clients/students if we use
JDK 1.3 i.e. browser version denpendency. JDK 1.3 needs Netscape
4.7 and higher or Internet Explorer 5.x.

We would like to build some forms/web pages that would interact
directly with our Oracle database.
Would our target environment be appropriate for a particular
job?

Your advice and comments are highly valued and looked forward
to. TIA.

Sincerely
Nerissa Paulo

      and we said...
1) Yes you can with Oracle8i release 3 (8.1.7).  See

http://technet.oracle.com/docs/products/oracle8i/doc_library/817_doc/addendum.817/a85455/introadd.htm#1001065
where you can read about the embedded servlet engine in the
database, the embedded JSP (java server page) in the database,
the embedded PLSQL gateway, and EJB support in the server.

This allows you to deploy the applications in the database in
much the same way you would using an application server.  The
database is an application server.

2) You would pick the technology most appropriate for you and
use it.  For example, you might choose to use JSP's to build
HTML based applications with dynamic content being provided by
small snippets of java embedded in HTML.

3) Yes, goto

http://technet.oracle.com/tech/java/
and choose the relevant technology -- then click on support to
join the message boards for that technology.

to build the forms -- I would probably use Developer, not
jDeveloper.  I would use jdeveloper with JSP's or servlets to
build the HTML based one.

December 04, 2000 D.P. -- Thanks for the question regarding "BACKUP
      ", version ORACLE 8

      You Asked
Sir
I want to make the backup process automated in NT platform.
and I want to you parallel server. Please let me know  where I
have to change in script in INIT.ORA .Is the parallel server
slow down the operations?

Please advice me.

Bye
D.P.Pattanayak

      and we said...
You should use a tool such as OEM (Oracle Enterprise manager) in
conjunction with RMAN (recovery manager) to automate your
backup.  There is no "init.ora" parameter to automate backups
but these two tools can do that.

OPS requires specialized hardware to operate.  As to whether OPS
slows things down -- it totally depends on what and how you are
using it.  If you are using 8.1.6 for example and choose to use
OPS for high availability only -- it has a special "high
availability" configuration that allows it to provide HA systems
without impacting online operations at all.  If you want to
concurrently read/write any piece of data from any node -- you
may have some performance considerations (which can be solved by
application design).

I would suggest reading:

http://technet.oracle.com/doc/oracle8i_816/paraserv.816/a76968/toc.htm
to get a better understanding of OPS.

December 04, 2000 Vinod -- Thanks for the question regarding "How
      can we stop Oracle DBA a/c (including SYS/SYSTEM) to see other a/c's
      DATA", version 8.1.6/8.1.7

      You Asked
Hi Tom,

we don't want to allow Oracle DBA a/c to see the other ORacle database a/c's
data. Could you help me to solve this problem?
I am using Oracle 8.1.6 and 8.1.7.
+
Thanks,

Vinod

      and we said...
Well, the DBA must be able to see that data -- else they could not back it up!

You can use encryption to selectively encrypt data in the database.  This would
prevent the dba from seeing cleartext data -- they would just be able to see the
encrypted data.

See

http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:dbms_obfuscation
for more info on that.

You would need to keep the "keys" private and secure in some fashion.  If the
DBA gains access to the key -- they can decrypt the data themselves (and don't
lose the keys either!)

December 04, 2000 -- Thanks for the question regarding "Accessing
      datatypes across users .", version 8.1.6.0.0

      You Asked
Hi Tom ,

How can grant access of a datatype which I created in one user
to another user . I understand datatypes cannot be granted like
other objects from one user to another user . Is there any
workaround available ? What I want is to create a datatype
centrally and let all users access it . Pls suggest .

Regds .

Pinaki

      and we said...
Yes you can.  If the user scott issues:

create type myTable as table of number;
grant execute on myTable to public;

then any other user can use the datatype:

  SCOTT.MYTABLE

in their applications anywhere.  Types referenced from other
schemas must be qualified with the owner name.  You cannot
create a synonym for a type.
December
      04, 2000 tian -- Thanks for the
      question regarding "about the OCI", version 8.1.5

      You Asked
Tom,I am anxious to develop a application related to the
OCI of Oracle ,which are expected to act as such function
to easily and freely access the LOB column from a table .
Iam also new to use VC++,the samples which is accopanied with
Oracle815,dont not include the detailed header file.So I cant
compile these samples successful(\oraclehome\ord\img\demo\
imdemo.c and \oraclehome\ord\img\demo\vc\,and .\oci\samples\
cdemmolb*.c).?
the second question is how to programatically find all the
tables that are owned by a certain account ?

                 expecting your guide!

      and we said...
All of the header files are there.  $ORACLE_HOME\oci\include
must be in your include path -- thats where oci.h and all of the
others are to be found.

To programatically find all of the tables owned by someone you
would start with the query:

 select table_name from all_tables where owner = :x

and you would proceed to allocate a statement for it, parse it,
bind the owner name you wanted to see, execute it, fetch from it
and close it (the statement).
December 04, 2000 Kenneth -- Thanks for the question regarding
      "Recovery", version 7.x , 8.x

      You Asked
Hi Tom,
I have a case study

day 1 - cold backup
day 2 - normal activities on the db
day 3 - normal activities on the db
day 4 - add  a datafile on a new tablespace
day 5 - normal activities on the db
day 6 - new datafile gets deleted. ( time noted )
day 7-  archives on tape.

Can you inform me the correct steps to
perform a recovery ?

Apart from the book of Oracle Backup and Recovery from Rama
Vellupuri, can you suggest me some literature or sites where
real life recovery  cases study are avaliable.
Thanks,
Kenneth

      and we said...
See

http://technet.oracle.com/doc/oracle8i_816/server.816/a76993/recoscen.htm#14480
for the answer to the question.  Basically -- we'll stop
recovery when we hit that datafile, ask you to name it and put
it in the correct place, and then resume recovery.

Apart from the above reference document, see

http://technet.oracle.com/doc/oracle8i_816/server.816/a76993/toc.htm
for more info.
December 04,
      2000 -- Thanks for the question
      regarding "long query", version 8.1.6

      You Asked
Tom:

if for my database, the data_block_size is 8k, then the max
number of extents for any segment is 8k , no matter what my
setting for maxextents. am i right?

I try to run query on Oracle8i Administrator's guide page
19-33,19-34.
it take me almost forever.what's potential problem?
can you run it in your machine and see how long it takes?
(it return several rows and then frozen for a long time and then
return some others
and frozen ...)

some of tablespace i use is local_managed, so next_extent in
dba_tables is null, but it still make no sense to take such
a long time.

Regards

      and we said...
No, the max extents is unlimited as of Oracle7.3.  The
restriction on the number of extents/segment based on the block
size is gone.

I filed a bug about that query a while ago.  It is fixed in the
8.2 doc. Not only does the query take a really long time to
execute, it is not correct in its results...  Here is some of
the text of the doc bug:

...
the "or seg.extents = seg.max_extents or seg.extents = 8192"
would need to be
pushed into the OR'ed together larger predicates to be correct,
what I mean is
it should be 4 or's with:

 WHERE ((seg.segment_type = 'TABLE'
      AND seg.segment_name = t.table_name
      AND seg.owner = t.owner
      AND ( seg.extents = seg.max_extents or seg.extents = 8192
or
            NOT EXISTS (SELECT tablespace_name
                          FROM dba_free_space free
                          WHERE free.tablespace_name =
t.tablespace_name
                            AND free.bytes >= t.next_extent) ) )

else every time a row was found with max_extents = extents -- we
would get
"count(*) from dba_tables" * "count(*) from dba_indexes" * ....
copies of it
(in other words -- lots of them!)

the problem with the above query is 2 fold:

o it does not run in anything resembling a "reasonable amount of
time"
o it returns a cartesian product of millions of rows IF there is
an extent
that is the max extent (in other words, if it finds the rows its
looking for
-- it gives the wrong answer)

Suggest the query be written as:

select seg.owner, seg.segment_name,
      seg.segment_type, seg.tablespace_name, seg.next_extent
  FROM sys.dba_segments seg
 where seg.segment_type in ( 'TABLE', 'INDEX', 'CLUSTER',
'ROLLBACK' )
  and ( NOT EXISTS (SELECT tablespace_name
                      FROM dba_free_space free
                      WHERE free.tablespace_name =
seg.tablespace_name
                        AND free.bytes >= seg.next_extent)
        or
        seg.extents = least( seg.max_extents, 8192 )
      )
/

which gives the answer they were going for and executes very
rapidly
(comparitively)...

December 04, 2000 -- Thanks for the question regarding "initrans",
      version 8.1.6

      You Asked
Tom:

why shoud I worry about initrans? if it is not big enough
space will allocated from free space in block. so i don't need
to set a big size for initrans.
even the first time when a lot of user query data block is not
efficiency, the second time will be good anyway.

      and we said...
Initrans is needed is you use serializable mode transactions.
We retain a history of the transactions on the block -- but only
if inittrans is big enough.  If it is not big enough - you will
get "cannot serialize access" if you have lots of updates to the
same block over time.

Initrans is needed if you have lots of concurrent updates to a
block and there is not sufficient space to grow the list.  Then
people will wait.

It is a tuning knob.  Most applications need not touch it.

Freelists on the other hand -- that is something you need to
concern yourself with.  Especially on segments with lots of
concurrent inserts/updates.  You can really speed things up by
setting freelists higher.
December
      05, 2000 Francois -- Thanks for the
      question regarding "Rownum question", version version 8

      You Asked
Ive got a problem with rownum

The problem is.....when im running my sql statment, ive got 3000
result from my select....i need just 50..

select a.name, b.code, sum(c.salary)
from   employee_v a, code_table b, salary_table c
where  a.id = b.employee_id
and    rownum < 51
and    code_name <> 'franck'
and    c.id = b.salary_id
and    to_date(c.code_date, 'DD-MON-RR') between '01-JAN-99' and
'01-JAN-00'
group by a.name, b.code, sum(c.salary)
order by a.name, b.code

The first table is a view from a table.

Can you help me on this.

      and we said...
In Oracle8i, release 8.1 and up:

select *
  from (
select a.name, b.code, sum(c.salary)
from   employee_v a, code_table b, salary_table c
where  a.id = b.employee_id
and    rownum < 51
and    code_name <> 'franck'
and    c.id = b.salary_id
and    to_date(c.code_date, 'DD-MON-RR') between '01-JAN-99' and

'01-JAN-00'
group by a.name, b.code, sum(c.salary)
order by a.name, b.code
)
where rownum <= 50
/

will work.  In 8.0 and before, the order by will NOT work in the
subquery.  The group by  by itself will *typically* sort the
data -- but it MIGHT NOT.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:247014750272
for more info on that.

December 05, 2000 Norman -- Thanks for the question regarding
      "Indexes", version Oracle 8i

      You Asked
Sir,

You have replied that the optimizer will see the index is
existing and will use it if feels that it will improve the
query. Do I have to put the same columns that I defined during
the creation of my index and in the where clause of my select
statement? Or even if I didn't use the same columns it will
still read the index? Pls. Help Thanks.

      and we said...
It will only use the index if it makes sense.

select count(*) from T;

might use the index in a fast full scan rather then read the
entire table (if the index is on a non-null column).

select * from t order by x ;

might use an index on X to sort the data (might not, probably
won't unless you are using first_rows optimization).

selectg * from t where x = 5;

would almost certainly (in most cases) use an index on X (given
that x was "selective")
December 05,
      2000 Sundar -- Thanks for the question
      regarding "Tablespace Quota", version 8.1.6

      You Asked
Hi Tom,
 Thanks for your earlier answers abt OPS.
How to give quota unlimited for a tablespace and whether it is
possible to create a initial extent of more than 2Gb running on
Oracle 8.1.6.We encountered this problem when we tried to create
a table with a initial extent of 2048M in  a tablespace of size
15Gb( 3 datafiles each of 3 Gb size).The DB_BLOCK_SIZE for our
database is 8192
Thanks in Advance...
Regs
Sundar

      and we said...
Alter user X quota unlimited on Tablespace;

is how to give someone unlimited quota on a tablespace.

The maximum extent size, regardless of block size or anything,
is 2 gig.

You do not need to mimize extents.  It is OK to have lots of
them, lots and lots of them.


Subject | Article | Last Updated (East coast time)
Oracle 8 i | article only | Dec 10, 2000 02:51 pm
Exclude mode | article only | Dec 10, 2000 03:44 pm
Discrete transaction | article only | Dec 10, 2000 04:40 pm
lots of same row at v$open_cursor view | article only | Dec 10, 2000 05:09 pm
open cursor big enough | article only | Dec 10, 2000 05:13 pm
FFS and index join | article only | Dec 10, 2000 05:19 pm
Use or not usr Bind Variable | article only | Dec 10, 2000 05:21 pm
cost of plan | article only | Dec 10, 2000 05:22 pm
desc | article only | Dec 10, 2000 06:02 pm
tablespace transport | article only | Dec 10, 2000 06:06 pm
Problem While Connecting to ORACLE from JAVA | article only | Dec 11, 2000 08:59 am
ROWID Problem | article only | Dec 11, 2000 09:03 am
To sort query output in Ascending and Descending order | article only | Dec 11, 2000 09:21 am
Doubts & Software | article only | Dec 11, 2000 09:27 am
execute operating system command from pl/sql | article only | Dec 11, 2000 10:10 am
Catching Function's/Procedure's Out Parameter in another Porcedure / anothere function. | article only | Dec 11, 2000 10:44 am
NOT NULL constraint - table level | article only | Dec 11, 2000 10:53 am
To Calculate size of the Index in bytes | article only | Dec 12, 2000 02:28 am
How to avoid user -deleting Records & Dropping Tables ! | article only | Dec 12, 2000 02:34 am
How to find the Deafult Tablespace of a already Existing User ! | article only | Dec 12, 2000 02:37 am
User access control in distributed environment. | article only | Dec 13, 2000 10:42 am
Writing a Procedure | article only | Dec 13, 2000 12:28 pm
Bitmap Indexes | article only | Dec 13, 2000 12:36 pm
Import Database to new instance | article only | Dec 13, 2000 12:42 pm
Getting UNIX environment variable in PL/SQL | article only | Dec 13, 2000 04:58 pm
Session Logs | article only | Dec 13, 2000 05:07 pm
Compiling forms 5.0 in developer 6.0 | article only | Dec 13, 2000 06:03 pm
adding 1 year to current date | article only | Dec 15, 2000 10:01 am
Datafile usage and applying a commit in other session | article only | Dec 15, 2000 10:13 am
Using SQLPlus commands in PL/SQL | article only | Dec 15, 2000 10:22 am
Chaning/altering the Partition key of a Partitioned Table | article only | Dec 15, 2000 10:25 am
Dynamic SQL | article only | Dec 15, 2000 02:31 pm
row(s) 1 - 32 of 32
December 10, 2000 Ray -- Thanks for the question regarding "Oracle 8 i", version Oracle 8 i
You Asked
What is Oracle 8 i?
and we said...
Oracle8i is the current release of Oracle -- the database.

There are:

Oracle7, latest version (and last) is 7.3.4.

Oracle8, lastest and last version is 8.0.6.

Oracle8i which had three releases.  There was Oracle8i, release 1 which was
version 8.1.5.  There was Oracle8i, release 2 which was version 8.1.6.  There is
currently Oracle8i release 3 which is version 8.1.7.

To see the differences between any of the above, goto:
http://technet.oracle.com/doc/oracle8i_816/server.816/a76962/toc.htm
and for a list of new 8.1.7 features, see:
http://technet.oracle.com/docs/products/oracle8i/doc_library/817_doc/addendum.817/a85455/toc.htm
...
December 10, 2000 -- Thanks for the question regarding "Exclude mode", version 8.1.6
You Asked
Tom:

Oracle 8i Administrator's guide page 10-8
To bring a datafile online or take it offline, you must have the
ALTER DATABASE
system privilege. You can perform these operations only when the
database is open
in EXCLUSIVE mode.

what's exclusive mode, it is corresponding to OPS, if my server
is not OPS,
i should have no problem to bring a datafile online or take it
offline at
ANY situation, am i right?
and we said...
EXCLUSIVE pertains to Parallel server, this is correct.  A
database mounted in exclusive mode (as determined by the
parallel_server init.ora parameter) is a non-OPS database.

If you are not running OPS, you should have no problems to bring
a datafile online/offline (other then normal issues such as the
file cannot be brought online since it doesn't exist, or needs
recovery or whatever...)
December 10, 2000 -- Thanks for the question regarding "Discrete transaction", version 8.1.6
You Asked
Tom:

SQL>create table test( a int, b int);
SQL>exec dbms_transaction.begin_discrete_transaction;
SQL>insert into test values(1,1);
then at another session:
SQL>insert into test values(2,2);
SQL>commit;
then return to original session
SQL>insert into test values(3,3);
SQL>select * from test;
1,1
2,2
3,3
SQL>commit;
successful.

Question:
1.suppose i can't see my change until commit, but i do.
2.never change an individual database block more than once per
transaction.i did and successful.
3.the only reason using discrete transaction imporve performance

is because no undo information generated, am i right?
and we said...
In Oracle8i -- unless you have:

_discrete_transactions_enabled=true

set in your init.ora (in prior releases no UNDERSCORE), discrete
transactions are not enabled.  the "begin discrete transaction"
is a "no-op".

If you enable that -- you'll get:

ERROR at line 1:
ORA-08175: discrete transaction restriction violated (ktcckv:
trying to CR post-change block)

when trying to read that block.

Discrete transactions are being obsoleted.  I would recommend
against using them.
December 10, 2000 -- Thanks for the question regarding "lots of same row at v$open_cursor view", version 8.1.6
You Asked
Tom:

  1* select * from v$open_cursor
test>/

SADDR           SID USER_NAME                      ADDRESS
HASH_VALUE SQL_TEXT
-------- ---------- ------------------------------ --------
----------
-----------------------------------------------------------
DA34A238         31 DBSNMP                         D95DC54C
2501101467 select name from v$database
DA3457F8         22 DBSNMP                         D95DC54C
2501101467 select name from v$database
DA35AA38         63 SYSTEM                         D8DB9678
4065929129 select * from v$open_cursor
DA341E38         15 SYS                            D92B7610
2252205219 SELECT VALUE FROM V$OPTION WHERE UPPER(PARAMETER)=:1
DA341E38         15 SYS                            D92B7610
2252205219 SELECT VALUE FROM V$OPTION WHERE UPPER(PARAMETER)=:1
DA341E38         15 SYS                            D92B7610
2252205219 SELECT VALUE FROM V$OPTION WHERE UPPER(PARAMETER)=:1
DA341E38         15 SYS                            D92B7610
2252205219 SELECT VALUE FROM V$OPTION WHERE UPPER(PARAMETER)=:1

why so many exactly same rows in v$open_cursor views?
and we said...
This just means that SYS has run some procedure/program that has
this query in it and we have four cached open cursors on it.  It
is easy to reproduce by just copying a procedure and giving it a
different name -- causing plsql to execute the same exact query
but have 2 distinct cursors that point to it.  There is only 1
query in the shared pool, whatever sys is running simply has
more then 1 cursor open on it.

Here is an example that shows this in action:

sys@TKYTE816> create or replace procedure p1( p_parm in varchar2
)
  2  as
  3  begin
  4      for x in ( select value
  5                   from v$option
  6                  where upper(parameter) = p_parm )
  7      loop
  8          null;
  9      end loop;
 10  end;
 11  /

Procedure created.

sys@TKYTE816> create or replace procedure p2( p_parm in varchar2
)
  2  as
  3  begin
  4      for x in ( select value
  5                   from v$option
  6                  where upper(parameter) = p_parm )
  7      loop
  8          null;
  9      end loop;
 10  end;
 11  /

Procedure created.

sys@TKYTE816>
sys@TKYTE816> exec p1( null )

PL/SQL procedure successfully completed.

sys@TKYTE816> exec p2( null )

PL/SQL procedure successfully completed.

sys@TKYTE816>
sys@TKYTE816> select *
  2    from v$open_cursor
  3   where sid = ( select sid
  4                   from v$session
  5                   where audsid = userenv('sessionid'));

SADDR    SID USER_NAME ADDRESS  HASH_VALUE SQL_TEXT
-------- --- --------- -------- ---------- --------------------
08B2E6AC   7 SYS       09A3C454 3779958315 SELECT VALUE   FROM
                                           V$OPTION  WHERE UPPE
                                           R(PARAMETER) = :b1

08B2E6AC   7 SYS       09A3C454 3779958315 SELECT VALUE   FROM
                                           V$OPTION  WHERE UPPE
                                           R(PARAMETER) = :b1

08B2E6AC   7 SYS       09A271A8  971864655 select *   from v$op
                                           en_cursor  where sid
                                            = ( select sid

So, this is not unusual -- rather it is to be expected if SYS is
running something that caches cursors.

Note that these cursors might not really be OPEN!!  Running:

          select a.value, b.name
            from v$mystat a, v$statname b
           where a.statistic# = b.statistic#
             and a.statistic#= 3

in the session (or changing this to use other v$ tables to look
at any session) you can find out how many cursors are REALLY
open.  Open cursors may have cursors that are easily reopened as
opposed to really open as well.  If you have
session_cached_cursors set -- cursors will be cached for you.
December 10, 2000 -- Thanks for the question regarding "open cursor big enough", version 8.1.6
You Asked
Tom:

oracle8i design and tuning for performance page 19-16

To take advantage of additional memory available for shared SQL
areas, you may also need to increase the number of cursors
permitted for a session. You can do this by increasing the value
of the initialization parameter OPEN_CURSORS.

How can i tell my setting for open_cursors is big enough?
and we said...
If you never hit ORA-1000 and don't use session_cached_cursors
-- it is big enough.

Otherwise, if you use session_cached_cursors and find that the
count of truely open cursors:

sys@TKYTE816> select a.value, b.name
  2  from v$mystat a, v$statname b
  3  where a.statistic# = b.statistic#
  4  and a.statistic#= 3;

is very near that - you need more open_cursors.

I myself run with a value of at least 500-1,000.
December 10, 2000 -- Thanks for the question regarding "FFS and index join", version 8.1.6
You Asked
Tom:

what's different between Fast full scan and Index join
to me it is the same.
oracle8i designing and tuning for performance page 4-23 and 4-24
and we said...
Well, a FFS uses 1 index and an index join uses at least two.

A ffs will read a single index (instead of a base table) and
answer the query.

An index join will hash join 2 or more indexes together into 1
big index to avoid full scanning the base table.

These are useful when the base table is very wide and the
indexes are very skinny.  We would rather read 2 skinny indexes
then 1 big fat table.
Review & Followup
Rating: 5
INDEX FFS January 05, 2004
Reviewer: Nitin from India
This was very good excerpts to know how INDEX FFS and index join works

December 10, 2000 -- Thanks for the question regarding "Use or not usr Bind Variable", version 8.1.6
You Asked
Tom:

plan selected for query use bind variable and those not use
may be different.

So I think use it or not is depents on DATA.

for example , i have a table test ( a int);

0.01% of rows have values  1 for a
0.01% of rows have values  2 for a
....
0.01% of rows have values 99 for a

and
99.01% of rows have values 100 for a;

then if i have query
select * from test where a= (anything between 1 to 99)
then it is better for me to use bind variable.

but if my query is
select * from test where a=100
then it is better not use.
and we said...
Correct -- as long as you also have collected histograms for the
column(s) involved as well.  If you do not have histograms, the
CBO will not know that 99% of the data has the value 100 -- it
will think that each row points to about 1% of the data and
would use the index even for 100.
December 10, 2000 -- Thanks for the question regarding "cost of plan", version 8.1.6
You Asked
Tom:

system>@?/rdbms/admin/utlxpls

Plan Table
-----------------------------------------------------------------
|Operation              | Name | Rows | Bytes| Cost|Pstart|Pstop
-----------------------------------------------------------------
|SELECT STATEMENT       |      |   14 |  462 |   1 |      |
| FILTER                |      |      |      |     |      |
|  TABLE ACCESS FULL    |EMP   |   14 |  462 |   1 |      |
|  MERGE JOIN CARTESIAN |      |   20 |   40 |   5 |      |
|   TABLE ACCESS FULL   |DEPT  |    4 |      |   1 |      |
|   SORT JOIN           |      |    5 |   10 |   4 |      |
|    TABLE ACCESS FULL  |EMP   |    5 |   10 |   1 |      |
-----------------------------------------------------------------

why cost in subOperation can be smaller than parent operation?
I think parent is accumulate of child.
and we said...
No, the parent is not the total of the children. Each access method has a cost
based on many factors (what hints were used, size of table, sort area size, size
of SGA, etc etc etc).  Costs are assigned to individual pieces of a query plan
-- not in a hierarchy.  Then the overall cost of a query is computed from all of
these discrete values.
December 10, 2000 joel -- Thanks for the question regarding "desc ", version 8.1.5
You Asked
as you know to describe a table use desc <tablename>
in sql*plus however im am running it in a loop with
pl/sql lang. in the loop i am executing the desc command
but it gives me an error for it it seems that it dosnt
understand it
i appriciate your help
and we said...
desc is a sqlplus command, it is not a SQL command.

You could run a query:

select column_name,
       data_type,
       substr(
       decode( data_type, 'NUMBER',
               decode( data_precision, NULL, NULL,
                '('||data_precision||','||data_scale||')' ),
                   data_length),
              1,11) data_length,
       decode( nullable, 'Y', 'null', 'not null' ) nullable
from all_tab_columns
where owner = :owner
  and table_name = :tname
order by column_id
/

inside of the loop and use dbms_output.put_line() to print out
the results from PLSQL in sqlplus or svrmgrl.  Make sure to set
serveroutput on before using dbms_output.
December 10, 2000 Syed -- Thanks for the question regarding "tablespace transport", version 8.1.5
You Asked
hello,

Dear,

i wanted to transport one of my tablespace (of Oracle 8i)
 to some other database (of oracle 8i). So, frist i have to
check
whether my tablespace is selfcontained or not, for  that purpose
i ran the procedures followed below;

SQL> begin
  2  execute dbms_tts.transport_set_check('USERS','RBS',TRUE);
  3  END;
  4  /
execute dbms_tts.transport_set_check('USERS','RBS',TRUE);
        *
ERROR at line 2:
ORA-06550: line 2, column 9:
PLS-00103: Encountered the symbol "DBMS_TTS" when expecting one
of the following:
:= . ( @ % ; immediate
The symbol ":=" was substituted for "DBMS_TTS" to continue.

-------------------------------------------------------

  1  BEGIN
  2  PROCEDURE TRANSPORT_SET_CHECK('USERS,RBS',TRUE);
  3* END;
SQL> /
PROCEDURE TRANSPORT_SET_CHECK('USERS,RBS',TRUE);
*
ERROR at line 2:
ORA-06550: line 2, column 1:
PLS-00103: Encountered the symbol "PROCEDURE" when expecting one
of the following:
begin declare exit for goto if loop mod null pragma raise
return select update while <an identifier>
<a double-quoted delimited-identifier> <a bind variable> <<
close current delete fetch lock insert open rollback
savepoint set sql execute commit forall
<a single-quoted SQL string>
The symbol "PROCEDURE" was ignored.

can any body help me to correctly run these procedures.

thanks,

mannan
mannanh@usa.net
and we said...
In sqlplus, execute (or exec for short) is a special command.
It is not a PLSQL command to run a procedure (although you can
execute immediate 'some string' to dynamically run some sql in
plsql with Oracle8i).

You would either:

SQL> exec dbms_tts.transport_set_check( 'USERS,RBS', true );

of

SQL> begin
   >   dbms_tts.transport_set_check( 'USERS,RBS', true );
   > end;
   > /

(note the TS_LIST is a single parameter -- not 2 as you have
it).

Also -- I cannot imagine why you would want to transport a
rollback segment (RBS)???

Also, DBMS_TTS typically does not have a public synonym, you may
have to issue SYS.dbms_tts.transport_set_check.  If you get
"undefined" -- you will need to have execute on that package
granted to you.  You will have execute on it if you have the
EXECUTE_CATALOG_ROLE role.
December 11, 2000 Khushru -- Thanks for the question regarding "Problem While Connecting to ORACLE from JAVA", version 8.1.6
You Asked
Dear Tom,

We are using ODBC to develop JAVA based applications. When
connecting to ORACLE thru ODBC we tried both the drivers on that
is supplied by MICROSOFT and the other supplied by ORACLE.

Many a times when our queries have a semi colon as a query
delimiter we get an error of "Unknown Character". Can you please
explain when and how is the query delimiter required when
passing a query thru ODBC to ORACLE
and we said...
The semi colon is not a query delimiter.

The semi colon might be used by some environments such as
SQLPlus which will read UNTIL it sees a semi-colon at the end of
a statement and then will run it.  So, for example:

SQL> select * from dual;
....
SQL> select * from dual
  1> /
....

both work -- sqlplus will see the word select and goto the
semi-colon or slash to run the command.  It does NOT include the
semi-colon in the command.

The semi-colon is used in PLSQL to terminate statements so that:

SQL> begin
  1>    update t set x = 5;
  2>    commit;
  3> end;
  4> /

includes semi-colons but they are part of the LANGUAGE, not
command separators per-say.

In general, you will not use semi-colons in any sql statement
unless it is written in PLSQL -- and then it is not a query
delimiter, but rather the end of a statement (eg: like
x := x+5;
)
December 11, 2000 Archa -- Thanks for the question regarding "ROWID Problem", version 8.1.6
You Asked
Dear Tom,

While writing a query to retrieve rowids we many a times get
symbols like + / in the ROWID. To the best of my knowledge the
only allowable character in ROWID are 'A' to 'F' and '0' to '9'

Are these characters now going to be a part of ROWID
The followin is the Result

ROWID                SKILL_ID

------------------ ----------

AAAC4VAALAAAAAXAA3          6

AAAC4VAALAAAAAXAA4         70

AAAC4VAALAAAAAXAA5          8

AAAC4VAALAAAAAXAA6          8

AAAC4VAALAAAAAXAA7        224

AAAC4VAALAAAAAXAA8          6

AAAC4VAALAAAAAXAA9          8

AAAC4VAALAAAAAXAA+          4     ----- Problem

AAAC4VAALAAAAAXAA/          0     ----- Problem
AAAC4VAALAAAAAXABA          5

AAAC4VAALAAAAAXABB        137

also the query that i write using these rowids give proper
results

Thaning you in advance.

Archa
and we said...
These are to be expected.  Since version 8.0 of Oracle, rowids
have been encoded using base64 encoding.  base64 allows for
characters:

A-Z
a-z
0-9
+
/

in the rowid.  If this is giving you a problem on the web where
both + and / are special characters, simply use a function such
as:

create or replace function urlencode( p_str in varchar2 )
return varchar2
as
    l_tmp   varchar2(12000);
    l_len   number default length(p_str);
    l_bad   varchar2(100)
            default ' >%}\~];?@&<#{|^[`/:=$+''"' || chr(10);
    l_char  char(1);
begin
    if ( p_str is NULL ) then
        return NULL;
    end if;

    for i in 1 .. l_len loop
        l_char :=  substr(p_str,i,1);
        if ( instr( l_bad, l_char ) > 0 )
        then
            l_tmp := l_tmp || '%' ||
                       to_char(ascii(l_char), 'fm0X');
        else
            l_tmp := l_tmp || l_char;
        end if;
    end loop;

    return l_tmp;
end;
/

on the rowid to encode it.
December 11, 2000 Bhavesh -- Thanks for the question regarding "To sort query output in Ascending and Descending order", version 4.0.8.2
You Asked
Hi Tom,
     Thanks for all your previous help in past. No words of
thanks are suffice for the help you are providing to Oracle
users. I have a query from OAS this time. In fact I have written
the following procdeure in OAS.

CREATE OR REPLACE PROCEDURE show_employee (sequence in VARCHAR2
DEFAULT 'ENAME')
AS
   row_count       INTEGER := 0;
   eno             NUMBER(4);
   enam            VARCHAR2(10);
   ejob            VARCHAR2(9);
   ehire           DATE;
   esal            NUMBER(7,2);
   counter         NUMBER := 0;
   TYPE rc         IS REF CURSOR;
   l_cursor        rc;
   sql_stmt        VARCHAR2(2000);
BEGIN
   sql_stmt := 'SELECT EMPNO, ENAME, JOB, HIREDATE, SAL  FROM
   Emp ORDER BY '|| sequence;
OPEN l_cursor FOR sql_stmt;
    LOOP
       FETCH l_cursor INTO eno, enam, ejob, ehire;
       EXIT WHEN l_cursor%NOTFOUND;
       row_count := row_count + 1;
       HTP.BODYOPEN(Null, 'alink=#0000FF link=#0000FF
vlink=#0000FF');
              IF row_count = 1 THEN
                 HTP.P('<center>');
                 HTP.TABLEOPEN('BORDER');
                 HTP.TABLEROWOPEN('CENTER', 'CENTER', NULL,
NULL,
              'bgcolor=#FFCC00 bordercolor=#3F2A55');
                 HTP.TABLEDATA(HTF.BOLD(HTF.ANCHOR('
http://myserver.com/test/show_employee'||'?sequence='||'empno'

'No.')));
                     HTP.TABLEDATA(HTF.BOLD(HTF.ANCHOR('
http://myserver.com/test/show_employee'||'?sequence='||'ename'

'Name')));
                 HTP.TABLEDATA(HTF.BOLD(HTF.ANCHOR('
http://myserver.com/test/show_employee'||'?sequence='||'job'

'Job')));
                 HTP.TABLEDATA(HTF.BOLD(HTF.ANCHOR('
http://myserver.com/test/show_employee'||'?sequence='||'hiredate'
 'Date
Hired')));
                 HTP.TABLEROWCLOSE;
              END IF;
                 HTP.TABLEROWOPEN;
              HTP.TABLEDATA ( HTF.ANCHOR('
http://myserver.com/test/detail_employee'||'?inemployee='||eno
 eno));
                 HTP.TABLEDATA ( enam);
                 HTP.TABLEDATA ( ejob);
                 HTP.TABLEDATA ( ehire);
                 HTP.TABLEROWCLOSE;
              counter := counter + 1;
    END LOOP;
    CLOSE l_cursor;
    HTP.TABLECLOSE;
    HTP.P('</CENTER>');
    HTP.BODYCLOSE;
    IF row_count = 0 THEN
       RAISE NO_DATA_FOUND;
    END IF;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
       HTP.NL;
       HTP.P('There is no data available currently ');
    WHEN OTHERS THEN
       HTP.P('<CENTER>');
END;
/

This procedure simply lists the employee number, name, job,
hiredate, salary from the table and the header of the table
serves as a url which when clicked sorts the table based on that
particular field in ascending order. Now I have two queries
regarding the same.
1. How can I make the above procedure to work as a flip flop. I
mean if I click the employee number field for the first time it
orders the table in ascending order of employee number and if I
click for the second time the same table gets sorted on employee
number but this time in descding order.
2. When I click the particular heading on the table the url gets
listed on the address bar. Can we prevent this from getting
displayed on the address bar.
Thanks in advance.
Best Regards

Bhavesh
and we said...
1) you'll need to add another parameter --

p_asc_desc in varchar2 default 'asc'

Then, create the query as:

'SELECT EMPNO, ENAME, JOB, HIREDATE, SAL  FROM
   Emp ORDER BY '|| sequence || ' ' || p_asc_desc;

In that fashion, it'll default to ASC as it does now and when
you call it from existing code -- they do not have to supply a
value for it (so this will not break any existing code).

2) you would need to use java script to catch the click on the
link and POST a form, instead of using a plain ol' <a href=...>
tag.  Your java script will fill in a form and post it.  When
you use POST, the data does not appear in the URL bar.

For example, let's say you have a page like this:

<SCRIPT LANGUAGE="JavaScript1.1">
<!--
function doSubmit( r )
{

 document.forms[0].p_request.value = r;
 document.forms[0].submit();
}
//-->
</SCRIPT>

<HTML>
<HEAD>
<TITLE>Demo</TITLE>
</HEAD>

<FORM ACTION="http://aria.us.oracle.com/wa/webdemo/owa/demo"
METHOD="post" name="my_form">
<INPUT TYPE="hidden" NAME="p_session_id" VALUE="567">
<input type="hidden" name="p_request">

<A HREF="javascript:doSubmit('123')">click me to pass 123</A>
<br>
<A HREF="javascript:doSubmit('789')">click me to pass 789</A>

</FORM>
</BODY>
</HTML>

and a procedure like this:

create or replace
procedure demo( p_session_id in varchar2, p_request in varchar2
)
as
begin
  htp.p( 'session id = ' || p_session_id );
  htp.br;
  htp.p( 'request = ' || p_request );
end;
/

If you run that page and click on the different links, you'll
see that is passes 2 values and they do not appear in the URL
bar.
December 11, 2000 Prem -- Thanks for the question regarding "Doubts & Software ", version Oracle 8.1.5.0.0
You Asked
I have some doubts

1. In PL/SQL the syntax says create or replace procedure name
is|as, I would like to know what is the diffrence between using
"IS" and "AS" in creating procedures and functions.

2. How to enforce constrains in Object Tables.

3. I would like to upgrade my database to 8.1.7 because this
version supports EJB (Entity Beans). I am working on Intel
Solaris 2.7, where can I get a trial download for my platform, I
have went through entire OTN site, it is provided with Sparc
version Solaris but not Intel version, But the documents are
available for Intel version.

Please guide me to whome I have to ask if these questions are
not relevant to you.

Thanks
prem
and we said...
1) no difference.  Here is how I use it:

create or replace procedure foo
as
begin
    .....

and in a package, I would use:

create or replace package demo
AS
   procedure foo
   IS
   begin
       .....

I use the AS where it "sounds" more correct and IS where it
sounds more correct.  otherwise, they are the same.

2) as you would for any table.  See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76976/adobjmng.htm#1002713
which is the section on "constratins for object tables" in the
Oracle8i Application Developer's Guide - Object-Relational
Features

3) 8.1.7 is not yet available on intel solaris as of this
writing (december 11'th, 2000).
December 11, 2000 rams -- Thanks for the question regarding "execute operating system command from pl/sql", version 8i with linux
You Asked
Hai Tom
  I want to execute linux os commands from pl/sql.
if possible please give me good suggestion with examples.
How to use ftp process in pl/sql and How to
solve RPC error also . I am awaiting for your reply.

Thanks and Regards
Rams.R
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:150612348067
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:952229840241
for methods on how to run system commands from inside the
database.

As for the RPC error -- that would be due to "mis configured"
tns or listener.ora files.

You need to setup the listener.ora and tnsnames.ora file for
extprocs.

Here is a sample listener.ora file:

----------------------------------------------------
LISTENER =
  (ADDRESS_LIST =
    (ADDRESS=(PROTOCOL=IPC)(KEY=oracle81.world))
    (ADDRESS=(PROTOCOL=TCP)(Host=sheepdog)(Port=1521))
  )
SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME=sheepdog.us.oracle.com)
      (ORACLE_HOME= /d01/home/oracle81)
      (SID_NAME = oracle81)
    )
    (SID_DESC =
      (SID_NAME = extproc)
      (ORACLE_HOME = /d01/home/oracle81)
      (PROGRAM = extproc)
    )
  )
STARTUP_WAIT_TIME_LISTENER = 0
CONNECT_TIMEOUT_LISTENER = 10
----------------------------------------------------

The important things in the listener file for extprocs:

o ADDRESS=(PROTOCOL=IPC)(KEY=oracle81.world))

set up an IPC based listener.  remember the value of the KEY=
(you can make it
whatever you want, just remember what it is)

o (SID_DESC=(SID_NAME=extproc)

remember that SID_NAME, call it extproc.

The next file is the tnsnames.ora file, it needs an entry like:

---------------------------------------------------
extproc_connection_data =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = IPC)(KEY = oracle81.world))
    (CONNECT_DATA = (SID = extproc))
  )
--------------------------------------------------

Important things:

o (ADDRESS = (PROTOCOL = IPC)(KEY = oracle81.world))

should be the same as was in the listener.ora file....

o (CONNECT_DATA = (SID = extproc))

the sid must match the sid in the (SID_DESC=(SID_NAME=extproc)
from the
listener.ora....

Also, if your sqlnet.ora specifies some default domain, it needs
to be on the
tnsnames entry.  So if you have a sqlnet.ora with stuff like:

sqlnet.authentication_services=(none)
names.directory_path = (TNSNAMES, HOSTNAME)
names.default_domain = world
name.default_zone = world
automatic_ipc = off

in it, that would be extproc_connection_data.world -- not just
extproc_connection_data.

December 11, 2000 Rajesh -- Thanks for the question regarding
      "Catching Function's/Procedure's Out Parameter in another Porcedure /
      anothere function.", version 8i

      You Asked
1. I declare a out parameter of varchar2 type along with return
type as raw in a function. I would like to capture the
outparameter value in that procedure to insert it into a talbe's
field. How do I do that? Is there a way?

Ex:

--Function.

create or replace function moretrial2(er out varchar2) return
raw as
j raw(16);
begin
      select sys_guid() into j from dual;
      return j;
      er:='Success';
end;

--Procedure.

 create or replace procedure gh(de raw default null,cd
varchar2,gr varchar2)as
 wrong  exception;
 ax        raw(16);

 begin
          if cd like 'Update' then
                   if de is not null then
                           update te set a=gr where b=de;
                   elsif de is null then
                           raise wrong;
                   end if;
           else

    insert into te values( outparam value of function moretrial2
,moretrial2());

--However second insert is nothing but return type raw and it is

--producing the result successfully. The question is how to
--capture outparam  value of a function/procedure into another?

             end if;
           Exception
                   when wrong then
                           NULL;
 end;

      and we said...
You cannot call a function from SQL that has OUT parameters.

You would have to code something like:

   return_value := moretrial2( out_param );
   insert into te values ( out_param, return_value );

December 11, 2000 Orna -- Thanks for the question regarding "NOT
      NULL constraint - table level", version 8.0.6

      You Asked
Hi Tom,

Is there a logical reason why Oracle does not allow defining NOT
NULL constraints on table level - and only on column level ?

thanks
Orna

      and we said...
Because they can only be done on a single column -- things that
can only be done for a column are done at that level (eg: you
cannot specify a default at the table level either).

You can do the equivalent of a not null with a

check ( x is not null )

check constraint at the table level if you like.
December 12, 2000 Sudhanshu -- Thanks for the question regarding
      "To Calculate size of the Index in bytes", version 8.0.3

      You Asked
Hello sir,

I am trying to calculate size of the index in bytes. For this i
found one script to calculate the index size. But when i am
running this script No output is comming. When i checked the
reason i found that INDEX_STATS table is empty, which is used in
this script. The scripts is given below -

/* calculate the size of the index in bytes */
select XS.BLOCKS * VP.VALUE into nSize from INDEX_STATS XS,
V$PARAMETER VP where VP.NAME = 'db_block_size';

Can U tell me
Q1. How can i calculate the size of  the index in byte and what
%size of the table it will take?
Q2. Why above script is not working?

Waiting your quick response.

Thanks & regards
Sudhanshu Kulshreshtha
NIIT
INDIA
Email : 1. s_kulshreshtha@yahoo.com
        2. sudhanshuK@niit.com

      and we said...
See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:231414051079
for the easy way to get this type of information using a
stored procedure.  It is very fast as well.

The INDEX_STATS view is a dynamic view that is populated for one
index at a time only.  It gets populated right after an "analyze
index validate structure".  If you log out -- it'll be empty
again.  Only your session can see your row.
December 12, 2000 OP -- Thanks for the question regarding "How to
      avoid user -deleting Records & Dropping Tables !", version 8.1.5

      You Asked
Dear Tom,

Hi !

How are you Doing !

I have created one user P3 and this user has been granted
connect,resource previlege .

This user has all pevileges so that it can CREATE TABLES,
INSERT RECORDS,DELETE RECORDS AND DROP TABLES FROM THE
DATABASE .

Now this P3 user password has been given to 15 users in our
Team.

"I want now is that users who are logged in as P3 should
be able to create tables and Insert data into the Table
but should not be able to either delete or Drop the
Tables from the DATABASE "

What should I do to acheieve this ?

Thanks & Regards
OP

      and we said...
See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:385418740519
for how to prevent someone from dropping their own objects.
 A similar solution will prevent them from deleting from their
own tables as well -- put a DELETE trigger on each table.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:646423863863
for how you might automatically create the trigger on any
table created in this schema.  That example shows a GRANT but
the creation of a trigger would be done in the same fashion.

December 12, 2000 OP -- Thanks for the question regarding "How to
      find the Deafult Tablespace of a already Existing User !", version 8.1.5

      You Asked
Dear Tom,

Hi !

I have 5 users Existing in My database U1,U2,U3,U4,U5.

"I want to find out what is the DEFAULT and TEMPORARY
tablespace which have been assigned to U3 and How
much space is left in the respective Tablespace for
that User ?"

Thanks & Regards
OP

      and we said...
select username,
       default_tablespace,
       temporary_tablespace,
      ( select sum(bytes)
          from dba_free_space
         where tablespace_name = dba_users.default_tablespace
      )
 from dba_users
where username = USER
/

will get your that.
December 13,
      2000 Balaji -- Thanks for the question
      regarding "User access control in distributed environment.", version 8.1.5

      You Asked
Hi TOM,

I have submitted a question a week before, and i think for some
reason it didn't reach you.
Here is the question.

We have distributed databases from five different agencies
connected together and we have a common  application which query
all the databases. The application will connect to only one
database which is a common database, and talk to others using
db_link.
The application is developed using Active Server Pages.

We have to control the user access, depending upon which agency
he is from, and what is his designation etc...
And each agency has different set of requirements, agency a
would like to share some data to b, but not to c.....like wise.

Currently we have only one database user set up for this
application and we are multiplexing it through odbc....
And all the access control is done in ASP Scripts....

But we have a feeling this is not a scalable solution as we may
get more and more users and more agencies(databases).....

My question is will it good to control the access at the
database level itself. If yes how to implement it.
As we have multiple databases, if we need to give access to one
new user we have to create userid in all the databases.....

Any advises and directions higly appreciated...

      and we said...
Sounds like a perfect application for Fine Grained Access
Control:

http://osi.oracle.com/~tkyte/article2/index.html
Upon accessing a page, you would run a procedure to set an
application context.  This application context would contain the
identity of the end user.  You would supply the necessary
security policy functions to enforce your security requirements.

If you are using "connection pooling" that doesn't log out after
a request or otherwise does not reset the database state after
each page, you'll need to add a call to the plsql routine:

  dbms_session.reset_package;

before running any page -- a simple PLSQL call.

Why don't you read through that document referenced above and if
you have further questions -- feel free to follow up.
December 13, 2000 Sandra -- Thanks for the question regarding
      "Writing a Procedure", version SQLPlus 8.5.0.0

      You Asked
I am trying to create a procedure that counts the number of
licenses being used on our databases.  Then submit this
procedure onto the job queue.
I am using
select upper('&1') name, to_char(sysdate,'dd/mm/yy @
hh24:mi:ss') timestamp, sessions_current, sessions_highwater
from v$license;
I have been unsucessful in creating a procedure getting various
errors, the main one being sys.v$license no declared.
Can you please help?
Sandra

      and we said...
A procedure to do that would be:

create or replace procedure gather_data( p_name in varchar2 )
as
begin
   insert into your_log_table
   select upper(p_name), sysdate, sessions_current,
          sessions_highwater
     from v$license;
end;
/

You do not use &1 and so on in stored procedures -- they are
"macro" variables for SQLPlus.  In a procedure, we use formal
parameters (p_name is a formal parameter above).

And the owner of this procedure would need to have SELECT ON
V_$LICENSE granted to them by the user SYS.  This grant needs to
be directly granted to this owner, not via a role.

See

http://osi.oracle.com/~tkyte/Misc/RolesAndProcedures.html
for why that is.

December 13, 2000 Riju -- Thanks for the question regarding "Bitmap
      Indexes", version 8.1.6

      You Asked
The "Oracle8i Designing and Tuning for Performance" section on
Bitmap Index Restrictions says that bitmap indexes cannot be
used for referential integrity checking (see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76992/ch6_acce.htm#2511
.

However, a simple test shows that Oracle DOES inforce the
referential integrity on foreign keys. Whats going on?

Thanks in advance for your help.

Riju Saini

      and we said...
We do not enforce RI using indexes.  We may use a B*Tree
index to reduce the table locking that may take place during RI
checking that may otherwise take place.  An index is optional
and if it is a b*tree index -- we can use it to make this
operation better.

We cannot use a bitmap to do this as many rows are represented
in each bitmap entry and we need the b*tree which has one row
per key for locking.

We do not need an index to enforce RI, we can use a b*tree to
make it more efficient.

See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:292016138754
for further discussion.
December
      13, 2000 Brian -- Thanks for the
      question regarding "Import Database to new instance", version 7.3.3.0

      You Asked
I am having a problem importing an exported Oracle database on a
new machine.  I did the full export on one machine and want to
import it on a different machine to different instance name,
overwriting the existing database on the new machine.  I am
getting lots of PK messages and skipping tables messages.  What
am I doing wrong?

      and we said...
A full imp should be imported into a "clean" database.  It
imports everything -- SYSTEM owned objects and all.  It cannot
be used to overwrite an existing database with its data.

You want to erase the existing database and simply create a
minimal database to import fully into.
December 13, 2000 Srivatsa -- Thanks for the question regarding
      "Getting UNIX environment variable in PL/SQL", version 8.0.5.1.0

      You Asked
helo Tom

Good to see u back

I have a requirement of getting UNIX enviroment variable in
pl/sql.

Eg. ORACLE_HOME, HOME etc has certain path. I wish to use this
variable (or any other variable which i have defined in UNIX) to
retrieve in oracle so that i can use it

LEt me know if you can help me

bi

==srivatsa==

      and we said...
You can write an EXTPROC (external procedure) to do this and
make a call to the C function "getenv".  Bear in mind that this
will be the SERVERS environment -- never ever the clients (so
HOME for example, if set, would always be the HOME of the person
who started the database).

See

http://technet.oracle.com/doc/server.804/a58236/10_procs.htm#433731
for more information on external procedures.

December 13, 2000 Jana -- Thanks for the question regarding
      "Session Logs", version Oracle 7.3.2.2

      You Asked
Hi Tom;

Is there a table/view in Oracle that keeps track of
historical session info?  If not, do you know of a
script/query that can create and store this info. I
want to be able to keep session information by id,
duration, date etc.

Thanks in advance,

Jana

      and we said...
That sounds alot like auditing.  You need to enable auditing in
the database and then issue the statements to audit the actions
you want (in your case audit session probably).

http://technet.oracle.com/doc/server73x/SAD73/ch21.htm#toc165
has more information on this for 7.3.
December 13, 2000 habeebuddin -- Thanks for the question regarding
      "Compiling forms 5.0 in developer 6.0", version 6.0

      You Asked
Mr.Tom,

I have to upgrade developer/2000(2.1) forms as developer 6.0 for
that I need to compile the existing fmb(source files in the
developer 6.0 one by one. But this process is very time
consuming because I have to compile more than 400 fmb forms
files.  Please suggest me any other fast method or script to do
this.

Not: Please help how to write script for this.

Thanks & Regards....

      and we said...
if all of the forms are in a directory -- a simple command:

c:\> for %f in (*.fmb) do ifcmp60 module=%f userid=x/y

where .... are any other arguments you want, will compile all of
the forms for you.

December 15, 2000 Carl -- Thanks for the question regarding "adding
      1 year to current date", version 8i

      You Asked
I need to know how to add 1 year to a start date in this format
for example:
if the start date is December,15 2000 I would like to generate
the expiration date to be Deember 14 2001
thanks

      and we said...
Add 12 months and subtract 1 day:

SQL> select add_months( to_date('15-dec-2000'), 12 )-1
         from dual;

ADD_MONTH
---------
14-DEC-01

Review &
      Followup

      Rating: 5
Very
      Handy  October 16, 2002
Reviewer:  Jim

First impressions to get the next year might be
to add 365 days... with leap years that sure to bite you
at some stage, and who wants to get into a what a leap year
debate.

Add_months is cool

Thanks Tom

December 15, 2000 John -- Thanks for the question regarding
      "Datafile usage and applying a commit in other session", version 8.1.5

      You Asked
Hi Tom,

Kindly answere the following questions.

1. Tablespace PAY_TAB1 contains 4 datafiles of different size.
   When a user belongs to PAY_TAB1, creates a object in which
   datafile the objects will reside? [ Explain the order of
   using a datafiles belongs to a tablespace].

2. In what way the rollback segments are useful in recovery ?

3. Is it possible to apply a commit in other seesion to
   complete the transaction immediatly?[Instead of Killing a
   session]

4. What is the use of log file groups.[Not log files]

   Thanks in advance.

john

      and we said...
1) You are really asking "how are extents allocated for
objects".  This is covered in the server concepts manual:

http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c02block.htm#2846
there are 2 algorithms, one for locally managed tablespaces and
the other for dictionary managed.

SQLLDR gives you the ability, in direct path mode, to specify a
particular datafile.  As well, the ALTER table command gives you
the ability to manually allocate extents in specific files as
well.  Otherwise -- it is basically a "first fit" algorithm
(find the first chunk of space we can in the tablespace)

2) rollback segments are used to store UNDO information.  In the
event you decide to rollback your transaction, we access the
rollback segment to get the "before image" of the data you
modified.

During recovery -- REDO is applied to rollback segments and then
any UNCOMMITTED transactions (transactions that were active when
the system failed) are rolled back automatically using these
recovered rollback segments.  That is how rollback segments play
into the recovery process -- they are used to rollback any
active but uncommitted transactions that were in place during
the crash.

3) No, that session must commit.  Only it knows if it can commit
(because its transaction is at a point where a commit makes
sense).  Commiting another session would destroy the integrity
of the database.

4) we use log files in a circular fashion.  We must have at
least 2 groups with 1 member each to function.  The groups are
groups of members - we use multiple redundant members in group
to protect against the total loss of a redo log group.  We use
one group at a time (we write to one group at a time) and the
work recorded in that group must be checkpointed to the
datafiles before we can reuse that group again.
December 15, 2000 Navdeep -- Thanks for the question regarding
      "Using SQLPlus commands in PL/SQL", version 8.0.5.1.0

      You Asked
Tom,
Is there any way I can use SQLPLUS commands like SPOOL , set
etc. in pl/sql procedure.
My req. is that i want to create one spool file for each record
fetched in a cursor.

Thanks
Navdeep

      and we said...
No, sqlplus commands cannot be used in plsql.  You might find
UTL_FILE to be of use here.  It'll create a file on the server
however, not the client.  See

http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:744825627183
for an example.

Another way would be to have PLSQL write a SCRIPT that you
subsequently run, for example:

set serveroutput on size 1000000
set feedback off
spool tmp.sql

begin
    for x in ( select empno, ename from emp )
    loop
        dbms_output.put_line( 'spool ' || x.ename );
        dbms_output.put_line( 'prompt ' || x.empno );
        dbms_output.put_line( 'spool off' );
    end loop;
end;
/
spool off
@tmp

will create a file named after each employee with their empno in
it.
December 15, 2000 Krishna Mohan -- Thanks for the question
      regarding "Chaning/altering the Partition key of a Partitioned Table",
      version Oracle8i 8.1.6

      You Asked
Hi,
Here is what we are trying to do.
I have a table, say T1 which is partitioned using COL1 as partition key.
Now because of some design considerations we need to add COL2 to
partition key. How to change the Partition key of a table.
Looking forward to your reply.

And Thanx a lot for your time.

Regards,
Krishna Mohan

      and we said...
You need to rebuild the object as changing the partition key will physically
move many rows.

You can either use a CREATE TABLE AS SELECT or you could export the table, drop
it, create a new table with the new partitioning scheme and then reload it using
IMP with ignore=y (to ignore the object creation errors).  Using exp/imp would
cause all indexes, constraints, triggers and so on to be applied to the new
table (whereas with CREATE TABLE AS SELECT you would have to supply all of these
for the new table)
December 15,
      2000 Nishat -- Thanks for the question
      regarding "Dynamic SQL ", version sqlplus 2.3.4.0.0

      You Asked
I am using to_char(sTime,'DD-MM-YYYY HH24:MI:SS') in my select
statement, using space as a separator in the date format.
After executing this Dynamic SQL, when I investigated the S[]
for the select item name list, I am getting
to_char(sTime,'DD-MM-YYYYHH24:MI:SS') without the separator
between Date and Time.

How can I resolve this problem so as to have the literal string
of the format intact in the S[] array.

Thanxs in advance.

      and we said...
S[] is just the name of the column and the name of this column
is system generated.   The system generated name never includes
the spaces.

I am not aware of any method to achieve what you want short of
using a quoted identifier in the query itself to get the name
you want:

ops$tkyte@ORA8I.WORLD> column "DD-MM-YYYY HH24:MI:SS" format a50

ops$tkyte@ORA8I.WORLD> select
to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') "DD-MM-YYYY HH24:MI:SS"
  2    from dual
  3  /

DD-MM-YYYY HH24:MI:SS
--------------------------------------------------
15-12-2000 14:32:26

Note that a quoted identifier must be 30 characters or less.


Subject | Article | Last Updated (East coast time)
SQL QUERY WITH WHERE CLAUSE | article only | Dec 16, 2000 04:08 pm
shell script | article only | Dec 16, 2000 04:26 pm
Data Dictionary | article only | Dec 16, 2000 06:45 pm
Password expiration option | article only | Dec 16, 2000 06:49 pm
Transport Tablespace | article only | Dec 16, 2000 06:51 pm
change file attribute | article only | Dec 16, 2000 07:00 pm
NLS & import | article only | Dec 18, 2000 10:49 am
Does Oracle SQL Support Nano-Second ? | article only | Dec 18, 2000 11:22 am
N-tier Authentication and Authorization | article only | Dec 18, 2000 11:25 am
Shared Schema | article only | Dec 18, 2000 12:52 pm
A Curious Tripling of Data Length | article only | Dec 18, 2000 03:00 pm
Improving performance on Querying Nested tables | article only | Dec 18, 2000 07:59 pm
How to connect ORACLE server on unix using OCI by a client on another machine? | article only | Dec 18, 2000 09:00 pm
tkproff | article only | Dec 18, 2000 09:06 pm
Oracle Forms | article only | Dec 18, 2000 09:26 pm
How to compare char and varchar2 | article only | Dec 18, 2000 09:49 pm
Evaluate Expression | article only | Dec 19, 2000 09:07 am
Datatype Conversion | article only | Dec 19, 2000 09:35 am
can oracle rebuild function ro procedure | article only | Dec 19, 2000 09:36 am
Materialized view | article only | Dec 19, 2000 09:40 am
Forms on application server | article only | Dec 19, 2000 10:15 am
Net8, logon triggers and ATXs | article only | Dec 19, 2000 11:13 am
problems while installing oracle on my PC | article only | Dec 19, 2000 04:15 pm
LEGATO/RMAN BACKUP | article only | Dec 19, 2000 04:26 pm
Error in trigger creation | article only | Dec 19, 2000 04:37 pm
More Storage Questions | article only | Dec 19, 2000 04:44 pm
recieving emails | article only | Dec 20, 2000 09:25 am
Regarding Table operator in Collection. | article only | Dec 20, 2000 10:36 am
Executing Stored Procedures through SQLPLus from a batch command file | article only | Dec 20, 2000 10:53 am
iAS and OAS | article only | Dec 20, 2000 11:58 am
Adding to block in layout editor | article only | Dec 20, 2000 06:14 pm
enable help in sqlplus | article only | Dec 20, 2000 06:52 pm
truncating empty table generate ORA-02266: article only Dec 21, 2000 10:23 am
d2k with oracle | article only | Dec 21, 2000 10:33 am
reading data from a clob column | article only | Dec 21, 2000 10:52 am
Oracle 8.0.4 not recognize Oracle 8.1.6 exported "*,dmp" file. | article only | Dec 21, 2000 10:55 am
Execute a SQL Script in a Procedure PL/SQL | article only | Dec 21, 2000 11:38 am
Question related with CONTAINS ! | article only | Dec 21, 2000 11:42 am
ERROR: ORA-01489: result of string concatenation is too long | article only | Dec 21, 2000 02:13 pm
Synchronous/Asynchronous communication. | article only | Dec 22, 2000 10:10 am
Storing Data Instead of Table | article only | Dec 22, 2000 02:36 pm
What rows does ESTIMATE STATISTICS scan ? | article only | Dec 22, 2000 03:18 pm
row(s) 1 - 42 of 42
December 16, 2000 Hassan -- Thanks for the question regarding "SQL QUERY WITH WHERE CLAUSE", version Oracle 7
You Asked
I'm trying to run simple queries with WHERE clause restricting
the data being fetched from the server based on the specific
WHERE clause on date datatype columns, but every time I execute
the query there is no record retrieved although the record
exists in the table. For example

select ename,hiredate
from emp
where hiredate ='22-FEB-81';

and if I change the date format using the alter session command
the query works fine

why is that?
and we said...
It is due to the implicit date format conversion.

In Oracle7, the default date mask is dd-mon-yy.  that means that
'22-feb-81' is implicity the date/time:

22-feb-2081 00:00:00

The data in your database is probably 22-feb-1981.

You should always use a 4 digit year to avoid this sort of
confusion.
December 16, 2000 baksha -- Thanks for the question regarding "shell script", version oracle 8.1.5 on solaris
You Asked
Do you have a shell script which can find the archive
destination for a given instance and list the archived log
files in that directory, total space of the archive directory,
used space, available space of the archvie directory.

thank you very much
baksha maran
and we said...
Sure, something like this:

#!/bin/csh

##  The next line is ONE line -- don't wrap it!!
set x=`echo "select '++'|| value from v"'$'"parameter where name
= 'log_archive_dest';" | sqlplus / | grep
 '^++' | sed s'/^++//'`

echo Arch Dest = $x
echo Used Space:
du -k $x
echo Free Space:
df -k $x
echo Files found:
ls -l $x
December 16, 2000 Lijie -- Thanks for the question regarding "Data Dictionary", version Oracle 8.1.5
You Asked
Dear Tom,

Where can I find detail definitions of those Oracle base tables,
such as sys.CDEF$, sys.COL$?

Thanks

Lijie Geng
and we said...
You cannot, they are undocumented.  The only supported data
dictionary tables are the ALL_*, DBA_*, USER_*, and v$* tables.
December 16, 2000 Veronica -- Thanks for the question regarding "Password expiration option", version Oracle 8i
You Asked
Tom,

How can I set a certain period of time after which the user's
password will expire?
(I only know about

alter user XXX
identified by XXXX
password  expire;

but it's not what I need.)
Thanks!
Veronica
and we said...
You do this with profiles.  See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76956/secure.htm#2204
for an example.
December 16, 2000 Ramu -- Thanks for the question regarding "Transport Tablespace", version 8.1.7
You Asked
Hi Tom,
 I have a question regarding transport tablespace.  After the
initial checking the main step is to export the tablespace
metadata.  In our case let us assume that the export is done to
the expdat.dmp file. One thing that confuses me is that when the
import is done in the target database, in the options the name
of  the datafiles that reside in the tablespace are given.
There is no need to specify an option during the import that
lists the export file (expdat.dmp) that we exported the metadata
from the source database.  So, what is the significance of the
export in the first place.

Thanks,
Ramu.
and we said...
You must tell imp what file to use with the metadate.  It'll
default to expdat.dmp so if expdat.dmp exists when you imported,
it won't ask you.

The import command for a transportable tablespace import might
resemble:

imp file=expdat.dmp userid=demo2/demo2
          transport_tablespace=y "datafiles=c:\temp\demo2.dbf"

You can use the file= directive to use a file other then
expdat.dmp but you must have the metadata or it will not work.
December 16, 2000 Shelly -- Thanks for the question regarding "change file attribute", version 8i.1.6.0.0
You Asked
Hello: Tom
     I use solaris system 2.8. I write java code like this

import  java.io.*;

public class Chmod{

public static String unixChmod(String filename, String mode)
{
    String command[] = new String[3];
    String inputLine = new String();
    Process   aProcess;
    //fow window
  /*
  command[0] = "attrib";
    command[1] = "D:\\asp\\test.txt";
    command[2] = "-r";
  */
  //for unix
 /* command[0]="chmod";
  command[2] = "/export/home/scheng/file1";
    command[1] = "777";
*/

   command[0]="chmod";
   command[1]=mode;
   command[2]=filename; //read or write
  try {
    Runtime runtime=Runtime.getRuntime();

    aProcess = runtime.exec(command);

    InputStreamReader in = new
InputStreamReader(aProcess.getInputStream());
    BufferedReader inStream = new BufferedReader(in);

    inputLine = inStream.readLine();

    inStream.close();
    aProcess.destroy();

  }  catch
    (java.lang.NullPointerException e)
    {
      inputLine = "No input";
    }
    catch (java.io.IOException e)
    {
      inputLine = "Error occured";
    }
    catch(Exception e)
    {
      inputLine="no change";
    }
    return inputLine;
}
}

I make another main function to run this java class. It work
fine.
but I deploy to oracle database no problem. then publish it

CREATE OR REPLACE PACKAGE CHMOD AS
FUNCTION WINCHMOD (p0 VARCHAR2, p1 VARCHAR2) RETURN VARCHAR2
AS LANGUAGE JAVA
NAME 'Chmod.unixChmod(java.lang.String, java.lang.String) return
java.lang.String';
END CHMOD;

but when I call : select chmod.winchmod(filepath, '444') from
dual

nothing return back. file attribute didn't change at all.
I already set utl_file_dir to this directoy.

thank you for your time.

have a good day!
and we said...
Utl_file_dir has no effect on java code, it only controls
utl_file -- the PLSQL package.

See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:952229840241
It shows an example of running a HOST command from java in the
database with 8.1.6.  Specially, it shows that since you are
running in a "sandbox" of sorts -- you must grant priveleges to
this procedure in order to run commands.  These priveleges are
very fine grained -- in my example I granted the ability to run
the single program /usr/bin/ps.

If you didn't catch and ignore the exception, you would have
seen the error:

ops$tkyte@DEV816> exec dbms_output.put_line( chmod.WINCHMOD(
'/tmp/x.dat', 'a+rwx' ) )
BEGIN dbms_output.put_line( chmod.WINCHMOD( '/tmp/x.dat',
'a+rwx' ) ); END;

*
ERROR at line 1:
ORA-29532: Java call terminated by uncaught Java exception:
java.security.AccessControlException:
the Permission (java.io.FilePermission <<ALL FILES>> execute)
has not been granted by
dbms_java.grant_permission to
SchemaProtectionDomain(OPS$TKYTE|PolicyTableProxy(OPS$TKYTE))
ORA-06512: at "OPS$TKYTE.CHMOD", line 0
ORA-06512: at line 1

I think you will find printing out of the exceptions to be very
useful -- all i did was remove your try/catch block and let the
exceptions propagate on up.
December 18, 2000 Sarantos -- Thanks for the question regarding "NLS & import", version 8.0.4.0.0
You Asked
Hi!
I have installed ORACLE 8 Personal Edition on Windows 98 and i
want to import a DMP file. The DMP file is in EL9ISO8859P7
charset; so is my database's NLS_LANG entry in the registry.
However the nls_database_parameters view has the following
entries:
NLS_CHARACTERSET               WE8ISO8859P1
NLS_NCHAR_CHARACTERSET         WE8ISO8859P1
The data that i have imported are junk; they are all '????'.
Is there anything i can do?
Thank You
and we said...
You are performing a characterset conversion from whatever
EL9ISO8859P7 (not familar with that one myself) is to the
Western European standard 8 bit character set.

This conversion is causing lots of characters to be mapped to
"unknown" as they apparently have no equivalent representation
in the WE8 characterset.  The only solution would be to create a
database with a characterset that supports your (eg: either
using the EL9 characterset or perhaps UTF8 which can support
many simultaneously).
December 18, 2000 Mughilan -- Thanks for the question regarding "Does Oracle SQL Support Nano-Second ?", version 8.0.3
You Asked
Sir,

Does oracle support NanoSecond ?

In the process of my coding, I'm running a PL/SQL script which
generates a set of transaction (i.e. rows). Each row is assigned
a transaction code to identify the row uniquely, which combines
the date and time (eg. T0012181853). Here T stands for the
various type and consecutive 2 digits stand for yy, mm, dd, ss.
But when i run the script i get more similar rows. I feel it
would be comfortable if there is a nano second field i would
concatenate so that i get unique rows. Or is there is any other
solution ?

Kindly reply for this serious matter.

Mughilan.K
Database Administrator
Trivitron Diagnostics Ltd.
and we said...
You should use a sequence for this.  The datetime datatype goes
does to 1 second of precision.  Even with a finer grained clock,
the opportunity for collisions would still be there.

you could:

SQL> create sequence myseq;

and then get new transaction ids via:

select transaction_types ||
       to_char(myseq.nextval,'fm00000000000009')
  from dual
/
December 18, 2000 Andre -- Thanks for the question regarding "N-tier Authentication and Authorization", version 8.1.6
You Asked
When I issue this command:

ALTER USER client GRANT CONNECT THROUGH application WITH ROLE
role

In short, what Oracle does is give the application user (usually
without privileges) the specified role the client owns. Am I
right ?

Could you briefly describe how it can be used in a multi-tier
environment ?

Thanks
and we said...
That allows an application that connects with its own creditials
to connect "as" that other user with the specificied roles.  It
allows the author of an OCI program to connect on behalf of
another user.

See
http://osi.oracle.com/~tkyte/Misc/OCI-N-Tier.html
for more details...
December 18, 2000 Andre -- Thanks for the question regarding "Shared Schema", version 8.1.6
You Asked
Continuing my previous question "N-tier Authentication and
Authorization" this morning...

Using a shared schema, I can multiplex several clients with
different usernames into only one centralized database schema,
through a middle tier, like a directory server. Correct ?

My question is: How can I implement N-tier Authen./Author. with
a shared schema or this does not make sense ?

What is in fact the relationship between N-tier Authentication
and Authorization and shared schemas ?
and we said...
A shared schema would be appropriate is a 2 tier architecture.
The client must be willing to present their certificate to the
database -- a middle tier cannot take someones certificate and
present it to the database on their behalf.

A shared schema is basically what you would implement yourself
with a middle tier.  The end user would autheticate to your
middle tier and your middle tier would be responsible for
connecting to the database in some fashion.  Typically, the
middle tier will consider WHO is the client and using a lookup
of its own, figure out WHAT user they should log into the
database as.

This is where N-Tier authentication can come into play.  If the
user authenticates to the middle tier -- the middle tier can map
that user to a database user account and (if the appropriate
grants have been made) log in as that user without having to
know that users password (the middle tier would present its OWN
credentials to the database, not the end users credentials).  In
this case, N-Tier would be used in place of "rolling your own"
shared schema implementation.
December 18, 2000 Raja -- Thanks for the question regarding "A Curious Tripling of Data Length ", version 8.1.5
You Asked
Hello Tom ,

We have two databases a Test Database and a Production DataBase
.
When I create a table in Production  database as select from the
Test database the Data Type length  Triples it self .
For Eg
 Varchar(3) in Test DB becomes Varchar(9) in Production DB ;
 Varchar(5) in Test DB becomes Varchar(15) in Production DB.

The spool file extract is as follows :

In the Test DB known as PSC_TEST :

PSC_TEST> create table t1(f1 varchar2(3),f2 varchar2(5),
                           f3 number(2), f4  date);
Table created.
PSC_TESTt> desc t1
Name                            Null?    Type
------------------------------- -------- ----
F1                                       VARCHAR2(3)
F2                                       VARCHAR2(5)
F3                                       NUMBER(2)
F4                                       DATE

In the Production DB known as PSC_PRDN :

PSC_PRDN> create table t1 as select * from t1@psc_test
  2  where 1=2;
Table created.
PSC_PRDN> desc t1
Name                            Null?    Type
------------------------------- -------- ----
F1                                       VARCHAR2(9)
F2                                       VARCHAR2(15)
F3                                       NUMBER(2)
F4                                       DATE

Only the Varchar type length alone gets tripled .

The difference between Test DB and Prodn DB are as follows :

                        Test DB     PRDN DB
Block Size                   2K    4K
Character set             US7ASCII    UTF
Table space               Dictionary   Locally Managed
                        Managed

Does any one of the above three factors have  hand in tipling of
the Varchar Length ?
Thank YOu
Raja
and we said...
A varchar2(3) in "ascii" is a varchar2(9) in UTF.  UTF allows
for multi-byte characters.  In order to store 1 character in
UTF, you need 3 bytes.

This is normal and to be expected when using any multi-byte
character sets.
December 18, 2000 Vivek -- Thanks for the question regarding "Improving performance on Querying Nested tables ", version 8.1.6.2.0
You Asked
Hi Tom ,
 How're you doing ? I have a table column which is a nested
table of varchar2(2000) . This column can have any free text the
user enters . I am looking to do searches based on this data
using LIKE '%ABC%' .  The table structure is

Table invoices_table
 invoice_number varchar2(10)
 invoice_date date
 comments commentlist
 update_user varchar2(15)
 update_date date

Commentlist is a nested table created as
create type commentlist as table of varchar2(2000) .

The query I am using is

select a.invoice_number from invoices_table a , table (select
comments from invoices_table where invoice_number =
a.invoice_number) b
where b.column_value LIKE '%ABC%'

This query takes a very very long time to execute . My question
is what can I  do  to improve the performance of this query .
Can I add indexes to the nested table ? OR is there any other
technique I should be using to query the information .

Thanks in advance for your help/suggestions

Vivek
and we said...
Well, there is no index that can speed up "like '%ABC%'" -- we
must full scan the nested table each and every time.  An index
could be used for "like 'ABC%'" -- since the leading edge does
not have a % on it.  By putting a wildcard on the front -- we
have to consider EACH and EVERY row.

You should consider a technology like interMedia.  It specially
indexes text to provide for fast keyword retrieval.

Yes, you can index the nested table:
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76976/adobjmng.htm#1002752
shows how but in this case, I'm afraid it won't do too much.

Also, almost every nested table should be an IOT (index
organized table) as well -- with the nested_table_id on the
leading edge of its primary key.

See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76976/adobjadv.htm#1003248
for more info - if you do not use an IOT, you pretty much need
to create an index on the NESTED_TABLE_ID which is really a
foreign key back to the parent rows.
December 18, 2000 minnie -- Thanks for the question regarding "How to connect ORACLE server on unix using OCI by a client on another machine?", version oracle8i 8.1.5
You Asked
Hi, Tom
  I wrote some OCI program on a machine(Unix) that has  ORACLE
server and oracle database, they worked well. Nut I don't know
how to connect to oracle database on UNIX using OCI by a Windows
client that already installed NET8 and sqlplus. I noticed that
there are a process "OCISessionBegin" in some samples like

OCIAttrSet((dvoid *)usrhp, (ub4)OCI_HTYPE_SESSION,
             (dvoid *)"scott", (ub4)strlen("scott"),
OCI_ATTR_USERNAME, errhp);

  OCIAttrSet((dvoid *)usrhp, (ub4)OCI_HTYPE_SESSION,
             (dvoid *)"tiger", (ub4)strlen("tiger"),
OCI_ATTR_PASSWORD, errhp);

OCISessionBegin (svchp, errhp, usrhp, OCI_CRED_RDBMS,
           OCI_DEFAULT);

But there are no statement connect to which oracle database if
there are serverl oracle server in different UNIX machine?

Thanks

Minnie
and we said...
Most of the time, you can use the simplified login method:

sword OCILogon ( OCIEnv *envhp,
                 OCIError *errhp,
                 OCISvcCtx **svchp,
                 CONST text *username,
                 ub4 uname_len,
                 CONST text *password,
                 ub4 passwd_len,
                 CONST text *dbname,
                 ub4 dbname_len );

Here, the last 2 parameters are what you are interested in.

If you are using the more complex login method, it would be the
OCIServerAttach call you are interested in:

sword OCIServerAttach ( OCIServer *srvhp,
                        OCIError *errhp,
                        CONST text *dblink,
                        sb4 dblink_len,
                        ub4 mode );

A quick and dirty method is to set the environment variable
TWO_TASK to the database connect string and we'll use that by
default.
Review & Followup
Rating: 3
May 13, 2001
Reviewer: A reader from finland
i do it by using OCILogon, but i still can not succeed, i do not know how to set
the database name,such as ,the remote server is server1, and database instance
is inst1, how can set them, i set like 'server1:inst1', but it cannot work.can
you descript it more detail?

December 18, 2000 Rahul -- Thanks for the question regarding "tkproff", version 8.0.5
You Asked
Tom,

Can i run the TKPROF utility from the client?. I am able to
alter session to TRUE for sql_trace and timed_statistics and not
able to change the location for user_dump_dest. User_dump_dest
is not a modifiable parameter. But Oracles documentation for
TKPROF describes it as a modifiable parameter.

My init.ora displays the user_dump_dest=%RDBMS80%\trace. Is
there a way wherein i could change this location with out
restarting the instance. If yes, are the generated TRACE files
available at clients end or at the server.

Regards,
Rahul.
and we said...
User dump dest is modifiable

ops$tkyte@8.0> alter system set user_dump_dest
                  = '/export/home/oracle8/admin/oracle8/udump';

System altered.

It must be set to a directory on the SERVER -- not on the
client.  It is the server backend process that writes this
trace.  It must be a file system it can see and write to.

To "see" the file on your client, you would have to export/share
a directory from the server and have the user_dump_dest be that
directory.  Your client would mount that filesystem.   I would
not recommend doing it the "other way" - making your database
dependent on a networked drive.
December 18, 2000 James -- Thanks for the question regarding "Oracle Forms", version v. 8i
You Asked
I am developing an application using Oracle Forms, and ran into
three questions I could'nt resolve with the books and help
screens I currently am using.  I am interested in getting your
reponse on them (eg, a direct answer, and/or point me to some
other resource)

1) REFERENCING VALUES IN A FORM

I have a block with five records displayed at once (there are
only 5 records in the base table).  Prior to allowing the user
to update data from this block (either at the item or block
level, which ever is best), I want to validate the user's entry
in one of the columns are in decending order for the five
records.  I can do this with triggers in the case of a single
record instant showing by referencing the value with the syntax
:block.item.  In the current case, however, I want to reference
each of the 5 instances of this item on the form, so I can
validate they are in the correct sequence.  I'm not sure how to
reference individual instances of an item (ie, the value for
each of the five records) in a form.

2)  SQL - FROM CLAUSE

Is there a general rule for the order the table names are listed
in in an SQL FROM clause (base on efficiencies ?).  Also, does
this depend on the DBMS ?  I understand the most restrictive
statements in a WHERE clause should be put last (to restrict
records being processed), but am unsure when it comes to a FROM
clause.

3)  RADIO BUTTONS

I have a when new form instance trigger which does an Execute
Query command.  Things work fine except that data displayed in
Radio Buttons do not display correctly.  When I display the next
record the buttons work correctly, and when I go back to the
first record the buttons again work correctly (even though they
initially did not with the new form).  Is there any way to get
the buttons to work correctly when a new form is brought up (and
the Execute Query fires per the triger) ?

Thank you
and we said...
1) you can use the builtins FIRST_RECORD, NEXT_RECORD to iterate
over the items in a block.  for example, the following sums all
of the "deptnos" in the DEPT block:

declare
    l_sum number default 0;
begin
    go_block( 'DEPT' );
    first_record;
    loop
        l_sum := l_sum + :dept.deptno;
        exit when ( :system.last_record = 'TRUE' );
        next_record;
    end loop;
    message( 'Sum of DEPT = ' || l_sum );
end;

2) When using the Cost based optimizer (CBO) -- the order of the
tables is wholly irrelevant.  It will reorder them.

When using the rule based optimizer (RBO) -- you want to put
your driving tables -- the tables you want us to goto first, on
the RIGHT HAND side of the from list.  In general with Rules:

   from a, b, c

will drive the query from c to b to a (given that they are all
joined together and such).  So, typically you put your most
restrictive table on the RIGHT hand side.

The same is true for the where clause.  When using the CBO, the
order is not relevant.  When using RBO, we tend to evaluate
BOTTON UP.

3) I'd need more details on how to exactly reproduce against the
EMP/DEPT tables.  I just built a default block tabular block on
DEPT, made LOC a radio group and added 4 radion buttons.  I
assigned the various locations to them and ran the form.  Worked
right away.  I'm using forms 6.5 and would need to know your
version.
December 18, 2000 H -- Thanks for the question regarding "How to compare char and varchar2", version 8.1.6
You Asked
Hi Tom:

I have run the block:
declare
  b char( 10 );
  v char( 10 );
begin
  b := '1';
  v := '1   ';
  if ( b = v ) then
     dbms_output.put_line ( 'b=v' );
  else
     dbms_output.put_line ( 'b<>v' );
  end if;
end;
/
It's show 'b=v';
but I change v to varchar2(10)
declare
  b char( 10 );
  v varchar2( 10 );
It's show 'b<>v';

BUT I WANT B=V;

there are to many place to compare char and varchar in my
program. Must I use ltrim(trim(b)) = ltrim(ltrim(v)) to compare
char and varchar2, If No, Would you please tell me how to do.
  Thanks in advance.

regards
Hjty.
and we said...
I never use char() for this very reason.  CHAR's are ALWAYS
blank padded -- ANSI has made it this way.

If you compare a char(9) with a char(10), they'll never compare
either.

You can either:

o use RTRIM( char_variables ).  You only need rtrim -- not the
ltrim.  You want to remove trailing blanks.

o stop using CHAR all together.

o write your own "isequal" function:

  function isequal( a varchar2, b varchar2 ) return boolean
  as
  begin
    return rtrim(a) = rtrim(b);
  end;

  and use that instead of ='s
December 19, 2000 John -- Thanks for the question regarding "Evaluate Expression", version any
You Asked
Hi Tom,

How can I evaluate a character string ?

For example, if I have a character string '5 * (4 + 6)'
 how can I evaluate it to 50

 Or character string '1/3' to 0.3333333

 Thanks

Roop
and we said...
Here is one method.  It lets you pass a formula and upto 1 input
to the formual (you use the word "in_variable" in the formula
and I'll bind the value in for you).

ops$tkyte@ORA8I.WORLD> create or replace package eval
  2  as
  3      function do_it
  4      ( p_function in varchar2, p_var in number )
  5      return number;
  6
  7  end;
  8  /
Package created.

ops$tkyte@ORA8I.WORLD> create or replace package body eval
  2  as
  3
  4  g_theCursor        integer default dbms_sql.open_cursor;
  5
  6  function do_it
  7  ( p_function in varchar2, p_var in number )
  8  return number
  9  is
 10      l_rowsprocessed number  default 0;
 11      l_retval       number;
 12  begin
 13      dbms_sql.parse(g_theCursor,
 14                    'begin :ret_val := ' ||
 15         replace(p_function,'in_variable',':in_variable') ||
 16                      '; end;',
 17                     dbms_sql.native );
 18
 19      dbms_sql.bind_variable
               (g_theCursor,':ret_val',l_retval );
 20      begin
 21          dbms_sql.bind_variable
                 ( g_theCursor, ':in_variable', p_var );
 22      exception
 23          when others then
 24              if ( sqlcode = -1006 ) then
 25                  null;
 26              else
 27                  RAISE;
 28              end if;
 29      end;
 30      l_rowsprocessed := dbms_sql.execute(g_theCursor);
 31      dbms_sql.variable_value
             ( g_theCursor, ':ret_val', l_retval );
 32
 33      return l_retval;
 34  end do_it;
 35
 36
 37  end eval;
 38  /

Package body created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> begin
  2    dbms_output.put_line
  3    ( eval.do_it( '1 * (12.1 * POWER(in_variable,2.06))',
                5 ) );
  4  end;
  5  /
333.168228204034354868248961030690574583

PL/SQL procedure successfully completed.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> begin
  2     dbms_output.put_line
  3     ( eval.do_it( '2.06 * 1.77371', NULL ) );
  4  end;
  5  /
3.6538426

PL/SQL procedure successfully completed.
December 19, 2000 afaq -- Thanks for the question regarding "Datatype Conversion", version "version 8.0.3"
You Asked
Hi Tom,

   We have got a situation where we need to change the datatype
of a field at runtime.Following is the scenario for it

          Table  1                     Table 2
  pd_keyword_cat_char                   pd_valid_data
   Keyword       varchar2(3)           Keyword varchar2(3)
   categroy_code number(5,0)           categroy_code number(5,0)
   char_code       varchar2(5)         char_code  varchar2(5)
   measure_unit   varchar2(5)          valid_data varchar2(70)
   must_flag        varchar2(1)        date_created   date
   printing_order  number(2,0)         created_by varchar2(30)
   date_created   date                 date_modified  date
   created_by      varchar2(30)        modified_by varchar2(30)
   date_modified  date
   modified_by     varchar2(30)

 Requirement:  On the form based on each of the above table we
would like  the VALID_DATA field of the PD_VALID_DATA table to
accept only number data if the MEASURE_UNIT field of the
PK_KEYWORD_CAT_CHAR table has data in it,else the VALID_DATA
field has to accept only character data.

 Thanks in Advance
 Afaq Baig
and we said...
You would code a WHEN-VALIDATE-ITEM trigger on that item in
table 2.  Assuming keyword is a UNIQUE (primary key) column in
table 1, you might want to create a view that joins table 1 to
table 2 and create the block on that so that you don't have to
query table 1 for each item when you validate it.  You can build
the block in table 1.measure_unit and table 2.* so that you'll
have the measure unit readily available.  As long as KEYWORD in
table 1 is unique or primary key -- this view will be updateable
for all columns in table 2.

Your when-validate-item trigger could then look like:

declare
  dummy number;
begin
  if ( :block.measure_unit is not null ) then
     dummy := to_number( :block.valid_data );
  end if;
end;
December 19, 2000 H -- Thanks for the question regarding "can oracle rebuild function ro procedure", version 8.1.6
You Asked
Hi Tom:
  I have a table like:
   create table bb ( n char( 10 ) );
  and I have many stored procedure based on table bb, such as
   create or replace procedure tt as
    begin
      insert into bb values ( '11' );
    end;
  when I run
   select object_name, status from user_objects where
object_name = 'TT';
  it show me STATUS is VALID;
  but after I modify table bb like :
    alter table bb modify ( n char(11) );
  and run:
  select object_name, status from user_objects where object_name
= 'TT';
  it show me STATUS is INVALID;

  Would you please tell me How to let the status VALID without
reinstall the source code of tt;

  Thanks in advance.

Regards
Hjty
and we said...
Just run the procedure and it'll automagically compile itself.

If you really want to, you can

alter procedure tt compile;

as well.  It is not necessary.  The procedure will automagically
compile itself when next executed.
December 19, 2000 akthar -- Thanks for the question regarding "Materialized view ", version 8.1.5
You Asked
How to use order by clause while creating materialized view.

matter most urgent .

thanks in advance
and we said...
see
http://technet.oracle.com/doc/oracle8i_816/server.816/a76994/mv.htm#40552

this only orders the rows when the MV is created.  It does not
cause the rows selected from the MV to be ordered.  If you need
that functionality -- you'll need to create a regular VIEW ontop
of the MV and query the view.
December 19, 2000 Omar -- Thanks for the question regarding "Forms on application server", version 4.0
You Asked
Hi Tom,

Thanks a lot for being my helper in Oracle. This Time I want
more than a Question , some of them I think will be a little bit
long, because I am trying to ask you a week a go and I could
not.

Q1. Here we are trying to develop a Library system on the web,
really I want you to tell me which best oracle products to use
and in what way.

Q2. What are you doing in this page is really greate , I want
you ,please , to provide me how and what are you doing here ,
with sample code of your search routines if possible, with the
structure of your database.

Q3.How can call a database procedure with html tags (I mean to
be displayed as html page using htp package) from a button in a
form developed on application server with forms server.

Q4.How to load a winword doc file in a lob column, and how to
search in it for a string and display the contents on a web
page.

thanks in advance
and we said...
q1 -- thats really hard to answer as I do not know exactly what
a "library system" means to you.  It could be as easy as using
Portal -- as that has content management functions, is
integrated with interMedia for searching, and so on.  If you
were building from scratch, some people would like to use Java
and servlets/jsps -- then JDeveloper might be the tool.  If this
is an intranet based application and demanded a very rich GUI,
forms developer server might be the right answer.  So, the
answer is -- I don't know.  You'll need to evaluate the tools --
the job you have to do -- and who you have to do it with (their
skill set).

q2 - my search routine is a simple query actually.  I use
interMedia to index all of my questions and answers.  When you
search, I am simply

"select * from T where contains( text, 'your search' ) > 0"

I use the interMedia "markup" routine to do the highlighting for
me.  I do virtually nothing in my search routine, the database
does it all.

See
http://technet.oracle.com/doc/oracle8i_816/inter.816/index.htm
for more info on intermedia.

q3 - The developer built-in procedure web.show_document will
launch a browser window directed to any URL which is specified
as a parameter.

q4 - see q2.  Intermedia is the way to do this.  It has filters
for many document types from pdf, to doc to ppt.
December 19, 2000 Andre -- Thanks for the question regarding "Net8, logon triggers and ATXs", version 8.1.6
You Asked
1) Are both FAILOVER and LOAD_BALANCE parameters default in
tnsnames.ora when I specify more than one ADDRESS ?

2) Oracle warns to take care when creating a LOGON trigger
because, in case it fails, it´s impossible to log in, even as a
DBA. However, the workaround would be to connect as INTERNAL and
disable the trigger. This is not very clear to me: In this case,
what´s the difference between connecting as SYS and INTERNAL ?

3) As to autonomous transactions (ATX´s), I´ve read:
"In an ATX, commited changes are immediately  visible to other
transactions (except for the calling transaction unless its
isolation level is "read commited") regardless of whether the
calling PL/SQL block commits or rolls back. Changes made by the
calling transaction are not visible to the ATX unless they are
commited before calling the autonomous block"
What seems strange to me is that it appears -- from the above
quote -- that an ATX and the calling transaction are run "in
parallel" like different "threads" of execution. Or does the
calling transaction wait until the ATX finishes to continue its
work ? Would you please comment on the "read commited" isolation
level in this case ?

Thanks
and we said...
Here are the definitions and defaults for each of the above:

FAILOVER (Connect-Time Failover)

At connect time, instructs Net8 to fail over to a different
listener if the first listener fails when set to ON. The number
of addresses in the list determines how many addresses are
tried. When set to OFF, instructs Net8 to try one address.
Connect-time failover is turned ON by default for multiple
address lists (ADDRESS_LIST), connect descriptors (DESCRIPTION),
and multiple connect descriptors (DESCRIPTION_LIST).

LOAD_BALANCE (Client Load Balancing)

When set to ON, instructs Net8 to progress through the list of
listener addresses in a random sequence, balancing the load on
the various listeners. When set to OFF, instructs Net8 to try
the
addresses sequentially until one succeeds. Client load balancing
is turned ON by default for multiple connect descriptors
(DESCRIPTION_LIST).

2) it is a subtle difference.  If you connect as SYS you cannot
"shutdown" "startup" for example.  Internal is "special".

SVRMGR> connect sys
Password:
Connected.
SVRMGR> shutdown
ORA-01031: insufficient privileges

SVRMGR> connect internal
Password:
Connected.
SVRMGR> shutdown
Database closed.
Database dismounted.
ORACLE instance shut down.

so, sys cannot shutdown, internal can

SVRMGR> connect sys
Password:
ORA-01034: ORACLE not available
SVRMGR> startup
ORA-01031: insufficient privileges

sys cannot startup, but sys connected as SYSDBA can

SVRMGR> connect sys as sysdba
Password:
Connected.
SVRMGR> startup
ORACLE instance started.
Total System Global Area                         43681036 bytes
Fixed Size                                          70924 bytes
Variable Size                                    39436288 bytes
Database Buffers                                  4096000 bytes
Redo Buffers                                        77824 bytes
Database mounted.
Database opened.
SVRMGR>

internal and "as sysdba" are synonymous

3) the parent and child transactions are executed serially.  The
parent is suspended for duration of the autonomous transaction.

Here things can get a little murky.  Database changes made but
not yet committed by a parent transaction are not visible to the
autonomous transactions.  Changes made and committed by the
parent transaction are always visible to the child transaction.
Changes made by the autonomous transaction may or may not be
visible to the parent transaction depending on its isolation
level.

I said before though that this is where things get murky.  I was
pretty clear above in saying that changes made by the parent
transaction are not visible to the child but that’s not 100% of
the story.  A cursor opened by the child sub-transaction will
not see those uncommitted changes but a cursor opened by the
parent and fetch from by the child – will.  The following case
shows how this works.  We will create a table, insert a row into
that table, open a cursor on that table and pass that cursor to
the autonomous transaction.  This autonomous transaction will
“see” the uncommitted row in the cursor but it will not see that
same row when it runs its own cursor against the same exact
table:

ops$tkyte@DEV816> create or replace package types
  2  as
  3          type rc is ref cursor;
  4  end;
  5  /
Package created.

ops$tkyte@DEV816> create table t ( msg varchar2(255) );
Table created.

ops$tkyte@DEV816> create or replace
  2  procedure autonomous_proc( p_cursor in out types.rc )
  3  as
  4          pragma autonomous_transaction;
  5          l_msg  varchar2(4000);
  6  begin
  7          dbms_output.put_line( 'Data from Parent cursor' );
  8          loop
  9                  fetch p_cursor into l_msg;
 10                  exit when p_cursor%notfound;
 11                  dbms_output.put_line( l_msg );
 12          end loop;
 13          close p_cursor;
 14          dbms_output.put_line( 'End of data from parent' );
 15
 16          dbms_output.put_line( chr(9) );
 17          dbms_output.put_line( 'Data from Child cursor' );
 18          for x in ( SELECT * from t )
 19          loop
 20                  dbms_output.put_line( x.msg );
 21          end loop;
 22          dbms_output.put_line( 'End of data from child' );
 23  end;
 24  /
Procedure created.

ops$tkyte@DEV816> create or replace
  2  procedure parent_proc
  3  as
  4          l_cursor        types.rc;
  5  begin
  6          insert into t values
  7          ( 'This is a row inserted by parent_proc' );
  8
  9          open l_cursor for select * from t;
 10
 11          autonomous_proc( l_cursor );
 12  end;
 13  /
Procedure created.

ops$tkyte@DEV816> exec parent_proc
Data from Parent cursor
This is a row inserted by parent_proc
End of data from parent

Data from Child cursor
End of data from child

PL/SQL procedure successfully completed.

The cursor from the parent transaction is opened and running in
the parents transaction state – it can see these uncommitted
rows.  The cursor opened in the autonomous transaction might as
well have been opened in another session all together when it
comes to this uncommitted data – it will never be able to see
these uncommitted rows.

So, that shows how a child sub-transaction will react to
uncommitted changes made by the parent as far as SELECTS go.
What about the parent with regards to seeing data changes made
by the child?  Well, that will depend on the parents isolation
level.  If you use the default isolation level of committed
read, the parent will be able to see the changes.  If you are
using serializable transactions however, you will not be able to
the changes made – even though you made them.  For example:

ops$tkyte@DEV816> create table t ( msg varchar2(4000) );
Table created.

ops$tkyte@DEV816> create or replace procedure auto_proc
  2  as
  3          pragma autonomous_transaction;
  4  begin
  5          insert into t values ( 'A row for you' );
  6          commit;
  7  end;
  8  /
Procedure created.

ops$tkyte@DEV816> create or replace
     procedure proc( read_committed in boolean )
  2  as
  3  begin
  4          if ( read_committed ) then
  5              set transaction isolation level read committed;
  6          else
  7              set transaction isolation level serializable;
  8          end if;
  9
 10          auto_proc;
 11
 12          dbms_output.put_line( '--------' );
 13          for x in ( select * from t ) loop
 14                  dbms_output.put_line( x.msg );
 15          end loop;
 16          dbms_output.put_line( '--------' );
 17          commit;
 18  end;
 19  /
Procedure created.

ops$tkyte@DEV816> exec proc( TRUE )
--------
A row for you
--------

PL/SQL procedure successfully completed.

ops$tkyte@DEV816> delete from t;
1 row deleted.

ops$tkyte@DEV816> commit;
Commit complete.

ops$tkyte@DEV816> exec proc( FALSE )
--------
--------

PL/SQL procedure successfully completed.

As you can see – when the procedure is run in read committed
mode, we see the committed changes.  When run in serializable
mode, we cannot see the changes.  This is because the changes in
the autonomous transaction happened in another transaction all
together and the isolation mode of serializable dictates we can
only see our transactions changes (it is as if our transaction
was the only transaction in the database in this mode, we are
not permitted to see others changes).
December 19, 2000 Muhammad -- Thanks for the question regarding "problems while installing oracle on my PC", version Personal oracle 8.0.3
You Asked
I have windows 98 os. I tried to install personal oracle 8 with
developer 2000 on it . the installation was ok but when I try to
connect it it gives a message that " Interface driver not found"
and it doesn't connect it. somebody told me that you can't
install both oracle sqlplus and developer both on win 98, but
you must have win NT os for this purpose. Also he told me that
the primary partiton should be of FAT 16 based. then you can
install both developer and oracle database on it. please guide
me in this respect what should i do . If it is possible for you
that you guide me step by step what to do from the very
beginning i-e starting from creating partitions, installing
win98 and win NT and then going to the oracle installation, I
shall really be very grateful to you.

Thanking you sir, in anticipation;
Muhammad Ali
and we said...
If the products are installed into separate oracle homes or have
different required support files (RSF's), you need to use
SQLNet.  In all likelyhood, you have a developer release that is
based on 7.3 or 8.0.5 (hard to tell since you didn't include a
version).

In this case, you need to configure the listener.ora in the
oracle-home of the DATABASE and start the tns listener.  You
need to then configure the tnsnames.ora file in the oracle-home
of the developer software.  Then, you can connect from d2k to
the database using "scott/tiger@tnsnames-entry" where
tnsnames-entry is the name you used when setting up the
tnsnames.ora file.

see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:871227537936
for an example.
December 19, 2000 BIKRAM -- Thanks for the question regarding "LEGATO/RMAN BACKUP", version oracle 8i
You Asked
We are going to implement RMAN tape backups. We will be using
Legato Networker module as the MML. Do you have some expertise
here? From my previous experience, I know we need to modify our
RMAN scripts to include a few legato environment variables -
but, I don't exactly remember them now. We are running oracle
8.1.6.1 on Sun Solaris 2.5. Also, I know we will need to relink
the oracle executable with legato MML. Do you have the
instructions for this relink?   On a separate issue, I have a
very small table (82 rows) - I have added a foreign key to this
table. Do I need to create an index on the foreign key column?
My previous experience suggests to create indexes for all the
foreign key columns.
and we said...
There is now an entire manual dedicated just to using Legato
with Oracle.
http://technet.oracle.com/doc/oracle8i_816/server.816/a77218/toc.htm
I believe you'll find it'll answer most all of the questions.

as for foreign keys and indexes see:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:292016138754
For an 82 row table -- you'll really only need the index if you
update the parent tables primary key or delete from the parent
table and need to avoid the full table lock that would result on
the child without the index.
December 19, 2000 Ravi -- Thanks for the question regarding "Error in trigger creation", version 815
You Asked
Tom,

I got the following script from your archive. It meets my
requirement. My oracle version is 815

create or replace trigger do_grant
after CREATE on schema
declare
    l_str varchar2(255);
    l_job number;
begin
    if ( ora_dict_obj_type = 'TABLE' )
    then
        l_str := 'execute immediate "grant select on ' ||
                                     ora_dict_obj_name ||
                                    ' to scott";';
        dbms_job.submit( l_job, replace(l_str,'"','''') );
    end if;
end;
/
5/10     PLS-00201: identifier 'ORA_DICT_OBJ_TYPE' must be
declared

Could you please tell me,  how to overcome this problem in 815

Thanks
Ravi

When I ran this, I got the following error message.
and we said...
Sorry -- in 8.1.6 it is ora_dict_obj_name.  In 8.1.5 it was:

dictionary_obj_name

VARCHAR(30)

Name of the dictionary object on which the DDL operation
occurred.

Example:

 INSERT INTO event_table ('Changed object is ' ||
            sys.dictionary_obj_name');

See chapter 14 of you Application Developers Guide for all of
the Event Attribute Functions available in the execution of a
DDL trigger.
December 19, 2000 Arthur -- Thanks for the question regarding "More Storage Questions", version 8.1.5
You Asked
Tom,

Too many storage parameters to keep track of.  I want to add a
datafile to a tablespace.  This was the original startment
creating the tablespace/datafile:

CREATE TABLESPACE DATA_EJ1 DATAFILE
   '/u01/oradata/DR_CASHT/DATA_EJ1.dbf' SIZE 1866465280 REUSE
    AUTOEXTEND ON NEXT 4096 MAXSIZE 4194296K
   DEFAULT STORAGE (INITIAL     5120 K
         NEXT        5120 K
         MINEXTENTS  1
         MAXEXTENTS  2147483645
         PCTINCREASE 0)
   ONLINE
   PERMANENT;

The current tablespace/datafile is about 2GB.  The new datafile
will grow, probably to 2GB also.  Here are some questions:

1)  Does it make sense to make the new datafile 2GB also?
2)  If the new datafile is 2GB, what good is the AUTOEXTEND
clause?
3)  That is A LOT of extents, is that causing any real
performance problems?

Thanks.
and we said...
1) you already have it at about 1.8 gig, rounding it out
wouldn't hurt.

2) if you don't want it to go over 2gig, and you created it at
2gig, you would not want to use autoextend.  Autoextend is
useful when you want to let a file grow over time from a couple
of meg to Xgig.  Saves you time backing up in the beginning
while the file is small.

3) Lots of extents are OK.  Extents are done at the segment
level so if you have lots of segments -- at 5meg / extent -- the
most you would have is about 500 extents in a 2 gig datafile
with 1 segment.  Thats not outrageous.  On the other hand, if I
knew I was going to have a single 2 gig object in a single file
-- I might choose to use a larger extent size.
December 20, 2000 sudipto -- Thanks for the question regarding "recieving emails ", version forms 6i,oracle 8i
You Asked
Dear Mr Tom,
  Sir, i am working on a module that will recieve emails and
store them to the database(oracle). Kinldy tell me if there is
some method by which i can recieve emails from the mail server
of the internet service provider or web email provider and then
store the email as different records in a datatable. Is this
feature available in Oracle 8i (feature of downloading emails)?
moreover i am required to store each mail as a separate record
and the different attribute like sender reciever date etc as
fields. Kindly suggest a solution as soon as convinient as i am
struck.
  Hoping to a positive response
yours faithfully
sudipto basu
and we said...
Java can do this in 8i.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:255615160805
it shows how to load up the packages to SEND email -- Sun
has equivalent packages to READ email.
December 20, 2000 Farhad -- Thanks for the question regarding "Regarding Table operator in Collection.", version 8.1.5
You Asked
Hi Tom,
   Mailing u after a long time now. Well, I am some difficulties
so please solve it for me.

 1. Can I use a table operator in VARRAYS specially for
inserting and updating the values in VARRAYS types?

 2. How to insert into a clob or blob column of a table with
some example?

 Hoping for your prompt reply.

 Regards,
 Farhad.
and we said...
1) no, not for the update/insert. piecewise operations are not
supported on VARRAYS. you must update the entire varray or
insert the entire varray.  Consider the following example.  If
you use a nested table -- it works, when you use a VARRAY as
this example does, the DML does not work (since piecewise
operations are not supported on VARRAYs)

ops$tkyte@ORA8I.WORLD> create type myVarray as varray(50) of
number
  2  --create type myVarray as table of number
  3  /

Type created.

ops$tkyte@ORA8I.WORLD> create table t ( x int, v myVarray )
  2  --nested table v store as v_tbl
  3  ;

Table created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> insert into t values ( 1, myVarray( 1, 2,
3, 4, 5, 6, 7, 8 ) );

1 row created.

ops$tkyte@ORA8I.WORLD> insert into t values ( 2, myVarray( 10,
20, 30, 40, 50, 60, 70, 80 ) );

1 row created.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select * from table( select v from t
where x = 1 );

COLUMN_VALUE
------------
           1
           2
           3
           4
           5
           6
           7
           8

8 rows selected.

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> update table( select v from t where x = 1
)
  2  set column_value = column_value + 5
  3  where column_value > 5;
set column_value = column_value + 5
    *
ERROR at line 2:
ORA-25015: cannot perform DML on this nested table view column

ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD>
ops$tkyte@ORA8I.WORLD> select * from table( select v from t
where x = 1 );

COLUMN_VALUE
------------
           1
           2
           3
           4
           5
           6
           7
           8

8 rows selected.

2) see
http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:load+blob
for some pointers on that.
December 20, 2000 Kevin -- Thanks for the question regarding "Executing Stored Procedures through SQLPLus from a batch command file", version 8.0.5
You Asked
Hi

We have a number of developed stored procedures in the database.
We need to call a number of these directly from a dos batch
command file. At present we have batch files that create/replace
the procedure and then execute it at the end. However this is
not ideal so we have one script which generates the procedure
for implementation and then a large number of other batch files
which will EXECUTE the procedure.

We are trying to do the following from the batch file

sqlplus <username>/<password>@db_name execute
delete_prev_process

The delete_prev_process is a procedure name as opposed to an
external sql script file !!

This is returning an error message as it seems to expect a
script file to run. Is what we are attempting to do achieveable.

Any help much appreciated

Thanks

Kevin
and we said...
echo exec dbms_output.put_line( 'Hello World' ) | sqlplus
tkyte/tkyte

will work.  Echo the command to sqlplus.
December 20, 2000 Muralidhar -- Thanks for the question regarding "iAS and OAS", version 1.00
You Asked
what is the difference between OAS and iAS?
and we said...
Night and day.

OAS is built on Spyglass Mosaic and a Corba 2.0 Orb.

iAS is built on Apache and its module concept.

Functionally -- they offer the same features, the plsql
cartridge and so on are all there.

Architecturally, they are very different.

see
http://technet.oracle.com/docs/products/ias/doc_index.htm
for all of the iAS documentation.
December 20, 2000 Cathy -- Thanks for the question regarding "Adding to block in layout editor", version forms 4.5
You Asked
I am adding buttons to a canvas which has a block that has four
records.  When I try and add a button ( or any other object) it
adds four.  How can I avoid this and just add one button?
and we said...
You would create another block whose number of displayed items
is 1.  Before you select the button on the toolbar -- you would
use the drop down list in the upper right hand corner to choose
this new control block you just created.  By putting the buttons
on this block (but on the same canvas) you'll achieve a single
button instead of 4.
December 20, 2000 saigals -- Thanks for the question regarding "enable help in sqlplus", version 8.0.6.0.1
You Asked
Tom,

How do I enable help in sqlplus?

Thanks,
saigals
and we said...
Here are the directions for 8.0

goto $ORACLE_HOME/sqlplus/admin/help

there you will find:

helptbl.sql
helpindx.sql
plshelp.ctl
plushelp.ctl
sqlhelp.ctl

you should connect as SYSTEM and run helptbl.sql.  Then run

sqlldr userid=system/manager control=plshelp.ctl
sqlldr userid=system/manager control=plushelp.ctl
sqlldr userid=system/manager control=sqlhelp.ctl

then run helpindx.sql when connected as SYSTEM.
December 21, 2000 Michael -- Thanks for the question regarding "truncating empty table generate ORA-02266:", version 8.1.6
You Asked
Tom ,
why truncating empty table generates the error ORA-02266 ?

SQL> select count(*) from t_data;

  COUNT(*)
----------
         0

SQL> truncate table t_data
                     *
ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled
foreign keys

SQL> delete t_data;

0 rows deleted.

Thanks,
Michael.
and we said...
You cannot truncate a table with an enabled foreign key that
points to it.  Truncate does not fire any triggers, does not
validate any constraints.  It does not care of the child table
is empty or not -- in this case the child table might actually
not be empty.

You would have to disable or drop the foreign keys that
reference this table.

Here is an example:

ops$tkyte@DEV816> create table p ( x int primary key );
Table created.

ops$tkyte@DEV816> create table c ( y int primary key,
  2                   x int,
  3            constraint c_fk foreign key(x) references p);
Table created.

ops$tkyte@DEV816> insert into c ( y ) values ( 1 );
1 row created.

ops$tkyte@DEV816> truncate table p;
truncate table p
               *
ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled
foreign keys

ops$tkyte@DEV816> alter table c disable constraint c_fk;
Table altered.

ops$tkyte@DEV816> truncate table p;
Table truncated.

Now we can truncate since the foreign key is no longer
enabled, all we need to do now is re-enable it which will also
check it and make sure none of the rows in C point to a row in
P

ops$tkyte@DEV816> alter table c enable constraint c_fk;
Table altered.

Alternatively, you can run a query to find all of the foriegn
key constraints and generate an "alter table" command that would
rebuild them.  In this fashion, you can drop them, run the
truncate and the rebuild them.  This is handy if you do not know
the constraints before hand -- it'll show you what they are:

ops$tkyte@DEV816> column fkey format a80 word_wrapped
ops$tkyte@DEV816> select
  2  'alter table "' || child_tname || '"' || chr(10) ||
  3  'add constraint "' || child_cons_name || '"' || chr(10) ||
  4  'foreign key ( ' || child_columns || ' ) ' || chr(10) ||
  5  'references "' || parent_tname || '" ( ' ||
             parent_columns || ');' fkey
  6  from
  7  ( select a.table_name child_tname, a.constraint_name
               child_cons_name,
  8           b.r_constraint_name parent_cons_name,
  9           max(decode(position, 1,     '"'||
 10                  substr(column_name,1,30)||'"',NULL)) ||
 11           max(decode(position, 2,', '||'"'||
 12                  substr(column_name,1,30)||'"',NULL)) ||
 13           max(decode(position, 3,', '||'"'||
 14                  substr(column_name,1,30)||'"',NULL)) ||
 15           max(decode(position, 4,', '||'"'||
 16                  substr(column_name,1,30)||'"',NULL)) ||
 17           max(decode(position, 5,', '||'"'||
 18                  substr(column_name,1,30)||'"',NULL)) ||
 19           max(decode(position, 6,', '||'"'||
 20                  substr(column_name,1,30)||'"',NULL)) ||
 21           max(decode(position, 7,', '||'"'||
 22                  substr(column_name,1,30)||'"',NULL)) ||
 23           max(decode(position, 8,', '||'"'||
 24                  substr(column_name,1,30)||'"',NULL)) ||
 25           max(decode(position, 9,', '||'"'||
 26                  substr(column_name,1,30)||'"',NULL)) ||
 27           max(decode(position,10,', '||'"'||
 28                  substr(column_name,1,30)||'"',NULL)) ||
 29           max(decode(position,11,', '||'"'||
 30                  substr(column_name,1,30)||'"',NULL)) ||
 31           max(decode(position,12,', '||'"'||
 32                  substr(column_name,1,30)||'"',NULL)) ||
 33           max(decode(position,13,', '||'"'||
 34                  substr(column_name,1,30)||'"',NULL)) ||
 35           max(decode(position,14,', '||'"'||
 36                  substr(column_name,1,30)||'"',NULL)) ||
 37           max(decode(position,15,', '||'"'||
 38                  substr(column_name,1,30)||'"',NULL)) ||
 39           max(decode(position,16,', '||'"'||
 40                  substr(column_name,1,30)||'"',NULL))
 41              child_columns
 42      from user_cons_columns a, user_constraints b
 43     where a.constraint_name = b.constraint_name
 44       and b.constraint_type = 'R'
 45     group by a.table_name, a.constraint_name,
                    b.r_constraint_name ) child,
 46  ( select a.constraint_name parent_cons_name, a.table_name
               parent_tname,
 47           max(decode(position, 1,     '"'||
 48                  substr(column_name,1,30)||'"',NULL)) ||
 49           max(decode(position, 2,', '||'"'||
 50                  substr(column_name,1,30)||'"',NULL)) ||
 51           max(decode(position, 3,', '||'"'||
 52                  substr(column_name,1,30)||'"',NULL)) ||
 53           max(decode(position, 4,', '||'"'||
 54                  substr(column_name,1,30)||'"',NULL)) ||
 55           max(decode(position, 5,', '||'"'||
 56                  substr(column_name,1,30)||'"',NULL)) ||
 57           max(decode(position, 6,', '||'"'||
 58                  substr(column_name,1,30)||'"',NULL)) ||
 59           max(decode(position, 7,', '||'"'||
 60                  substr(column_name,1,30)||'"',NULL)) ||
 61           max(decode(position, 8,', '||'"'||
 62                  substr(column_name,1,30)||'"',NULL)) ||
 63           max(decode(position, 9,', '||'"'||
 64                  substr(column_name,1,30)||'"',NULL)) ||
 65           max(decode(position,10,', '||'"'||
 66                  substr(column_name,1,30)||'"',NULL)) ||
 67           max(decode(position,11,', '||'"'||
 68                  substr(column_name,1,30)||'"',NULL)) ||
 69           max(decode(position,12,', '||'"'||
 70                  substr(column_name,1,30)||'"',NULL)) ||
 71           max(decode(position,13,', '||'"'||
 72                  substr(column_name,1,30)||'"',NULL)) ||
 73           max(decode(position,14,', '||'"'||
 74                  substr(column_name,1,30)||'"',NULL)) ||
 75           max(decode(position,15,', '||'"'||
 76                  substr(column_name,1,30)||'"',NULL)) ||
 77           max(decode(position,16,', '||'"'||
 78                  substr(column_name,1,30)||'"',NULL))
 79              parent_columns
 80      from user_cons_columns a, user_constraints b
 81     where a.constraint_name = b.constraint_name
 82       and b.constraint_type in ( 'P', 'U' )
 83     group by a.table_name, a.constraint_name ) parent
 84  where child.parent_cons_name = parent.parent_cons_name
 85    and parent.parent_tname = upper('&1')
 86  /
old  85:   and parent.parent_tname = upper('&1')
new  85:   and parent.parent_tname = upper('p')

FKEY
---------------------------------------------------------
alter table "C"
add constraint "C_FK"
foreign key ( "X" )
references "P" ( "X");
December 21, 2000 nirad -- Thanks for the question regarding "d2k with oracle", version oracle8i
You Asked
hi tom,

can i use developer 2000 with oracle8i enterprise edition
release 8.1.5.0.0?is it possible to install developer 2000 with
oracle enterprise editon on windows nt server?
and we said...
Yes, I have it setup that way myself right now.  You will
install each product into its own Oracle_Home.
December 21, 2000 jark -- Thanks for the question regarding "reading data from a clob column ", version 8.0.1
You Asked
please tell me the way how to insert and read the data from a
clob,blob column

waiting for your reply....

with regards
varma
and we said...
Lots of examples at
http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:blob+clob
Also see
http://technet.oracle.com/doc/oracle8i_816/appdev.816/index.htm
there are at leat 6 documents on doing this in various languages
in addition to the standard documentation.
December 21, 2000 Choo -- Thanks for the question regarding "Oracle 8.0.4 not recognize Oracle 8.1.6 exported "*,dmp" file.", version 8.1.6
You Asked
Our company just upgrade to Oracle Database 8.1.6 in Unix
platform but most of our customer is still using Oracle Database
8.0.4. The problem for us is Oracle 8.0.4 can not import the
table which export by Oracle 8.1.6.

Normally, we will export the table with using "exp" command. And
our customer may import those table using "imp" command.

Here is the error message:-
IMP-00010: not a valid export file, header failed verification.
IMP-00021: operating system error - error code (dec2, hex ox2).
IMP-00000: import terminated unsuccefully.

Can you provide us some solution to recover this situations?

Thankyou.
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:820826902083
An export generated by version X cannot be read by version Y if
Y < X.

You will need to install the Oracle 8.0.4 client on a machine
somewhere in your network and use that version of EXP to export
the data.

Alternatively, you might be able to use something like:
http://osi.oracle.com/~tkyte/flat/index.html
which will be version idenpendent.
December 21, 2000 Francoise -- Thanks for the question regarding "Execute a SQL Script in a Procedure PL/SQL", version 8.1.6
You Asked
Hello,

How could I execute a SQL script inside a Procedure in PL/SQL ?

Thank You !!!
and we said...
You cannot.  a SQL script is interpreted and parsed by sqlplus.
PLSQL does not have SQLPlus compiled into it.

You could use UTL_FILE to open a text file, read it in plsql and
dynamically execute the statements -- in effect building your
own SQLPlus in plsql.
December 21, 2000 OP -- Thanks for the question regarding "Question related with CONTAINS !", version 8.1.6.0.0
You Asked
Dear Tom,

Hi !

How are you Doing !

Ques)

Is there any Keyword CONTAINS which can be used in the
where clause while writing a SELECT statement.

What is the purpose and where Exactly it is used.Is it
something similar to LIKE operator.

Kindly answer.

Thanks & Regards
OP Lalwani
and we said...
Contains is part of interMedia Text.  See
http://technet.oracle.com/doc/oracle8i_816/inter.816/a77063/toc.htm
for all of the details and
http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:intermedia
for some discussions/examples.

It allows for case insensitive keyword searching, proximity
searching, and'ing/or'ing, document markup and so on.  You are
using it when you click on the second link above.
December 21, 2000 Shane -- Thanks for the question regarding "ERROR: ORA-01489: result of string concatenation is too long ", version 3.3.2.0.2, Oracle DB 8.1.5
You Asked
We have written Stored Procedures that extract data from our
database and inserts the data into about seven tables.

I then use a SQL*plus script that joins the tables and
concatenates the columns together into a fixed length file.
I spool this file out to the network for another system to work
with. It can only handle a single fixed length file.

The record length was at 3856 chars and it worked. Now with new
additional requirements the record length is now 4658 chars and
I get the above error. I know that VARCHAR2 can only be a max of
4000 chars but do not know why this should affect the string if
I am spooling out the record. I can not split the file either.

Would you know of another way to get the data to a spooled fixed
length file? Could I change some server setting to deal with
larger output? Could I move it to a larger data type and then
spool it out? Any ideas would be appreciated.

Thanking you in advance
Shane Lakes

Shortened Example of script:

Set arraysize 1
Set linesize 4000
Set pagesize 50000
Set embedded on
Set termout off
Set heading off
Set feedback off
Set verfiy off

Spool C:\VAL.txt
Select
rpad (NVL(TO_CHAR(A.SEQNUM), ' '),12, ' ') ||
rpad (NVL(TO_CHAR(A.CASE_MBR_KEY_OUT), ' '),8, ' ') ||
rpad (NVL(TO_CHAR(A.CASE_KEY_OUT), ' '),8, ' ') ||
rpad (NVL(A.CONT_NO_OUT, ' '),10, ' ') ||
rpad (NVL(A.BRANCH_CD_OUT, ' '),6, ' ') ||
rpad (NVL(A.COUNS_CD_OUT, ' '),6, ' ') ||
.
. Lines left out
.
.rpad (NVL(G.EXP_DESC9, ' '),50, ' ') ||
rpad (NVL(G.EXP_SCL9, ' '),4, ' ') ||
rpad (NVL(TO_CHAR(G.EXP_CHRG_AMT9), ' '),16, ' ') ||
rpad (NVL(TO_CHAR(G.EXP_CHRG_XPCT9), ' '),6, ' ') ||
rpad (NVL(G.EXP_DESC10, ' '),50, ' ') ||
rpad (NVL(G.EXP_SCL10, ' '),4, ' ') ||
rpad (NVL(TO_CHAR(G.EXP_CHRG_AMT10), ' '),16, ' ') ||
rpad (NVL(TO_CHAR(G.EXP_CHRG_XPCT10), ' '),6, ' ') ||
rpad (NVL(TO_CHAR(G.TIMESTAMP, 'YYYYMMDD HH24:MI:SS'), ' '),26,
' ')
from
VAL_SCHEME_DTLS A,
VAL_MBR_DTLS B,
VAL_MBR_BEN_DTLS C,
VAL_MBR_UNIT_DTLS D,
VAL_PREM_DTLS E,
VAL_MBR_LOADINGS F,
VAL_MBR_EXPENSES G
where
A.SEQNUM = B.SEQNUM AND
B.SEQNUM = C.SEQNUM AND
C.SEQNUM = D.SEQNUM AND
D.SEQNUM = E.SEQNUM AND
E.SEQNUM = F.SEQNUM AND
F.SEQNUM = G.SEQNUM
/
Spool off
and we said...
the max length of a varchar2 is 4000 characters in 8.x (2000 in
7.x).  A string concatenation is a varchar2 -- hence, the max
you can concat is 4000 bytes.

One solution for you in 8i would be to use a temporary table and
a clob.  Here is an example:

drop table clob_table;

create global temporary table clob_table
( id int primary key, x clob ) on commit delete rows
/

declare
    l_cnt number default 1;
    l_clob  clob;

    procedure append( p_string in varchar2 )
    as
    begin
        dbms_lob.writeappend(l_clob,length(p_string),p_string);
    end;
begin
    for x in ( select * from all_objects where rownum < 10 )
    loop
        insert into clob_table values ( l_cnt, empty_clob() )
            returning x into l_clob;

        -- Here i am just generating data, you would have
        -- your rpads and nvl's of the columns here...
        for i in 1 .. trunc(5000/length(x.object_name))+1
        loop
            append( x.object_name );
        end loop;
        l_cnt := l_cnt+1;
    end loop;
end;
/

set long 10000
select x from clob_table order by id;
commit;
-- data disappears after the commit.

Another solution would be to use UTL_FILE if the file can be on
the server.  Use the entry point in UTL_FILE that lets fopen
specify the maximum record width and set it to 32k or so.
Otherwise the line length with utl_file will default to about
1022 bytes.
December 22, 2000 Gursev -- Thanks for the question regarding "Synchronous/Asynchronous communication.", version version 8.1.6
You Asked
i  am using jdbc to connect to oracle  and i am using java to
connect to it. its like when i get the result set but with some
kind of control. take a case when a result set is of 400000
records but i don't want my client to wait for that big reuslt
set i just will break it into batches of 1000 or less

hi ! tom,
When we are retreiving a large no of recordS(50000-1,00,000) the
database doesn't give the cursor control  in our hand until it
has scrolled down the result set once.
The problem is how to get the control in our hands,so that we
can get records in some batches , while the records are still
being fetched from the dbase.
I am using oracle 8i.
I had heard this has something to do with asynchronous
communication but how ,I don't have any hint.

thanks in advance ..
and we said...
JDBC array fetches, by default if you are using the Oracle JDBC
drivers we fetch 10 rows at a time.   You can control the number
of rows we pre-fetch by using:

  ((OracleStatement)stmt).setRowPrefetch (200);

that would tell us to fetch 200 rows everytime you asked for a
row (and we didn't have one cached already).

Your problem, if it is taking a long time to get the first row,
is probably that we must resolve the ENTIRE result set before
giving you the first row back.  Lets say you run a query like:

 select * from t where x > 10 order by y;

If there are 400k rows that satisfy this and we used an index on
X to find them -- we must find ALL of them and they sort them
before you get the very first row back.  That'll take a while.
On the other hand -- a query like:

 select * from t where x > 10;

will starting returning data almost immediately since we could
just use the index to find the first matching row.  Sometimes
you can take a query that has to resolve the entire result set
(as in the first case above) and make it be able to return rows
immediately.  For example, if we indexed   t(x,y) then the
query:

  select * from t where x > 10 order by y;

would be able to use that index to select rows where x > 10 AND
sort by y simultaneously -- hence you would start getting data
right away -- you would not have to wait for the entire answer
to be built.

So, I think you need to look at your query and figure out if you
can make it so that it can return the first row of the answer
BEFORE it finds the last row of the answer.  JDBC is batching
this -- it is NOT fetching all 50k - 100k records at once, it is
fetching them 10 at a time on demand.
December 22, 2000 Nikunj -- Thanks for the question regarding "Storing Data Instead of Table ", version ver 6.0
You Asked
hi tom,

in my application i given a list of values of item code & its
other info.
but when ever user select the item it should be remove from the
list so

i had created one table as below

 desc dummy3
 Name                            Null?    Type
 ------------------------------- -------- ----
 ITCODE                          NOT NULL VARCHAR2(60)
 ITDES                           NOT NULL VARCHAR2(100)
 UNITRATE                                 NUMBER
 SALES_SRNO                               NUMBER
 U_PER_CARTON                    NOT NULL NUMBER(12,2)
 KG_PER_CARTON                   NOT NULL NUMBER(13,3)
 UNITPACK                        NOT NULL NUMBER(12,2)
 PACKAGING                       NOT NULL VARCHAR2(20)

so i had write below sql script on three trigger 1). when new
form instance 2) on commit    3). key -exit

delete from dummy3;
insert into dummy3 select itcode,itdes,(nvl(rate,0)) unitrate,
nvl(sales_srno,0)+1 sales_srno,u_per_carton,kg_per_carton,
unitpack,packaging
from item;

and on item code i had write below script on key-listval
DECLARE
  a_value_chosen BOOLEAN;
BEGIN
  a_value_chosen := Show_Lov('ITEM');
  IF a_value_chosen THEN
    delete from dummy3 where itcode=:itcode and
sales_srno=:sales_s_no;
    go_item('no_of_carton');
  END IF;
END;

so is it possible without storing value in table ?

thanks,
amit
and we said...
Just create an LOV based on a record group that has your query
associated with it (the query you are now inserting into
dummy3).

Make sure to set the "Automatic Refresh" property in the LOV to
FALSE (no).

Then, logic like this:

declare
        rg_id recordGroup;
        gc_id groupColumn;
        rowCount number;
begin
    if ( show_lov( 'the_lov' ) )
    then
       rg_id := Find_Group( 'LOV_RG' );
       gc_id := Find_Column( 'LOV_RG.DEPTNO' );
       rowCount := Get_Group_Row_Count( rg_id );
       for i in 1 .. rowcount
       loop
                    if ( get_group_number_cell( gc_id, i )
                                               = :dept.deptno )
            then
               delete_group_row( rg_id, i );
               exit;
            end if;
       end loop;
    end if;
end;

will remove from the record group associated with the LOV the
last selected item (I used the deptno column of scott.dept as a
test).
December 22, 2000 Andre -- Thanks for the question regarding "What rows does ESTIMATE STATISTICS scan ?", version 8.1.6
You Asked
I know ANALYZE TABLE ... ESTIMATE STATISTICS does a row
sampling, where I can specify the number (or percentage) of rows
to estimate.

My question is: I what fashion are these rows scanned? For
example, if I want 1064 rows (the default) to be checked, are
these rows the first 1064 rows from the table or are they
"randomly" selected ? Are they selected any other way ?

Thanks !
and we said...
They are randomly selected from the entire table.

<quote server concepts, chapter 21, statistics for CBO>

To estimate statistics, Oracle selects a random sample of data.
You can specify the sampling percentage and whether sampling
should be based on rows or blocks.

Row sampling reads rows without regard to their physical
placement on disk. This method provides the most random data for
estimates, but it can result in reading more data than
necessary. For example, in the worst case a row sample might
select one row from each block, requiring a full scan of the
table or index.

Block sampling reads a random sample of blocks and uses all of
the rows in those blocks for estimates. This method reduces the
amount of I/O activity for a given sample size, but it can
reduce the randomness of the sample if rows are not randomly
distributed on disk. Block sampling is not available for index
statistics.
</quote>


Subject | Article | Last Updated (East coast time)
how can i know the number of tables and details in a database ? | article only | Dec 23, 2000 11:04 am
SQL & PL/SQL doubts | article only | Dec 23, 2000 11:24 am
Again - Storing Data Instead of Table | article only | Dec 23, 2000 11:30 am
PL/SQL | article only | Dec 23, 2000 08:37 pm
Oracle Parallel Server | article only | Dec 23, 2000 08:42 pm
Problems using Oracle Universal Installer with Win ME | article only | Dec 24, 2000 10:05 am
Fisrt Chance | article only | Dec 24, 2000 10:07 am
Adding conditions to WHERE clause, from ENTER-QUERY. | article only | Dec 24, 2000 10:10 am
LArge No of records being transacted | article only | Dec 24, 2000 10:13 am
Pinned packages,procedures,sequences | article only | Dec 24, 2000 10:17 am
Is there any way in JDBC to tell the user that a record is Locked ? | article only | Dec 24, 2000 10:35 am
export/import | article only | Dec 25, 2000 11:25 am
History of Oracle | article only | Dec 25, 2000 11:34 am
SGA Shared Pool - Data -Reg | article only | Dec 25, 2000 11:39 am
Size of a database | article only | Dec 25, 2000 11:42 am
locking records in tables when the user downloads into laptop | article only | Dec 25, 2000 11:46 am
mySQL | article only | Dec 25, 2000 11:50 am
Dump Data On To a Flat File. | article only | Dec 25, 2000 11:54 am
Decode | article only | Dec 26, 2000 09:32 am
Select statement | article only | Dec 26, 2000 09:42 am
Can I have multiple remote standby databases ? | article only | Dec 26, 2000 09:50 am
dirty read | article only | Dec 26, 2000 09:59 am
Integrity of Data | article only | Dec 26, 2000 10:19 am
How can i bind the form to add date in database only for 1st of month | article only | Dec 26, 2000 11:43 am
remote machine | article only | Dec 26, 2000 11:57 am
FK / PK relationship | article only | Dec 26, 2000 02:21 pm
DDE | article only | Dec 27, 2000 09:32 am
CREATING A COPY OF TABLE | article only | Dec 27, 2000 09:39 am
Remote Procedure Call | article only | Dec 27, 2000 10:37 am
About Indexes | article only | Dec 27, 2000 10:47 am
Multiple Data Sources for a single data load | article only | Dec 27, 2000 11:33 am
BACKED_UP column in DBA_TABLES | article only | Dec 27, 2000 11:53 am
Recovery... | article only | Dec 28, 2000 10:12 am
FORMS - Format Mask, Documentation | article only | Dec 28, 2000 10:36 am
Privileges | article only | Dec 28, 2000 10:45 am
RPC Call Error | article only | Dec 28, 2000 12:34 pm
Highwatermark | article only | Dec 28, 2000 01:19 pm
Nested tables | article only | Dec 28, 2000 03:45 pm
the difference between select * and select 'X' and select null | article only | Dec 28, 2000 04:46 pm
reverse indexes | article only | Dec 29, 2000 09:02 am
CallableStatement | article only | Dec 29, 2000 09:15 am
HTTP request | article only | Dec 29, 2000 09:29 am
Export Problem | article only | Dec 29, 2000 09:45 am
backup control file | article only | Dec 29, 2000 09:50 am
what is the use of 'BGM' ? | article only | Dec 29, 2000 10:35 am
Unique and PK constraints using a non-unique index | article only | Dec 29, 2000 10:40 am
get user list created by another user | article only | Dec 29, 2000 01:10 pm
latch misses | article only | Dec 29, 2000 01:57 pm
Oracle 9i | article only | Dec 29, 2000 02:00 pm
Datafiles | article only | Dec 29, 2000 03:42 pm
Database Creation Script | article only | Dec 29, 2000 03:44 pm
row(s) 1 - 51 of 51
December 23, 2000 chan -- Thanks for the question regarding "how can i know the number of tables and details in a database ?", version 8i v8.1.7
You Asked
how can i know the number of tables and details in a database ?
i m using linux oracle, so i don't use GUI. so what command can
i type to check?
and we said...
Query the data dictionary.

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76961/toc.htm
chapter 2.

A query such as:

select owner, object_type, count(*)
 from dba_objects
group by owner, object_type
/

would for example show you a count by user of the number of each
type of object (package, procedure, table, index, etc) they own.
December 23, 2000 Guru -- Thanks for the question regarding "SQL & PL/SQL doubts", version Oralcle 7.3
You Asked
Hi Tom,

   I have several questions for you in PL/SQL & SQL.

1. Can we use a column of LOB datatype in a user defined
datatype.

2. Pl. tell me what is meant by throughput.  Also tell me what
should be the optimizer hint if my main goal is throughput.

Is it a) FIRST_ROWS
      b) CHOOSE
      c) LAST ROWS.
Pl. explain in detail.

Thanking You,
Guru Prasad M.R.
and we said...
1) yes:

tkyte@TKYTE816> create type myType as object ( x clob );
  2  /
Type created.

tkyte@TKYTE816> create table typeTable of myType;
Table created.

tkyte@TKYTE816> desc typeTable
 Name              Null?    Type
 ----------------- -------- ------------
 X                          CLOB

tkyte@TKYTE816>

2) throughput is defined by websters as:

Main Entry: through·put
Pronunciation: 'thrü-"put
Function: noun
Date: circa 1915
: OUTPUT, PRODUCTION <the throughput of a computer>

It is a measure of the amount of work done in a period of time.
Your throughput might be 5 transactions per second for example.

There is no optimizer hint that maximizes throughput.  In
general "all_rows" optimization would do that as it attempts to
generate query plans that give you the last row in a result set
the fastest whereas first_rows attempts to get the first row as
fast as possible.  It depends on if you do everything in BATCH
or via  a user interface with end users.  End users would
typically enjoy first_rows over all rows in an interactive
application but when running a report, they might enjoy all rows
over first rows.

You have to tune to improve throughput.  There is no "switch".
December 23, 2000 Nikunj -- Thanks for the question regarding "Again - Storing Data Instead of Table ", version 6.0
You Asked
tom,

thanks for reply on storing data instead of table.
now i face below problem.

its remove selected row from record group but after user save
the record and go for new entry the rows with he had selected on
his privous entry does not display.

so tell me how can i solve this.

Just create an LOV based on a record group that has your query
associated with it (the query you are now inserting into
dummy3).

Make sure to set the "Automatic Refresh" property in the LOV to
FALSE (no).

Then, logic like this:

declare
        rg_id recordGroup;
        gc_id groupColumn;
        rowCount number;
begin
    if ( show_lov( 'the_lov' ) )
    then
       rg_id := Find_Group( 'LOV_RG' );
       gc_id := Find_Column( 'LOV_RG.DEPTNO' );
       rowCount := Get_Group_Row_Count( rg_id );
       for i in 1 .. rowcount
       loop
                    if ( get_group_number_cell( gc_id, i )
                                               = :dept.deptno )
            then
               delete_group_row( rg_id, i );
               exit;
            end if;
       end loop;
    end if;
end;

will remove from the record group associated with the LOV the
last selected item (I used the deptno column of scott.dept as a
test).
and we said...
Just add logic like:

declare
    rg_id recordGroup;
begin
    rg_id := Find_Group( 'LOV_RG' );
    if ( populate_group( rg_id ) <> 0 ) then null; end if;
end;

in your form when you want to refresh the LOV to have all of the
value.  Use an ON-COMMIT or some other trigger to reset the LOV
when you want it to be reset.

that trigger above needs some error handling of course.
December 23, 2000 Govindan -- Thanks for the question regarding "PL/SQL", version 8.1.6
You Asked
I want to know how to pass a Nested Table/VArray (preferably
Nested Table) as a parameter to a PL/SQL procedure/function?.
I prefer Nested Table because I can get dynamically flexible
number of elemets.

Thanks.

Govindan Katteri
and we said...
Well, you would have to specify a language.  From plsql to plsql
it is fairly trivial:

tkyte@TKYTE816> create or replace type myTableType
  2  as table of number
  3  /

Type created.

tkyte@TKYTE816>
tkyte@TKYTE816> create or replace procedure foo( p_table in
myTableType )
  2  as
  3  begin
  4          for i in 1 .. p_table.count loop
  5                  dbms_output.put_line( p_table(i) );
  6          end loop;
  7  end;
  8  /

Procedure created.

tkyte@TKYTE816>
tkyte@TKYTE816> declare
  2          l_tab myTableType := myTableType( 1, 2, 3, 4 );
  3  begin
  4          foo( l_tab );
  5  end;
  6  /
1
2
3
4

PL/SQL procedure successfully completed.

If you have a certain language in mind, feel free to followup.
December 23, 2000 ahmad -- Thanks for the question regarding "Oracle Parallel Server", version 8.0.5
You Asked
Hi tom;
My question is about oracle parallel server.
what is the memory structures of an OPS.
I mean does every instance has its own sga and each user has his
own pga,and user directly connect to the database or
indirectly(any other possible way).
or they first connect to a instance then through instances they
r connected to database?
Tanx in Advance!!
and we said...
OPS is a configuration where more then one INSTANCE of Oracle
(an instance being a collection of init files, processes and
memory -- SGA) mount a single database ( a database being a
collection of files -- redo, data, control).

Each instance has its own sga.
Each PROCESS has a PGA, each user has a UGA.

Nothing about that is different from non-OPS Oracle.

you might want to look at
http://technet.oracle.com/doc/oracle8i_816/paraserv.816/index.htm
and in particular the OPS concepts guide for more info.
December 24, 2000 Navdeep -- Thanks for the question regarding "Problems using Oracle Universal Installer with Win ME", version 8.1.5 Personal
You Asked
Tom ,
I am trying to install Personal Oracle 8i on win me -- the
version is actually meant for Win98 , but Win Me being backward
compatible with win 98 programs , the software should install.
However when i run  the Oracle Universal Installer , the moment
I hit the next button after the welcome screen , it just
vanishes. I tried installing it using a response file , but that
too didn't work. Can you suggest as to what might be the reason
for it. Do i need to download a patch or something else ? -
I have a 64 mb machine. The software did install on the same
machine with win 98.

Thanks
Navdeep
and we said...
Win ME is a totally NEW operating system.  Things "should" work
but there are lots of things that do not.

The database is not supported on Win ME.  It does not function
correctly on that operating system.

The only supported platforms as of this writing from Microsoft
are

Win95
Win98
WinNT
Win2000 (8.1.6 and up only)
Review & Followup
Rating: 3
Universal Installer , & Win200 February 17, 2002
Reviewer: mubeen
Dear Tom,

what i did is used a Universal installer from a Production CD 8.1.6 and tried to
install this goes fine ON win 98 on win 2000, i get this message

"INVALID STAGING AREA THERE ARE NO TOP LEVEL COMPONENTS FOR WIN NT AVAILABLE FOR
INSTALLER FROM THIS STAGING AREA"

Can you please guide me,

Thanks

December 24, 2000 Abrar -- Thanks for the question regarding "Fisrt Chance", version 8.1.6
You Asked
hello sir!
this is the first time, i am approaching to u.
How can i make the full command file (script file) of my
existing database in which there are many objects so that i can
create this database again on anyother PC.
and we said...
You would use the utility EXP (export) and IMP (import).

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76955/toc.htm
for a total description of these utilities.  In short, lets say
you wanted to copy all of the objects and data of the user "X"
from one machine to another.  You could:

$ exp userid=X/password owner=x

binary ftp or otherwise copy the file expdat.dmp to the other
machine

$ imp userid=X/password full=y
December 24, 2000 Rama Subramanian G -- Thanks for the question regarding "Adding conditions to WHERE clause, from ENTER-QUERY.", version Forms 6.0.5.0.2
You Asked
Hi Tom,

In Forms 6.0, while in Enter-Query Mode, I enter some values in
some data items for a query.  When the Query is executed, forms
takes care to fetch rows qualifying the WHERE clause as per the
data items to which values were entered.

I would like to know, whether we can add some additional
conditions to the default SELECT that Forms frames.  The
situations can be, additional WHERE clauses based on child
tables of the table where the Query is executed.

Regards,
Rama Subramanian G
and we said...
Sure, you can programatically set a BLOCK property of a
DEFAULT_WHERE.

From the online help in this area:

The WHERE and ORDER BY block properties allow you to restrict
and order the records returned to a data block by the default
SELECT statement associated with that block.

You can modify the WHERE and ORDER BY clauses programmatically
at runtime by executing the SET_BLOCK_PROPERTY built-in
procedure.

Remember also that operators can place the form in Enter Query
mode and then further restrict the default WHERE Clause by
specifying additional query conditions in data items.

You can set the default WHERE and ORDER BY clauses for a block
in the Property Palette.  To invoke a text editor in the
Property Palette, double-click the desired property.

Tip:  Select ToolsTables/Columns to invoke the Tables/Columns
browser to look up table and column names in the database.
Any valid SQL WHERE and ORDER BY clauses can be entered in the
default WHERE clause and default ORDER BY clause properties.
Some additional considerations are specific to Form Builder:

n    It is not necessary to include the reserved words WHERE and
ORDER BY; Form Builder implicitly adds them to any text you
enter.  Thus, the clause

ORDER BY last_name

can be entered as

last_name

And the following is a valid WHERE clause entry:

account_balance > 5000

n    You cannot reference LONG database columns in the default
WHERE/ORDER BY clauses.
December 24, 2000 Sankalp -- Thanks for the question regarding "LArge No of records being transacted", version 8i
You Asked
Dear Tom,
      I am working on Insurance software and currently working
on Group Life Insurance.

Problem what I am facing is that for a particular policy , I am
having 5000 employees. Now when I save a policy into database, I
have around 60 tables to transact with and around 5000 recrds to
save.
      Once I say Commit in Forms the system hangs for long
time.And the policy  never gets stored.

      What database tuning or application level tuning , i need
to perform to commit these large number transactions.

Thanks in advance for the solution
SANKALP
System Analyst- Insurance
Pentasoft Malaysia
Malaysia
and we said...
Well, it is most likely the logic you are performing that is
taking so long.  It would typically take a very few seconds to
create 5,000 records.

I would suggest starting with SQL_TRACE, TIMED_STATISTICS and
TKPROF to see what your application is doing SQL wise to see if
there are any queries that are taking an abnormally long amount
of time.  That is the best place to start.

See
http://technet.oracle.com/doc/server.815/a67775/ch14_str.htm#1018
for details on that.
December 24, 2000 Jayaraman -- Thanks for the question regarding "Pinned packages,procedures,sequences", version 8.1.6.0.0
You Asked
Hi Tom,
I have pinned certain packages and procedures to the shared
pool.How do i find out what are the objects that have been
pinned? Is there any view or table which gives us this
information? Thanks in advance as always and i am really
grateful to you for your most useful service and suggestions.
Regards,
Ashok
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:289616051290
for an example.  It is in the dynamic performance table
v$db_object_cache.
December 24, 2000 Narayanan -- Thanks for the question regarding "Is there any way in JDBC to tell the user that a record is Locked ?", version 8.1.6
You Asked
Through JDBC, from one transaction, I give a update statement.
Without commiting the first transaction, I start a second
transaction. I am trying to update the same record. My program
executing the second update statement is locked/hanged untill I
give commit for my first transaction.

Now the problem is, Is there any way in JDBC to tell the user
running the second transaction that the record he is trying to
update is already updated by some other user & it is uncommitted
?

How to achieve this. Thanks is advance for your reply

Regards,
Narayanan.A.R.
and we said...
Instead of just updating the record -- you should select it for
update nowait.  You need to do this to ensure the record has not
been changed typically anyway.

Let's say you have an application that queries up a record and
lets the user look at it.  BEFORE they change a single byte of
that record -- right before -- you should execute some logic
like:

   select *
     from T
    where c1 = <selected value of c1>
      and c2 = <selected value of c2>
      ......
   FOR UPDATE NOWAIT;

You should either ensure you select the PRIMARY KEY (so as to
identify the exact record you wish) or include the ROWID in your
initial select so you can easily find this record again (rowid
will be the fastest).

Now, you would run the above query BEFORE they changed a byte of
data on the screen.  If you

o get 0 records that means between the time you selected the
record originally and now someone else has modified this record.
 You need to requery this record to avoid overwritting their
updates.  If you do not requery the record -- your program will
suffer from what is known as the "lost update" problem.  You
will overwrite others updates without ever inspecting them.

o get an ORA-54, Resource Busy -- someone else has this record
locked.  You must wait.  Don't even bother changing this record
on screen because the likely hood is that it will have changed
in the database and you'll have to requery it anyway.  You can
keep retrying this operation until you get 0 or 1 records back
without an ORA-54

o get a record back -- you have successfully locked the record
in the database.  You can make any changes you want.  When the
time comes to do the update -- you can be assured that the
record is yours.  You have it locked already.

This is exactly the logic performed by tools such as Oracle
Forms for you transparently.  The SELECT ... for update nowait
is what you want to use.  For an interactive application that
queries up lots of records and lets the user pick one to update
-- the above logic is the most correct implementation to

o promote maximum concurrency

o protect data integrity

o avoid programs blocking in the database waiting for a row
(which they would undoubtably overwrite someone elses changes
unless they follow the above logic leading to "lost updates")
December 25, 2000 omran -- Thanks for the question regarding "export/import", version personal oracle8..4.0.0
You Asked
how can i export data from oracle8 as dmp file
 which can i import it using oracle7?
thank you v.much Tom.

note:
I am new user in oracle feild,and my english language
is not very strong so please help me by writing me using simple
words.
best regards
abu al khair omran.
12-24-2000
and we said...
You need to use the version 7.x EXP tool over SQLNet to the 8.x
database.

You will

o run catexp7.sql found in $ORACLE_HOME/rdbms/admin in the
version 8.x database.  This should be run using the SVRMGRL
command line tool when connected as SYS or INTERNAL.  This will
supply the views that the version 7 EXP uses.

o using the version 7 EXP utility, perform the export using a
username/password@database connect string

o import as normal.
December 25, 2000 aimin -- Thanks for the question regarding "History of Oracle", version version 8.1.5
You Asked
Hi,

i'm wondering if there is a place where i can find the Oracle
chronology?

Thanks

aimin yin
and we said...
You can see a brief history here:
http://www.atr.net/faq/software/FRONT_END/faqgenrl.htm#hist
and here:
http://www.oracle.com/corporate/pressroom/html/index.html?firsts2.html
...
Review & Followup
Rating: 1
October 29, 2002
Reviewer: A reader

December 25, 2000 Koshal -- Thanks for the question regarding "SGA Shared Pool - Data -Reg", version 8.1.6.0
You Asked
Hi Tom

1. When I say 'select * from table_name' which contains
    10000 rows  thnink that i have good amount of SGA.
   Is the result set stored in the SGA or Not?

2. When I say 'select Count(*) from table_name' which returns
   returns a single rows does the result set is stored in
   the SGA.  If it is stored in the SGA when I execute the
   statement for the second time it should be returned within
   a fraction of second irrespect of the time taken for executing
   the query for the first time.

Regards
and we said...
1) The "result set" is not stored there but the blocks that are used to
construct the result set might be.  It depends.   It depends on the size of the
table, the settings of the table (cache vs nocache) and so on.  typically a full
scan like that would go to the head of the LRU list so that those blocks are
immediately aged out of the SGA.  If the table is "cached" -- they then the
blocks are buffered "normally".

2) result sets are never stored in the SGA.  Blocks that can be used to make a
result set are.  The result of a count(*) would not be cached HOWEVER the index
that was use to answer the count(*) or the table blocks that were used might be.

A count(*) is a "highly unstable" answer -- other sessions modifying the table
will affect it continously.  It would not be cached.  To see how to "pre answer"
computationally expensive queries, you want to read about Materialized Views.
See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76994/mv.htm#721
for details.
December 25, 2000 -- Thanks for the question regarding "Size of a database", version 8.1.6
You Asked
How do i calculate the size of my database.
Is there any formula to calculate the size of an existing
database( whether it is 1 GB or 100GB etc..)
Also, if i have to setup a database for an application which has
some 20 tables and around 50,000 records, how do i plan the
sizes for the tablespaces. please send me any other useful
information on database design.
Also, while creating a database , what is the naming convention
that needs to be followed for the tables, keys, indexes,
tablespaces...etc..
Thanks in advance.
Warm Regards
and we said...
see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:285415955510
to find out how to find out how big an existing database it.

To size a new instance, see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:302216525000
for my guidelines.

For naming conventions -- there are none that need to be
followed.  You might want to implement one that fits in with
your way of doing things but there are no standard or mandatory
naming conventions.
December 25, 2000 -- Thanks for the question regarding "locking records in tables when the user downloads into laptop", version 8.1.6
You Asked
Hi,
I have a 8i database server on NT and 8i lite on a laptop.
The laptop user will have to go offline occasionally and
whenever he goes offline he will take relevant data into the
laptop. At this point of time when he downloads the relevant
data, those particular records in the database server should be
locked thus preventing any other user from accessing those
records. When the laptop user comes back online , he will do the
replication thus uploading all the changes which he made during
offline.
is it possible to do this type of locking.

i will be using updatable snapshots on the 8i lite.

Is there any facility in 8i EE so that the records can be locked
till the laptop user comes back and uploads the data.
and we said...
You will need to implement this yourself.  It is commonly
refered to "dynamic ownership".  There will be a column in the
table you use to enforce this.  A trigger will prevent anyone
from updating this row unless the column has a specific value.
For example, you might use the values "I" (for in) and "O" (for
out).  On the master site the trigger would be:

create or replace trigger t
before update or delete on t for each row
begin
   if ( :old.owner_column <> 'I' ) then
      raise_application_error
      ( -20001, 'This row is checked out');
   end if;
end;
/

On the snapshot sites -- you would use:

create or replace trigger t
before update or delete on t for each row
begin
   if ( :old.owner_column <> 'O' ) then
      raise_application_error
      ( -20001, 'This row is NOT checked out');
   end if;
end;
/

See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76959/repadv.htm#1767
for all of the details and more ideas.
December 25, 2000 Ravi -- Thanks for the question regarding "mySQL", version 8.1.6
You Asked
Is there a utility that helps us migrate the data from mySQL
database to Oracle 8.1.6 database?

Also, is there a strategy one has to follow for migrating from
one database to another?
and we said...
See
http://technet.oracle.com/software/tech/migration/workbench/software_index.htm
for the migration toolkit.
December 25, 2000 Ganesh -- Thanks for the question regarding "Dump Data On To a Flat File.", version 8.1.5, 8.1.6
You Asked
Hi Tom,

I have a database running in Ingres and there is a command there to port a
tables data to a Flat File for a third party program to read and move the data
to a Legacy System.

When i coverted those scripts to Oracle PL/SQL Programs i used the UTL_FILE
Package to write the data in the way the legacy system understands (i.e) by
delimiting them with spaces or Tabs or Other characters.

Tom Now COmming to my question is there anyother way in oracle to transfer the
data from a Database table to flat file.

Thanks for u'r help.

Regards,
Ganesh R
and we said...
SQLPlus works quite well at doing this, see
http://osi.oracle.com/~tkyte/flat/index.html
for an example.  Beyond that, UTL_FILE and sqlplus are the best bets in this
arena.

follow up to comment:

it is there, I just tested it, nothing has moved in a long time in the
directory.  Not sure what might have gone wrong.
Review & Followup
Rating: 2
Dump Data On To a Flat File April 25, 2001
Reviewer: chris barr from cambridge, MA, USA
As always, it's pretty much just what I'm looking for,
but this URL cannot be found:
http://osi.oracle.com/~tkyte/flat/unloader.zip

December 26, 2000 Kiran -- Thanks for the question regarding "Decode", version version 8.1.5
You Asked
Hi ,
 Can I use expression in decode function
For eg; select decode(salary>100,true,1,0) from table;
i.e., if a column value is less or more than a specified value ,
then it should return some pre-defined value.

Thanks
KK.
and we said...
In Oracle8i release 2 and up (8.1.6) this is somewhat simplified
using the new CASE statement:

tkyte@TKYTE816> select
  2     case
  3       when sal > 1000
  4       then 'Salary > 1000'
  5       else 'Salary NOT > 1000'
  6     end,
  7     ename, sal
  8   from emp
  9  /

CASEWHENSAL>1000T ENAME             SAL
----------------- ---------- ----------
Salary NOT > 1000 SMITH             800
Salary > 1000     ALLEN            1600
Salary > 1000     WARD             1250
Salary > 1000     JONES            2975
Salary > 1000     MARTIN           1250
Salary > 1000     BLAKE            2850
Salary > 1000     CLARK            2450
Salary > 1000     SCOTT            3000
Salary > 1000     KING             5000
Salary > 1000     TURNER           1500
Salary > 1000     ADAMS            1100
Salary NOT > 1000 JAMES             950
Salary > 1000     FORD             3000
Salary > 1000     MILLER           1300

14 rows selected.

Prior to that, using SIGN in a decode works nicely.  SIGN tells
us if a number if negative, positive or zero:

tkyte@TKYTE816>
tkyte@TKYTE816> select
  2    decode( sign(sal-1000),
  3             1, 'Salary > 1000',
  4                'Salary NOT > 1000' ),
  5         ename, sal
  6    from emp
  7  /

DECODE(SIGN(SAL-1 ENAME             SAL
----------------- ---------- ----------
Salary NOT > 1000 SMITH             800
Salary > 1000     ALLEN            1600
Salary > 1000     WARD             1250
Salary > 1000     JONES            2975
Salary > 1000     MARTIN           1250
Salary > 1000     BLAKE            2850
Salary > 1000     CLARK            2450
Salary > 1000     SCOTT            3000
Salary > 1000     KING             5000
Salary > 1000     TURNER           1500
Salary > 1000     ADAMS            1100
Salary NOT > 1000 JAMES             950
Salary > 1000     FORD             3000
Salary > 1000     MILLER           1300

14 rows selected.
December 26, 2000 Kiran -- Thanks for the question regarding "Select statement", version version 8.1.5
You Asked
Hi,

Table Structure:
Accountno Number
Billno    Number
Amount    Number

Data:
Accountno    Billno     Amount
1008         23         100
1008         89         200

With a single select I want the output as follows
assuming that there would be always 2 different billno for a
single account

Accountno    Billno_1  Billno_2  sum(Amount)
1008         23        89        300

Please help me with the select statement

Thanks
KK.
and we said...
Assuming that

o AccountNo, Billno is unique (eg: billno is unique within an
accountNo)

o there are always 0, 1 or 2 rows / AccountNo

We can use the following:

tkyte@TKYTE816> create table t
  2  ( Accountno Number,
  3    Billno    Number,
  4    Amount    Number
  5  )
  6  /

Table created.

tkyte@TKYTE816> insert into t values ( 1008, 23, 100 );
tkyte@TKYTE816> insert into t values ( 1008, 89, 200 );
tkyte@TKYTE816> insert into t values ( 3000, 44, 400 );
tkyte@TKYTE816> insert into t values ( 3000, 55, 500 );
tkyte@TKYTE816> insert into t values ( 4000, 55, 500 );

tkyte@TKYTE816> select accountNo,
  2         min(billno) billno_1,
  3             max(billno) billno_2,
  4             sum(amount) amount,
  5             count(*) cnt
  6    from (
  7  select accountNo, billno, amount, rownum r
  8    from t
  9   -- where condition goes here --
 10   order by accountNo, billno
 11         )
 12   group by accountNo
 13  /

 ACCOUNTNO   BILLNO_1   BILLNO_2     AMOUNT        CNT
---------- ---------- ---------- ---------- ----------
      1008         23         89        300          2
      3000         44         55        900          2
      4000         55         55        500          1

I've included the COUNT(*) here to validate the results.  If cnt
= 1, you must ignore one or the other of billno_1, billno_2 --
we could use the query:

  1  select accountNo,
  2         min(billno) billno_1,
  3        decode( count(*), 2, max(billno), null) billno_2,
  4        sum(amount) amount,
  5        count(*) cnt
  6    from (
  7  select accountNo, billno, amount, rownum r
  8    from t
  9   -- where condition goes here --
 10   order by accountNo, billno
 11         )
 12*  group by accountNo
tkyte@TKYTE816> /

 ACCOUNTNO   BILLNO_1  BILLNO_2     AMOUNT        CNT
---------- ---------- --------- ---------- ----------
      1008         23        89        300          2
      3000         44        55        900          2
      4000         55                  500          1

to make that more apparent.

If CNT is ever greater then 2 -- then you've violated the "there
would always be 2 different billno for a single account" rule.
December 26, 2000 Andre -- Thanks for the question regarding "Can I have multiple remote standby databases ?", version 8.1.6
You Asked
I´ve read that in Oracle8i I can have remote standby sites
defined using the SERVICE keyword in the LOG_ARCHIVE_LOG_DEST_n
in the primary DB, which spawns a RFS process in the standby
machine.

My case is this: I need to setup a site in which I need -- in
addition to my primary database -- a standby database in the
same LAN and another standby database in a remote site via a
slower interconnect (TCP/IP over maybe X.25 or T10).

1) Can I have more than one standy database defined by different
LOG_ARCHIVE_LOG_DEST_n paramters ?

2) In this scenario, do you think the slower connection to the
remote site may hamper this configuration ?
and we said...
1) yes you can.  See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76995/standbyc.htm#30033
for a graphic that details what happens in a failover situation
when there exists more then one standby.

2) Yes, it could very much.  If you make the slower standby
database a mandatory target, then you may recieve many "cannot
allocate new log, archival required" messages which will "hang"
your primary site.  If you make it a non-mandatory location, you
may spend much of your time reactivating the archival process to
this site if it times out or becomes otherwise unavailable.

You may consider doing a more manual process where the local
standby is automated and you manually ship the logs from the
automated standby to the remote standby via scripts and what not
-- so the that primary is not really even aware of or dependent
on the slower remote site.
December 26, 2000 joel -- Thanks for the question regarding "dirty read ", version 8.1.5
You Asked
hi is there any reason why oracle dosnt offer dirty read for
an ex. if someone loads a table without committing i should be
able to read it
i know that infprmix offers something like this
thanks tom i really app. it
and we said...
Dirty read is a "feature" offered by other databases in an
attempt to offer "non-blocking reads".  The offer up "dirty
reads" as a method to increase concurrency.

Oracle has never needed this "feature" (which we don't really
consider to be a feature but a workaround).  We do not block
simple reads from processing due to a lock on a row.  We provide
for consistent reads (correct answers) without row level locks.
Reads do not block writes and writes do not block reads.  See
http://technet.oracle.com/doc/oracle8i_816/server.816/a76965/c23cnsis.htm#17882
for a discussion of this mechanism.

If the loader of the table wants others to know how many rows
have been loaded, they should instrument their load program with
calls to dbms_application_info.set_client_info.  In that
fashion, one can "select client_info from v$session where
username = <username of loader>" to see the progress dynamically
(and very quickly, rather then counting rows over and over).
December 26, 2000 -- Thanks for the question regarding "Integrity of Data", version 8.1.7
You Asked
Hi Tom,

  I have a problem in inserting data in the master-detail
tables. We are doing this using batch. Following is the code for
doing that which is taken from the technet jdbc samples. There
is a foreign key constraint on the emp table which will refer to
the dept table.

import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;

public class BatchPrepared
{
  public static void main(String args[]) throws SQLException
    {
              java.sql.Connection conn= null;
    try
    {
      Class.forName("oracle.jdbc.driver.OracleDriver");

      conn =
(OracleConnection)DriverManager.getConnection("jdbc:oracle:thin:@
200.200.198.248:1521:b2bm","b2bd","b2bd");
   }
   catch (Exception ex)
   {
      System.out.println("Error in loading " + ex);
   }

    conn.setAutoCommit(false);
    ((OracleConnection)conn).setDefaultExecuteBatch (50);
    PreparedStatement ps =
      conn.prepareStatement ("insert into dept values (?, ?,
?)");
    ps.setInt (1, 10);
    ps.setString (2, "Oracle");
    ps.setString (3, "USA");

    int rows =ps.executeUpdate ();

    ps.setInt(1,20);
    ps.setString (2, "Applic");
    ps.setString (3, "Indon");

     rows = ps.executeUpdate ();

        ps = conn.prepareStatement ("insert into emp values (?,
?, ?)");

        ps.setInt (1, 100);
       ps.setString (2, "soma");
       ps.setInt (3, 10);

      System.out.println (ps.executeUpdate ());
    rows = ((OraclePreparedStatement)ps).sendBatch ();
   conn.setAutoCommit(true);
    ps.close ();
    conn.close ();
  }
}

I have a trigger on the dept table which will submit a job to
perform some task. Now on executing the above example, while
inserting the emp table iam getting foreign key constraint error
saying that the parent key is not found. If i commit the dept
data then aim able to insert the emp data. Now my problem is if
i commit the header record, the job also will be committed even
if there is some problem in the emp data which shouldn't
happened. We are using batch inserts everwhere for the
master-detail inserts. Can't we use batch for inserting into
master-detail tables. If we insert directly without using the
batch, it is working fine. What should i do now. Pls help me
out.
and we said...
You are doing it to yourself.

You have ONE java variable PS.  This variable is being used to
execute 2 statements.

Your logic is like this:

  o allocate the prepared statement
  o use it to store 2 rows for DEPT
  o "loose" the reference to the cursor for inserting into DEPT
  o use it to store a row in EMP
  o SEND the batch for the EMP rows -- not for DEPT, you lost
    that prepared statement handle

That send of that batch will of course fail since the DEPT rows
are still saved on your side and will stay there until

o commit
o close the connection

Since you changed the defintion of PS, you have no opportunity
to close the statement for the insert into dept (you have just
"leaked" a cursor -- if you do this lots you will eventuall
exhaust the open_cursors for your program).  You have no
opportunity to do a SendBatch on the DEPT table either.

The solutions are:

o use exactly ONE SQL statement per prepared statement -- do not
reuse them as you have.

o always call CLOSE on a prepared statement (which will flush
the batch) BEFORE reusing it if you persist in reusing it (else
you will leak cursors and have others problems besides this
one).

Recommend you change the code at the bottom to:

...

    PreparedStatement ps2 =
       conn.prepareStatement
       ("insert into emp (empno,ename,deptno) values (?, ?,
?)");

    ps2.setInt (1, 100);
    ps2.setString (2, "soma");
    ps2.setInt (3, 10);

    ps2.executeUpdate();
    ps.close ();
    ps2.close ();
    conn.close ();
  }
}

So you have 2 prepared statements.  By closing them we

o avoid leaking cursors
o send the PARENT data over BEFORE the child data

You might have been thinking that since you used a single
prepared statement java VARIABLE that all three rows would be
queued up for transmission -- however there are really 2
preprared statements, one with 2 rows and another with 1 -- you
need 2 statements to do this correctly.
December 26, 2000 Naveed -- Thanks for the question regarding "How can i bind the form to add date in database only for 1st of month", version Forms 5.0.6.8.0
You Asked
Hello!
 I am facing a problem and wish that u would solve my problem:
I have a table with two columns; Month (data type DATE) and
Amount(data taype NUMBER). the column , month, has the standard
format.The problem is that i want to add records in database
table, from forms, where the date is only 1st OR 2nd of
month.While the formate of the forms textbox is MON-YYYY.
My question is that what is the way to add rows in database
table while just entering the month name and year in the form,
and the day will be considered/entered only as 1st OR 2nd of
month,automatically.Sould i use table check constraint or i
sould use a when -button-pressed trigger in the form.
Please answer my this questuion and help me out of this problem.
I will be very grateful to you.

  THANKS..
and we said...
Well, if it was just the first of the month -- it is trivial,
since MON-YYYY always gives you the first of the month:

ops$tkyte@DEV816> select to_date( 'dec-2000', 'mon-yyyy' ) from
dual;

TO_DATE('
---------
01-DEC-00

ops$tkyte@DEV816>

I might suggest you want to use a format of RRRR instead of YYYY
for the following reason:

ops$tkyte@DEV816> alter session set nls_date_format =
'dd-mon-yyyy'
  2  /

Session altered.

ops$tkyte@DEV816> select to_date( 'dec-2001', 'mon-yyyy' )
  2    from dual
  3  /

TO_DATE('DE
-----------
01-dec-2001

ops$tkyte@DEV816> select to_date( 'dec-01', 'mon-yyyy' )
  2    from dual
  3  /

TO_DATE('DE
-----------
01-dec-0001

ops$tkyte@DEV816> select to_date( 'dec-01', 'mon-rrrr' )
  2    from dual
  3  /

TO_DATE('DE
-----------
01-dec-2001

ops$tkyte@DEV816>

Notice how the date dec-01 is accepted with both formats but the
results are radically different!

As for getting a date on the second day of the month -- unless
you allow them to input the DAY as well as the month/year, I
don't know how you will achieve that.  I'd need more information
on that part of the question.
December 26, 2000 joel -- Thanks for the question regarding "remote machine", version 8.1.5
You Asked
hi please help
how do i connect my oracle_home variable to a diff machine
for exp. on machine a i would like to the oracle_home var
to connect to machine b that is i will do my work on machine a
but oracle sits on machine b but to get to b i have to path
another machine called 'path'
thank you very much
and we said...
Your ORACLE_HOME will always be set to the path where your
oracle software is installed on your local machine.

We use Net8 to connect over a network to the remote machine.
The owner of the remote database will have had to of setup the
listener.ora on that machine and will have had to of started the
TNS Listener.  Then, you can setup your tnsnames.ora file in
your $ORACLE_HOME/network/admin directory and connect to the
remote database using:

  username/password@remote_database

see
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:871227537936
for an example
December 26, 2000 Andre -- Thanks for the question regarding "FK / PK relationship", version 7.3.2
You Asked
I have 2 tables: T1 and T2. T1 is parent of T2. I need to
truncate (or delete *) T1 so it can be loaded with SQL*LOADER.
But there is the FK violation error. Since both tables are not
temporarily used, I am planning to use this approach:
. backup up table T2 with a CTAS
. truncate T2
. truncate T1
. load T1
. insert into T1 select from T2

Is this the best method ?

Thanks
and we said...
1) Alter table T2 disable constraint <fk_constraint_name>
2) Truncate T1, Load T1
3) Enable the constraint again.

For example, the exact commands are:

ops$tkyte@DEV816> create table t1 ( x int primary key );

Table created.

ops$tkyte@DEV816> create table t2 ( x int,
  2                           constraint t2_fk
  3                           foreign key(x) references t1 );

Table created.

ops$tkyte@DEV816> alter table t2 disable constraint t2_fk;
Table altered.

ops$tkyte@DEV816> truncate table t1;
Table truncated.

ops$tkyte@DEV816> -- load T1 here

ops$tkyte@DEV816> alter table t2 enable constraint t2_fk;
Table altered.
December 27, 2000 Jacob -- Thanks for the question regarding "DDE", version 8.1.5
You Asked
Tom,

I'm working at a customer for which we made, in Oracle
Financials 10.7 (fat client), a DDE-connection to an imageviewer
application on the PC (the number of the image is passed as a
parameter).

The customer is switching tot Oracle Financials 11i, now DDE is
no longer possible (so says the Oracle Documentation).

Can you tell me if it is still possible to start a
PC-application when using a formsserver on which the forms are
running? When it is, can you tell me how it must be done or
where I can get more info about it.

Thanks,

Jacob van Diermen
and we said...
I asked Bob Bunting for assistance on this one, he works in this
area much more than I do. He says:

A couple of possibilities I see here for the client -

1.  Use the web.show_document in forms which takes a URL as a
parameter and launch a standard browser window to download the
image file.  If it does not have to be a specific client
application used to view the image, why not just let the browser
handle the display.  Otherwise, you may be able to set something
up based on a file extension to launch a helper application.

2.  With forms, you can have what are called Java Plugable
components which is your own Java code on the client.
See -
http://technet.oracle.com/products/forms/pdf/269054.pdf
If the Java is signed, then it will be able to read/write to the
client's disk and make the Java call to launch a local
application Support bulletin 116129.1 explains how build a Java
Plugable component to read from a client's file system.  You
should be able to start with this example get it working and
then modify the Java to launch a local app lication. (Note:  I
have not tested this myself.   Outside of forms, I once set up
an
applet running in JInitiator to launch notepad on the PC
client.)

You can do whatever on the middle tier in 3GL using the foreign
function interface. (dll or shared library)
http://technet.oracle.com/doc/dev2k.210/guide21/d2kopen.htm#597309
If you middle tier is windows, then you can use OLE (no user
interface calls of course)

One more point to mention.  I think the customer problem
requires a client-side solution, but the response wouldn't be
complete with regard to the middle tier if we didn't mention the
new Java Importer capability of Forms 6i release 2.  This makes
it possible to any Java class from within PL/SQL.  The Java
would run in the middle tier.
http://technet.oracle.com/products/forms/pdf/java_importer.pdf
...
December 27, 2000 PRATTY -- Thanks for the question regarding "CREATING A COPY OF TABLE", version 8.1.5
You Asked
Hi Tom,
     When i created a table using
    CREATE TABLE <table i> AS SELECT * from <table ii>,
    i found that DEFAULT column values defined in
    table i is not copied to table ii(ie; i could not
    find that in DATA_DEFAULT in USER_TAB_COLUMNS).
    Pls. suggest how to copy default values too.
    (Oracle 8.1.5 on Solaris)

Thanks in advance.

Regards
Pratty.
and we said...
See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:703225007002
for how to use exp/imp to accomplish this across schemas or
databases (tablename will remain constant)

You can use export to export the total definition of the table,
then run imp with indexfile=temp.sql.  Then edit temp.sql to
rename the table and create the table using the SQL exp/imp
generates (which will include the defaults and all).  Then you
would use an INSERT INTO to populate it.
December 27, 2000 Krishna Mohan -- Thanks for the question regarding "Remote Procedure Call", version 8.1.5
You Asked
Hi Tom,
Thanx a lot for responding to my previous question on
Partitioning keys. Sorry for troubling you again. Is it possible
to call stored procedures of a remote Sybase(11.x) database from
Oracle 8i database. If yes, Pl. let us know how to achieve this.

Once again, thanx a lot for your time.

Regards,
Krishna Mohan
and we said...
Yes it is.

You need the Oracle Transparent Gateway for Sybase OR you can
load a jdbc driver for Sybase into Oracle (if you have the java
option) and connect to Sybase from "inside" the database (you'll
lose the two phase commit you would get otherwise this way
though).

See
http://www.oracle.com/gateways/
for more info.
December 27, 2000 Guru -- Thanks for the question regarding "About Indexes", version Oracle 7/8
You Asked
Hi Tom,

   I have several questions. Here they are

1) If i have a index on more than 1 column is there any data
dictionary view/table where i can see the columns on which the
index is created. For ex : we can see the columns that are
associated with a constraint using user_cons_columns.

2) Suppose we have a composite index on (empno, ename, deptno)
and we are using only deptno in the where clause of a select
statement.  Will the above index be used in that select
statement.  Pl. explain how oracle decides whether to use it or
not.

3) While i was reading about join views, i came across a KEY
PRESERVED TABLE.  Pl. explain about this table.

4) If a select statement takes increasingly long time to give
the output. Apart from the index what are the areas that needs
to be checked (like SGA, PGA, etc) to improve the performance.

With regards,
Guru Prasad M.R.
and we said...
1) user_ind_columns

2) No, that index will PROBABLY not be used.  There may be some
cases where it could be used (as a fast_full_scan, not as a
"normal" index).  Since the deptno is not on the leading edge of
the index -- we must full scan something.  We will either full
scan the table OR we might full scan the index if any of empno,
ename, deptno is NOT NULL and you have analyzed the table and
the optimizer believes full scanning the index vs the table
would be more efficient.

3) a key preserved table is a table in a join that will not have
its rows "multiplied".  Eg: in the query:

select * from emp, dept where emp.deptno = dept.deptno;

assuming a primary key on dept(deptno) -- it is understand that
EMP is key preserved (eg: each emp row joins to AT MOST one dept
record, you will not ever see the SAME emp row two times in the
above query).  The DEPT table on the other hand is NOT key
preserved since it can and will appear more then one time.

We can update key preserved tables in join views, we cannot
(without the help of an instead of trigger) update non key
preserved tables.

See
http://asktom.oracle.com/pls/ask/f?p=4950:7:::::F4950_P7_SEARCH_CRITERIA:key+preserved
for more info.

4) I do not understand.  If you mean "the query used to return
data fast but over time as data has changed, it no longer does"
-- then the major thing you want to look at is the query plan of
the query to figure out how to make it more efficient (eg: you
are missing an index, you have not analyzed the table recently).
 Start with the query itself and look at database settings dead
last.  99% of all tuning is done at the query level.
December 27, 2000 Rama Subramanian G -- Thanks for the question regarding "Multiple Data Sources for a single data load", version 8.1.5
You Asked
Hi,

I'm working on Oracle 8.1.5 running on SCO UnixWare 7.1.0.

I have sets of data to be loaded into a table in my database.
These sets are from different sources (flat files, foxpro data
files etc).

In SQL Loader, how should I take care of this situation, if I
need to load data in a single go?

Regards,
Rama Subramanian G
and we said...
SQLLoader loads a file into (possibly) many tables.

It cannot take many files to load simultaneously.

You'll need to run sqlldr more then one time, once for each
datafile or you would need to write a preprocessor type program
yourself that combined all the files into a single file for
sqlldr.

You do not need a control file/input file - you can pass to
sqlldr the name of the input datafile on the command line using
"data=xxxx".  Note that there is nothing to be gained/lost
really by running sqlldr once versus many times if you are using
the conventional path loader as it would commit the batches of
rows anything (it would not either load or not load an entire
file but does it by batch anyway).  It is only if you are using
direct path loads that this might be an issue.

You can actually start all of the sqlldr's concurrently to load
all of the datafiles at the same time using separate sessions.
December 27, 2000 Andre -- Thanks for the question regarding "BACKED_UP column in DBA_TABLES", version 8.1.6
You Asked
This is the description on DBA_TABLES.BACKED_UP from the Oracle
Refernce:

BACKED_UP VARCHAR2(1) Has table been backed up since last change

Does it mean the table has been put in hot backup mode since the
last change ?

Thanks !
and we said...
No, this column is used by an INCREMENTAL export only.  Tables
cannot be backed up by a hot backup, only tablespaces.

Here is an example.  I did a complete export and then touched
EMP and DEPT:

tkyte@TKYTE816> select table_name, backed_up from dba_tables
where owner = 'SCOTT';

TABLE_NAME                     B
------------------------------ -
BONUS                          Y
CREATE$JAVA$LOB$TABLE          Y
DEPT                           N <-----
DEPT_EMP                       Y
DUMMY                          Y
EMP                            N <-----
IMAGE                          Y
JAVA$CLASS$MD5$TABLE           Y
RESTAURANT                     Y
RESTAURANTPROPERTY             Y
SALGRADE                       Y
T                              Y
USERS                          Y

13 rows selected.

Then, I did an incremental export

tkyte@TKYTE816> host exp userid=sys/manager inctype=incremental

Export: Release 8.1.6.0.0 - Production on Wed Dec 27 11:53:18
2000

(c) Copyright 1999 Oracle Corporation.  All rights reserved.

Connected to: Oracle8i Enterprise Edition Release 8.1.6.0.0 -
Production
With the Partitioning option
JServer Release 8.1.6.0.0 - Production
Export done in WE8ISO8859P1 character set and WE8ISO8859P1 NCHAR
character set

About to export the entire database ...
. exporting tablespace definitions
. exporting profiles
. exporting user definitions
. exporting roles
. exporting resource costs
. exporting rollback segment definitions
. exporting database links
. exporting sequence numbers
. exporting directory aliases
. exporting context namespaces
. exporting foreign function library names
. exporting object type definitions
. exporting system procedural objects and actions
. exporting pre-schema procedural objects and actions
. exporting cluster definitions
. about to export SYSTEM's tables via Conventional Path ...
. about to export DBSNMP's tables via Conventional Path ...
. about to export AURORA$ORB$UNAUTHENTICATED's tables via
Conventional Path ...
. about to export SCOTT's tables via Conventional Path ...
. . exporting table                           DEPT          4
rows exported
. . exporting table                            EMP         14
rows exported
....

and now emp and dept are "backed up"

tkyte@TKYTE816> select table_name, backed_up from dba_tables
where owner = 'SCOTT';

TABLE_NAME                     B
------------------------------ -
BONUS                          Y
CREATE$JAVA$LOB$TABLE          Y
DEPT                           Y
DEPT_EMP                       Y
DUMMY                          Y
EMP                            Y
IMAGE                          Y
JAVA$CLASS$MD5$TABLE           Y
RESTAURANT                     Y
RESTAURANTPROPERTY             Y
SALGRADE                       Y
T                              Y
USERS                          Y

13 rows selected.

but as soon as I modify the table again

tkyte@TKYTE816> update scott.emp set ename = upper(ename);

14 rows updated.

tkyte@TKYTE816> select table_name, backed_up from dba_tables
where owner = 'SCOTT';

TABLE_NAME                     B
------------------------------ -
BONUS                          Y
CREATE$JAVA$LOB$TABLE          Y
DEPT                           Y
DEPT_EMP                       Y
DUMMY                          Y
EMP                            N  <--------
IMAGE                          Y
JAVA$CLASS$MD5$TABLE           Y
RESTAURANT                     Y
RESTAURANTPROPERTY             Y
SALGRADE                       Y
T                              Y
USERS                          Y

13 rows selected.

It'll show as not backed up.

This feature of export (incremental and cumulative exports) is
deprecated and may not be supported in the near future.
December 28, 2000 Dinesh -- Thanks for the question regarding "Recovery...", version 8.1.5
You Asked
Hi Tom,

       Belated christmas wishes and advance new year wishes.

 well i got a doubt in incomplete recovery say i got a database
and that is backed up regularly and the database is in
archivelog mode. suddenly my databases crashes at some time
after the backup is taken, so wat i done was i restore the
database with old backup and then try to recover using recover
until cancel with the time option . i got an error stating that
a file is missing in archive log now wat to do for this..

my question is if we missed one archive logfile in between can
we recover it or not .. if can tell me the detailed steps

i hope u can help me out as u did in all my other questions .

waiting for ur reply ..

Thanx
Dinesh
and we said...
If you lost an archive file -- you can only recover UPTO but not
including and definitely not beyond that archive.

You can recover but only upto the point in time immediately
before that archived redo log file was created.  Once the
archive redo log chain is broken -- thats it, we have to stop,
rollback any outstanding work and open the database.
Review & Followup
Rating: 5
July 16, 2001
Reviewer: Sanjeev from California
Good One

December 28, 2000 Rama Subramanian G -- Thanks for the question regarding "FORMS - Format Mask, Documentation", version 6.0.5.0.2
You Asked
Hi,

I wish you a very happy New Year 2001.

I have two questions.

I'm using Forms Version 6.0.5.0.2, backend is Oracle 8.1.5 on
SCO UnixWare 7.1.0.

Q.1.  In Forms, I have a text item which is numeric.  Suppose it
contains a negative value, is there any way by which I can
suppress the negative sign on screen, and display it in some
other color?

Q.2.  Do we have any facility in Forms or in Developer Suite, to
aid in creating a technical document of the application
developed?  IF not, does Oracle have any separate tool to do
that?

Regards,
Rama Subramnian G.
and we said...
1) If this field is a "display only field" (eg: no data
input/updates via this field) this can be accomplished easily.
Lets say you have 2 visual attributes "RED" and "NORMAL".  You
have a block built on a table T with a column X.  X is the
column you want to have with no sign and in red when it is
negative.  You would:

o set the PHYSICAL -> VISIBLE attribute for t.x to NO in the
property sheet for that item

o add another item to the block T called "display_x" for example
and set its DATABASE -> DATABASE ITEM to NO.

o add a post-change trigger to the t.x item that looks like:

if ( :t.x < 0 )
then
    set_item_instance_property( 't.display_x',
        CURRENT_RECORD, VISUAL_ATTRIBUTE, 'RED' );
else
    set_item_instance_property( 't.display_x',
        CURRENT_RECORD, VISUAL_ATTRIBUTE, 'NORMAL' );
end if;
:t.display_x := abs( :t.x );

Now, when you query up this block -- t.x will not be seen on
screen but as it's values change based on the database query --
it'll fill in the display_x and set each cells color
appropriately.

If this field is READ/WRITE, hiding the minus sign would not
only be hard but would be very confusing for someone inputting
data -- you would have to give them some mechanism for saying
"this value is negative".

q2) We use a tool call Designer 2000 for that.  It can reverse
engineer existing forms and is in fact an environment for
generating forms from specifications as well.  See
http://www.oracle.com/ip/develop/ids/index.html?designer.html
for more info on that.
December 28, 2000 Veronica -- Thanks for the question regarding "Privileges", version 8.1.5
You Asked
Tom,
Our developers would like to be able to see the texts of the
package bodies, stored procedures, triggers, etc., but we DBAs
do not want them to be able to alter or execute them in the test
or production environments (we have development instance for
that). Is there such a privilege in Oracle that would give them
the desired access without jeopardizing the security
considerations?
and we said...
Grant select on DBA_SOURCE to <developer role>;

Or create a view of DBA_SOURCE that exposes just the schemas you
want them to be able to see and grant them select on that view.
December 28, 2000 Vinnie -- Thanks for the question regarding "RPC Call Error", version 8.1.5
You Asked
I have the following Procedures:
BOX A
CREATE OR REPLACE PROCEDURE rpc_call
IS
    v_notes incident.notes%TYPE;
        v_asset incident.asset%TYPE;
    v_incident_id    VARCHAR2(40) := '12-AFRL'
BEGIN
    rpc_test@AFRL.world(v_incident_id,v_notes,v_asset);
    dbms_output.put_line(v_notes||' '||v_asset);
END;
/

BOX B
set serveroutput on
create or replace procedure rpc_test(t_incident_id IN VARCHAR2,
                v_notes OUT VARCHAR2,
                v_asset OUT VARCHAR2)
IS
t_site        site.accryn%TYPE;
t_rowid        VARCHAR2(250);
    t_accryn    site.accryn%TYPE;
    PRAGMA          autonomous_transaction;
BEGIN
    /* GET default SITE */
    SELECT accryn INTO t_site FROM site
        WHERE default_site = 'Y';
        /* CHECK LOCAL incident FIRST */
    IF substr(t_incident_id,instr(t_incident_id,'-')+1) = t_site
THEN
        SELECT notes,asset INTO v_notes,v_asset FROM incident
        WHERE incident_id = t_incident_id;
    ELSE
SELECT accryn, rowid INTO t_accryn, t_rowid
        FROM incident_ref
        WHERE rowid = (SELECT max(rowid) FROM incident_ref
                WHERE incident_id = t_incident_id);
        t_call :=
'rpc_test@'||t_accryn||'.world('||CHR(39)||t_incident_id
                ||CHR(39)||
                ','||v_notes||
                ','||v_asset||')';
        --v_notes := t_accryn;
        --v_asset := t_call;
        EXECUTE IMMEDIATE t_call;
        --rpc_test@afrl.world(t_incident_id,v_notes,v_asset);

    END IF;
END;
/

When I run rpc_call

I get the following error:
ORA-900 - invalid SQL stmt
ORA-6512 - at "RPC_TEST" line 31

Yet when I take out the Automous Trans stuff & just
run rpc_test@afrl.world(t_incident_id,v_notes,v_asset);
it works fine?
and we said...
you need to wrap all plsql in begin/end; blocks.

execute immediate 'proc';

fails but

execute immediate 'begin proc; end;'

would work.

Please use bind variables --

        t_call := 'rpc_test@'||t_accryn||'.world(:1,:2,:3);';
        execute immediate 'begin ' || t_call || '; end;'
          USING t_incident_id, v_notes, v_asset;

not only avoids issues with quotes but makes optimal use of the
shared pool and will run faster.
December 28, 2000 john -- Thanks for the question regarding "Highwatermark", version 8.1.6
You Asked
Hi

Please List out the disadvantges of having high highwatermark.

Thanks in advance.

john.
and we said...
If the HWM of a table is very much above there the data is (eg:
i put 1,000,000 rows into a table, I then did a "delete from T"
-- the HWM of the table is at 1,000,000 rows and I actually have
0 rows) -- full scan operations on the table will consume a
large amount of time as we full scan the blocks UNDER the HWM.
December 28, 2000 Vivek -- Thanks for the question regarding "Nested tables", version 8.1.6.2.0
You Asked
Hi Tom ,
 Just a design approach question . What are the advantageous of
using nested tables over
1. Having 2 tables related by foreign key
2. Storing the nested table data as a delimited concatenated
string in a varchar column (if the estimated no. of rows in each
nested table is very low) .

Thanks
Vivek
and we said...
1) well, a nested table is really two tables related by a
foreign key under the covers.  The physical implementation of
nested tables is exactly a parent/child table pair.  See
http://technet.oracle.com/doc/oracle8i_816/appdev.816/a76976/adobjdes.htm#441428
for details.  So, a nested table has syntactically advantages
(and disadvantages) over a strictly relational implementation.
Which is best is upto you.

2) that would be terrible in my opinion.  I would use a VARRAY
before doing that.  Way too hard to maintain that.  A varray
stores the information in a big LOB column but lets you index
into it very easily.  a VARRAY is not stored as parent/child but
as a LOB that works like an array.  You might consider that
instead.
December 28, 2000 roni -- Thanks for the question regarding "the difference between select * and select 'X' and select null", version oracle8.0.5.1.0
You Asked
Hi Tom,
Thank you, your answers on all my questions were very helpful.
I have another one and I think this is a very simple, but I can
not find an answer on this.
This is example.

select ctn,ban,effective_date
from service s
where not exists(select 'X'
             from l@service_ban ls
             where s.ban = ls.ban
             and s.ctn = ls.ctn)

select ctn,ban,effective_date
from service s
where not exists(select *
             from l@service_ban ls
             where s.ban = ls.ban
             and s.ctn = ls.ctn)

select ctn,ban,effective_date
from service s
where not exists(select null
             from l@service_ban ls
             where s.ban = ls.ban
             and s.ctn = ls.ctn)

What will be the different between those selects.
and we said...
Nothing, they are exactly the same.  We do not fully retrieve
the row with the select *, we do no extra work for the select
'X' vs select NULL.  They are the same. (proof below)

I will say however that unless service is a very very small
table -- the performance of this query is questionable.  It'll
have to run that subquery on the remote system for every row in
the outer query.  You might want to look at alternatives for
performance reasons.

If the select * did more work, we would expect it to fully
resolve the row.  Well, by creating a table that has a row that
spans a block, we can show that the where not exists ( select *
) does not fully retrieve the row -- just looks at the head
piece.

Say you have a script A.sql:

----------------------------
set termout off

define last_val=0
column value new_val last_val
select a.name, b.value from v$statname a, v$mystat b where
b.value > 0
and a.statistic#=b.statistic#
and a.name = 'table fetch continued row'
/
set termout on
----------------------------

and b.sql:

----------------------------------
select a.name, b.value-&last_val
  from v$statname a, v$mystat b
 where b.value > 0
   and a.statistic#=b.statistic#
   and a.name = 'table fetch continued row'
/
-----------------------------------

and we run the following script:

ops$tkyte@DEV816> set echo on
ops$tkyte@DEV816> set verify off
ops$tkyte@DEV816>
ops$tkyte@DEV816> create table t
  2  ( x int,
  3    a char(2000) default '*',
  4    b char(2000) default '*',
  5    c char(2000) default '*' ,
  6    d char(2000) default '*' ,
  7    e char(2000) default '*' ,
  8    f char(2000) default '*'
  9  );

Table created.

ops$tkyte@DEV816> column a noprint
ops$tkyte@DEV816> column b noprint
ops$tkyte@DEV816> column c noprint
ops$tkyte@DEV816> column d noprint
ops$tkyte@DEV816> column e noprint
ops$tkyte@DEV816> column f noprint
ops$tkyte@DEV816>
ops$tkyte@DEV816> insert into t ( x ) values ( 1 );

1 row created.

ops$tkyte@DEV816> @a
ops$tkyte@DEV816> set termout off
ops$tkyte@DEV816> select * from t;

         X
----------
         1

ops$tkyte@DEV816> @b
ops$tkyte@DEV816> select a.name, b.value-&last_val
  2    from v$statname a, v$mystat b
  3   where b.value > 0
  4     and a.statistic#=b.statistic#
  5     and a.name = 'table fetch continued row'
  6  /

NAME                            B.VALUE-7
------------------------------ ----------
table fetch continued row               1

That shows a SELECT * from T should have 1 "table fetch
continued row" since the row spans a block...

ops$tkyte@DEV816>
ops$tkyte@DEV816> @a
ops$tkyte@DEV816> set termout off
ops$tkyte@DEV816> select * from dual
  2  where exists ( select * from t where x = 1 );

D
-
X

ops$tkyte@DEV816> @b
ops$tkyte@DEV816> select a.name, b.value-&last_val
  2    from v$statname a, v$mystat b
  3   where b.value > 0
  4     and a.statistic#=b.statistic#
  5     and a.name = 'table fetch continued row'
  6  /

NAME                            B.VALUE-8
------------------------------ ----------
table fetch continued row               0

that shows that the exists did not do a select * , it did a
"select NULL" really.  It just looks for a head piece (or lack
of a head piece)

ops$tkyte@DEV816>
ops$tkyte@DEV816> @a
ops$tkyte@DEV816> set termout off
ops$tkyte@DEV816> select * from dual
  2
ops$tkyte@DEV816> where exists ( select 'x' from t where x = 1
);
SP2-0734: unknown command beginning "where exis..." - rest of
line ignored.
ops$tkyte@DEV816> @b
ops$tkyte@DEV816> select a.name, b.value-&last_val
  2    from v$statname a, v$mystat b
  3   where b.value > 0
  4     and a.statistic#=b.statistic#
  5     and a.name = 'table fetch continued row'
  6  /

NAME                            B.VALUE-8
------------------------------ ----------
table fetch continued row               0

ops$tkyte@DEV816>
ops$tkyte@DEV816> @a
ops$tkyte@DEV816> set termout off
ops$tkyte@DEV816> select * from dual
  2  where exists ( select null from t where x = 1 );

D
-
X

ops$tkyte@DEV816> @b
ops$tkyte@DEV816> select a.name, b.value-&last_val
  2    from v$statname a, v$mystat b
  3   where b.value > 0
  4     and a.statistic#=b.statistic#
  5     and a.name = 'table fetch continued row'
  6  /

NAME                            B.VALUE-8
------------------------------ ----------
table fetch continued row               0

ops$tkyte@DEV816>
Review & Followup
Rating: 4
Excellent Question/Answer May 21, 2002
Reviewer: Bill Bunke from Madison, WI USA
I've always felt that the Oracle server was smart enough to figure this out
without the programmer having to resort to any variation on the EXISTS (SELECT *
. . .) syntax.

Bravo for proving this in such an elegant manner. Now if only this could be
shared on a very wide basis . . .

Thanks

December 29, 2000 rekha -- Thanks for the question regarding "reverse indexes", version 8.1.7
You Asked
any views  that  I can check  for reverse indexes ie will tell
me that they are reverse indexes?
and we said...
The column index_type from user_indexes will tell you this:

tkyte@TKYTE816> select index_name, index_type from user_indexes;

INDEX_NAME                     INDEX_TYPE
------------------------------ ---------------------------
T_IDX_R                        NORMAL/REV
December 29, 2000 Vladimir -- Thanks for the question regarding "CallableStatement", version 8i
You Asked
Hi Tom,
First, thanks for your help before!!! and I 've some problem
with call store procedure used CallableStatement, con you give
an example to call a store procedeure from Java but used:
 {? = call procedure_name [(?,?,..)] }
that means syntax for a procedure that returns a result with
parameters and also with no  parameters
 {? = call procdeure_name }
For exampel I write a procedure:
create or replace package show_user as
 procedure show_user ;
end;
/
show errors
create or replace package body show_user as
procedure  show_user
IS
xx VARCHAR2(10);
yy varchar2(10);
 BEGIN
  SELECT user INTO xx FROM dual;
  yy:=xx;
 END;
end;
/
show errors

and that procedure I would like to call through
 {? = call show_user.show_user }

thanks TOM ,
P.D. sorry that I trouble you so much!!
Vlad
and we said...
Well, to have a procedure that returns a result set -- it must
have some formal parameters!  Your example above doesn't return
anything -- it does all of the work in the procedure itself.  It
selects user into xx and then assigns xx to yy.  It accepts no
inputs, produces no outputs.

Here is an example that shows how to do what you are trying
above:

create or replace package demo_pkg
as
    type refcur is ref cursor;

    procedure get_cur( x in out refcur );
end;
/

create or replace package body demo_pkg
as

procedure get_cur( x in out refcur )
is
begin
    open x for select USER from dual;
end;

end;
/

And the java to interface with that would be:

import java.sql.*;
import java.io.*;
import oracle.jdbc.driver.*;

class curvar
{
  public static void main (String args [])
  throws SQLException, ClassNotFoundException
  {
      String query  =
           "begin demo_pkg.get_cur( :1 ); end;";

      DriverManager.registerDriver
          (new oracle.jdbc.driver.OracleDriver());

      Connection conn=
        DriverManager.getConnection
        // ("jdbc:oracle:oci8:@ora8idev",
         ("jdbc:oracle:thin:@aria-dev:1521:ora816dev",
          "scott", "tiger");

      CallableStatement cstmt = conn.prepareCall(query);
      cstmt.registerOutParameter(1,OracleTypes.CURSOR);
      cstmt.execute();

      ResultSet rset = (ResultSet)cstmt.getObject(1);

      while( rset.next() )
        System.out.println( rset.getString(1) );

      rset.close();
      cstmt.close();
  }
}
Review & Followup
Rating: 4
"CallableStatement" November 06, 2001
Reviewer: Fikile Kentane from South Africa, Johannesburg
Thanks Tom. This review helped me big time. Now I can proceed with my Web
Application project.

The only part I did not I understand is the this line "type refcur is ref
cursor;" on the package "demo_pkg" specification. I will post the question to
you later.

Thanks again!

December 29, 2000 KK -- Thanks for the question regarding "HTTP request", version 8.1.6
You Asked
Can I post a XML document to a web server via the
http request from Oracle 8i?
and we said...
The existing UTL_HTTP package in the database does not support
POST, only GET.  So, if you are using UTL_HTTP, no, you cannot
POST the xml, you can only put it in the query string (eg:
utl_http.request( 'http;//server/url?xml_doc=<tag>xml</tag>' )).

Java in the database (if you use a java stored procedure) can do
this easily with the http classes in java.

8.1.6 supports a package UTL_TCP which allows PLSQL to do
"sockets" as well.  You could open a connect to a webserver on
port 80, write out the POST request:

POST /url/.../.../...  HTTP/1.0
Content-Length: xxxx

<tag>xml document of xxxx bytes goes here</tag>

as well.
Review & Followup
Rating: 4
October 31, 2002
Reviewer: Ramon de Diego

December 29, 2000 Vipul -- Thanks for the question regarding "Export Problem", version 7.3
You Asked
Hi Tom

I am using Oracle Server 8.0.0.4 On the server machine.On the
client machine we are using Oracle Client 7.3.When we taking
export on client it gives error while exporting table:-
ORA-01003 Oracle error 1033 encounterd
No statement parsed

Pl. resolve it ASAP. I will be thankful to u.

Bye
and we said...
On the server, using svrmgrl, connect as internal or sys and run
the script:

$ORACLE_HOME/rdbms/admin/catexp7.sql

that'll create the views necessary for a version 7 export tool.
December 29, 2000 ted -- Thanks for the question regarding "backup control file ", version 8.1.6
You Asked
thomas,

there are two command -
I.  alter database backup control file to trace(most common,
produce readable text file in udump).
II. alter database backup control file to
'/u16/me/control_bkup';
this produce a file which is not readable and unix file command
tells me it is a file type 'data'

question,
1. can i generate a backup control file to trace(format I above)
to a different destination other than location of udump ?

2. what is output from option II used for(when do one use option
II command and for what purpose) ?

thnx ted chyn
and we said...
1) no, it goes to udump.  You can alter the user dump
destination to somewhere else, dump it, and reset it.  For
example:

tkyte@TKYTE816> alter system set user_dump_dest = 'c:\temp';
System altered.

tkyte@TKYTE816> alter database backup controlfile to trace;
Database altered.

tkyte@TKYTE816> alter system set user_dump_dest =
'c:\oracle\admin\tkyte816\udump';
System altered.

2) you can use the output of option II when recovering a
database if you do not have the current controlfiles.  See
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:1143434607537
....
Review & Followup
Rating: 5
Send readable controlfile to a different destination March 14, 2002
Reviewer: Laura Hollister from San Diego, CA
Thank you very much - I can usually count on your archives to have the answer to
my question.  I run nightly cold backups through OEM and want to save the
readable controlfile elsewhere.  Instead of needing a shell script to find the
last trace file and move it to the backup destination, I can script the
temporary change to udump path, output the file and set udump back.

December 29, 2000 bhalchandra -- Thanks for the question regarding "what is the use of 'BGM' ?", version forms 6.0.5.0.2
You Asked
forms 6.0.5.0.2
Question No. 1
--------------

In Developer 2000

what is meant by 'BGM' and what is the use of 'BGM' ?

============================================================
Question No. 2
--------------
I have created a table with following fields and constraints

create table Empmst
(ename varchar2(20),
 estatus varchar2(1) check in ('L',null)
);

I inserted 5 records with 'estatus=null' value.

Now I write a query

select ename,estatus from empmst where estatus !='L';

-the output of the query is 'NO ROW SELECTED'

even i try this also

select ename,estatus from empmst where estatus <> 'L';

-the output of the query is 'NO ROW SELECTED'

but when I change my query to

select ename,estatus from empmst where estatus is null;

-- now got the result.

Why it is not giving the result in the previous QUERY ?

============================================================

Question No. 3
--------------

Can I assign different Record Group to LOV at run time ?
The record group will contain same number of fields but with
differnt data type and size.

============================================================
Question No. 4
--------------

Can I change the query of record group at run time ?
For this 'Populate_group_with_query ' built_in is suitable or
not ?
and we said...
1) BGM is the "background menu" -- a hidden menu that could have
function keys associated with it.  It is pretty much obsolete in
forms 6.

2) SQL has this thing called tri-valued logic.  The result of a
comparision is either:

o true
o false
o UNKNOWN

You can observe this via:

tkyte@TKYTE816> select * from dual where dummy = null;

no rows selected

tkyte@TKYTE816> select * from dual where dummy <> null;

no rows selected

tkyte@TKYTE816> select * from dual;

D
-
X

See -- "X" is neither equal to null nor is it NOT EQUAL to null.
 It is UNKNOWN wheter 'X' = NULL is true or false.  This is the
way SQL works.  Watch out for NULLS!

3) Yes HOWEVER the names AND types (but not sizes) of the
columns used by the record group MUST be the same.  When you
create the record group, you'll want to do something like:

select to_char(num_field) c1 from T1;

select char_field c1 from T2;

to make them have the same column names and both return
character strings.  If you do not do this, you'll get an error
at runtime.

See the function:

set_lov_property( 'lov name', GROUP_NAME, 'RG name' );

for more info.

4) yes, you can create and populate the record group at runtime.
 That function is suitable.
December 29, 2000 Andre -- Thanks for the question regarding "Unique and PK constraints using a non-unique index", version 8.1.6
You Asked
How does Oracle "enforce" the uniqueness of unique and PK
constraints using a non-unique index in Oracle8i ?

I understand Oracle used the "uniqueness" mechanism of the index
iteself to force such constraints. But since the index is not
unique any longer, where does this complexity go to ?

Oracle demands that, in this case, the PK columns form the
leading edge of the non-unique index.

Could it be then that the internal indexing mechamism in 8i is
modified as to to force this leading edge to be unique ?

Thanks !
and we said...
The database will use the index to verify that the entry is
unique rather then relying on the index itself.  That is -- a
manual check will be made.

We utilize these non-unique indexes especially when doing a
deferred constraint.  Consider:

tkyte@TKYTE816> create table t
  2  ( x int primary key deferrable )
  3  /

Table created.

tkyte@TKYTE816>
tkyte@TKYTE816> set constraints all deferred;

Constraint set.

tkyte@TKYTE816>
tkyte@TKYTE816> insert into t values ( 1 );

1 row created.

tkyte@TKYTE816> insert into t values ( 1 );

1 row created.

tkyte@TKYTE816> insert into t values ( 1 );

1 row created.

tkyte@TKYTE816> insert into t values ( 1 );

1 row created.

tkyte@TKYTE816> insert into t values ( 1 );

1 row created.

tkyte@TKYTE816>
tkyte@TKYTE816> update t set x = rownum;

5 rows updated.

tkyte@TKYTE816>
tkyte@TKYTE816> commit;

Commit complete.

Here we needed a non-unique index on the column X to allow the
many values of 1 to be inserted simultaneously.  Just as long as
at commit time they are all unique we are OK.  We use the index
to help us ensure they are unique instead of using it to enforce
the uniqueness for us.
December 29, 2000 Andey -- Thanks for the question regarding "get user list created by another user", version 7.3
You Asked
Hi,

Is there any way I can get the list of users which are created
by another user? For example, how can I know how many users and
who are the users created by DBA or some other user? Thanks a
lot. Happy New Year!

Andey
and we said...
You would have to enable auditing in order to capture this type
of information.  We do not store who created a user -- just that
they are created and when.

It will only work for "future" creates -- as audit trail entries
could be made for future create user commands but not for the
ones that have already happened.
December 29, 2000 wallacel -- Thanks for the question regarding "latch misses", version 8.1.6
You Asked
Tom:

when analyze latch misses, we don't care how many misses it
have,
what we really care is misses/gets, normally if it is greater
than 1% , then we need to take care of it, am i right?

if this is the case, the "Top latch misses chart" in
performace manager is misleading, because it only give us
top 10 misses, I think it should give us top 10 misses/gets,
it makes more sense, am i right?
and we said...
I agree with you yes and no.  It is a matter of percentages
sometimes and raw numbers other times.

If the misses are exceptionally high -- then no matter the
percentage, you spent a lot of time waiting for them to this
chart is still relevant.

Lets say you have 10 gets and 1 miss for latch X.  You have
100,000 gets and 100 misses for latch Y.  I'd rather in this
case tune around latch Y which has 0.1% miss rate. The miss rate
on latch X is 10% (one hundred times higher) but it only
happened once!  who cares about that one time in this case.

You sort of need both numbers to find the "worst" offenders.
Starting with the one that waited the most and working on
reducing that is as valid (sometimes more so) then finding the
one with the highest percentage wait.
December 29, 2000 Karla -- Thanks for the question regarding "Oracle 9i", version Oracle 9i
You Asked
What is the best way for us to obtain a developers kit for
Oracle 9i?
and we said...
You can get the 9i iAS (application server) from
http://technet.oracle.com/
now.  Oracle9i the database will not be available until the
first half of 2001.
December 29, 2000 Steven -- Thanks for the question regarding "Datafiles", version 8.0.5.
You Asked
I was curious as to the best setup for datafiles in a
tablespace. Is it better to have fewer larger datafiles or more
smaller datafiles in a tablespace. I know that an extent has to
be in one datafile, so the datafiles need to be big enough to
hold the largest possible extent. My server is running RAID 5,
Windows NT, so I have no control over what disks the datafiles
reside on, outside of what logical partition. My question is
what are the pros and cons of fewer large or more small
datafiles?
and we said...
I like to let my datafiles grow to be 2gig (and no more) in
size.  I use autoextend frequently, set the maxsize to 2gig and
when we hit it, I add another datafile.

The maximum extent size in Oracle is 2gig so thats not an issue.

I don't like to let them go over 2gig because

o some utilities have a hard time with files that big

o if I lose a file, It takes longer to restore and roll forward
a 10gig file then a 2gig file.  This helps limit my media
recovery time in the event of a media failure of some sort
(corrupt file, whatever)

Just my 2cents worth, this is really mostly a matter of opinion.
December 29, 2000 Matthew -- Thanks for the question regarding "Database Creation Script", version 8.1.6
You Asked
How can i generate a sql script from an existing database in
order to create the database on another server?

Do i need a utility to perform this task?

Thanks for your help!
matthew
and we said...
If you are trying to "clone" a database and the operating
systems are the same, simply backup the one database and restore
it on another machine.  that would be the fastest and easiest.

If they are not compatible, you would use dbassist to create a
new database, take a FULL export of the existing database and
perform an IMP of that.  That'll create the users, the
tablespaces, everything for you based on the old systems
structure.


Subject | Article | Last Updated (East coast time)
group by | article only | Dec 30, 2000 10:27 am
Data porting from MS Access to Oracle 8.0 | article only | Dec 30, 2000 11:43 am
Unique and PK constraints using a non-unique index (contd) | article only | Dec 30, 2000 11:47 am
Drpping primary key constraint | article only | Dec 31, 2000 12:56 pm
Snapshot too old error - more explanation | article only | Dec 31, 2000 01:12 pm
row(s) 1 - 5 of 5
December 30, 2000 Ken -- Thanks for the question regarding "group by ", version 8.1.5
You Asked
Hi Tom,

Happy Holidays !!!

Your answer to following question would be much appreciated:

I got 3 tables

table a
col. name                   col. value
C_EVENT_ID                   1
C_EVENT_TYPE_ID              1
C_ATTRIBUTE_ID               2
C_ATTRIBUTE_VALUE           656565

table b
col. name                   col. value
C_EVENT_ID             1
C_ENTRY_DATE           01/01/2000
C_ENTRY_NUMBERS        3

table c
col. name                   col. value
C_EVENT_TYPE_ID         1
C_EVENT_TYPE_DESC      view bills

All the c_event_type_id in table a are defined in table c, If
table c has only 1 row, I can ignore it and have something like

select c_entry_date, sum(c_entry_number) "# of view bills"  from
table a, table b where a.c_event_id = b.c_event_id group by
c_entry_date

But if there 's more than 1 c_event_type_id how can get it to
display :

c_entry_date, C_EVENT_TYPE_DESC(1) "view bills" ,
c_EVENT_TYPE_DESC(2) ....

By the way Tom, can I spool to a file in pl/sql ?.

Thanks
Ken
and we said...
Well, you didn't say if it OK or not to use varrays so I'll
assume it is OK.  Here is how to do that:

tkyte@TKYTE816> create table table_a
  2  ( c_event_id int,
  3    c_event_type_id int,
  4    c_attribute_id int,
  5    c_attribute_value  int
  6  )
  7  /
Table created.

tkyte@TKYTE816> create table table_b
  2  ( c_event_id int,
  3    c_entry_date date,
  4    c_entry_numbers int
  5  )
  6  /
Table created.

tkyte@TKYTE816> create table table_c
  2  ( c_event_type_id int,
  3    c_event_type_desc varchar2(25)
  4  )
  5  /
Table created.

tkyte@TKYTE816> create or replace type myArray as varray(512) of
varchar2(25)
  2  /
Type created.

tkyte@TKYTE816> insert into table_a values ( 1, 1, 2, 656565 );
tkyte@TKYTE816> insert into table_b values ( 1, trunc(sysdate),
3 );
tkyte@TKYTE816> insert into table_c values ( 1, 'event a' );
tkyte@TKYTE816> insert into table_c values ( 1, 'event b' );
tkyte@TKYTE816> insert into table_c values ( 1, 'event c' );

tkyte@TKYTE816> select c_entry_date,
  2         cast(
  3           multiset( select c_event_type_desc
  4                       from table_c
  5                      where table_c.c_event_type_id =
  6                        (select table_a.c_event_type_id
  7                           from table_a
  8                          where table_a.c_event_id =
  9                       table_b.c_event_id )) as myArray ) c2
 10    from table_b
 11  /

C_ENTRY_D C2
--------- ----------------------------------------
30-DEC-00 MYARRAY('event a', 'event b', 'event c')

You cannot issue the SPOOL command from plsql but PLSQL output
can be spooled -- you would issue the spool, run the procedure
in sqlplus and anything it writes with dbms_output will goto the
screen (if you have set serveroutput on in sqlplus) and will get
spooled.

To do real file io from plsql, you would use UTL_FILE.  Search
for UTL_FILE on my site for various examples.
December 30, 2000 Lakshman -- Thanks for the question regarding "Data porting from MS Access to Oracle 8.0", version 8.0
You Asked
Hi Tom,

Please tell me the best way to Port Data from MS Access table to Oracle 8.0
table.

Lakshman
and we said...
See
http://technet.oracle.com/software/tech/migration/workbench/software_index.htm
for a MS Access to Oracle migration toolkit and papers.
December 30, 2000 Andre -- Thanks for the question regarding "Unique and PK constraints using a non-unique index (contd)", version 8.1.6
You Asked
Thanks for your answer to my previous question on unique and PK
constraints using a non-unique index:
http://osi.oracle.com/wa/ask/owa/ask_tom_pkg.display?p_dispid=1227836429560
Oracle8 already had the deferrable constraint feature, but did
not use non-unique indexes to enforce unique and PK constraints,
since, as far as I know, this is a new feature in Oracle8i.

Questions:

1) So, did Oracle8 use another kind of mechanism to implement
deferred constraints or maybe the use of non-unique indexes was
undocumented then ?

2) Must I explicitly use non-unique indexes to implement
deferred constraints in Oracle8i or is it done automatically
when I just declare a constraint as deferred ?

3) Or do deferred constraints not necessarily use non-unique
indexes in Oracle8i ?

Thanks !
and we said...
1) Oracle8 used non-unique indexes for primary key constraints
when it needed to:

ops$tkyte@8.0> create table t ( x int primary key deferrable );
Table created.

ops$tkyte@8.0> select index_name, UNIQUENESS from user_indexes;

INDEX_NAME                     UNIQUENES
------------------------------ ---------
SYS_C0026462                   NONUNIQUE

ops$tkyte@8.0> select * from v$version;

BANNER
----------------------------------------------------------------
Oracle8 Enterprise Edition Release 8.0.3.0.0 - Production
PL/SQL Release 8.0.3.0.0 - Production
CORE Version 4.0.3.0.0 - Production
TNS for Solaris: Version 8.0.3.0.0 - Production
NLSRTL Version 3.3.0.0.0 - Production

2) using deferrable will create a non-unique index as
demonstrated above.

3) deferrable UNIQUE and PRIMARY KEY constraints use non-unique
indexes in Oracle8.0 and up.
December 31, 2000 Venkat -- Thanks for the question regarding "Drpping primary key constraint", version 7.3.2
You Asked
Is there a way to drop primary key constraint without dropping
the associated Unique Index?

We are facing this situation in a Data Warehouse installation.
We had used disable/ enable constraints as a way to trap invalid
records. We had done this as a general rule for all type of
validations. As the size of the database grew, we are having
performance issues. After reviewing the design, we have
identified a set of primary keys which are guaranteed in terms
of data cleansing, hence we want to remove them. We don't want
to drop the index,since the index could be used in any query/
ETL scenario. We can always drop the constraint and create
another index - we wanted to avoid this step if possible since
creating index also takes quite a bit of time and we want to
implement this with minimal end user impact.
and we said...
If the data is "gauranteed" then having the constraint + the
unique index is not more or less performant then just having the
index.

In this case, there would be NOTHING gained by not having the
constraint but having the index.  Don't disable these
constraints that are "gauranteed" -- just leave them be and
things will be as if the constraint did not exist.  A primary
key constraint in 7.3 is simply a UNIQUE INDEX + NOT NULL
constraint -- nothing more and nothing less.  If you left the
index but got rid of the constraint, our code path would be
identical, same amount of work!
December 31, 2000 Ravi -- Thanks for the question regarding "Snapshot too old error - more explanation", version 815
You Asked
Dear Tom,

I have a condition like this. We have a table with 30 columns
and we are interested in adding another 7 columns to it. The
table is roughly large like 400million rows.

After adding another 7 columns we would like to update the 7
columns of all the rows using a tool. This tool commits at
predetermined number of rows.

At the same time, users also query the same table, but limited
to the old 30 columns and not the new 7 columns. No user do any
DML on this table. This query  also returns large rows and takes
2 to 3 hours to complete in a data ware house env.

I read in a backup and recovery book that for an update of a
row, only the prior image of the updated columns would be stored
 in the rollback segment-- not the entire row. Then I assume
that, in this case the prior image of the 7 columns of the
update rows.

I would like to clarify the following:

At time t1, a query  q1, started reading the old 30 columns

At time t2, an update occurs on the 7 newly addded columns for
some rows

At time t3, commit occurs and the portion of the rbs for this
transacion is wrapped (or overwritten) due to some other
reasons.

At time t4, the same query  q1, tries to read the 30 non updated
columns of the updated rows.

Will oracle check the rollback segment for read consistency and
give "the snapshot too old error" or
Oracle will not go for the rollback segment at all since the
query donot try to read the updated columns.

Could you please tell how oracle maintains the read consistency.

Please give your comment at the earliest possible.

Thanks
Ravi
and we said...
We do the read consistency at the block level, not the column
level so yes -- the rollback segments would be checked at that
point in time.  We reconstruct the block as it appeared at the
time your query began.  We do not bother to check (in fact there
would be insufficient data to check if you overwrite the
rollback) if the particular COLUMNS you desire have been
modified.  There is no way for us to do this.

Your choices are:

o suffer the inevitable ora-1555's you will get on the long
running queries.

o size a rollback segment sufficiently large to hold the
rollback generated by the update WITHOUT committing and use this
rollback segment specifically.  This will avoid the ora-1555's
during the update.  drop the rbs after you no longer need it.

o size the rollback segments to be large enough to not wrap in a
3-4 hour period.  Make them this big BEFORE you start updating
(do not rely on them extending -- extend them yourself).  This
will avoid the ora-1555.

o since adding 7 columns and then updating them will undoubtably
cause MASSIVE row chaining, almost every row in this table will
migrate I am sure, consider building the table in its entirety
off to the side as a combination of OLD table and the NEW
updated rows -- do this as a CREATE TABLE AS SELECT with the
unrecoverable option (instead of updating these 7 columns,
perform the logic in the SELECT portion of the create table as
select you would have done during the update).  Index this table
using parallel unrecoverable index creates.  rename the OLD
table to T_OLD.  Rename this new table to T.  Drop the old table
after you are convinced all is well.  In order to do the DDL to
rename -- you will have to find a short period where no one is
querying the table.  This will result in a nicely rebuilt,
unchained table and no ora-1555's and a very very short downtime
window.
Review & Followup
Rating: 5
Excellent Solution, Small question to this July 28, 2001
Reviewer: Sreekanth from NJ, USA
The solution is excellent, I guess the down time of the table is affordable
compared to the frequent failures with 1555 error. It also avoids future
performance problems on the table.

Hi Tom,

Just in case we assume the table is not partitioned. How about partitioning  it
? while we do the re-building of the table . Will that reduce any down time  in
this scenario ?Or does it have any other side effects ? Please clarify

Thanks


Oracle9i SQL Reference

雪狼 作品

资料来源

资料来源：http://asktom.oracle.com

收集整理：Snowywolf

整理时间：2004-01

版权声明

您可以自由地将此文档复制发行，但请保留此声明页。

请勿将此文档用于任何商业用途。

联系作者

ITPUB号：Snowywolf

E m a i l：lisj@supermap.com

N a m e ：李绍俊

雪狼 作品