My blog has moved!

You should be automatically redirected in 5 seconds. If not, visit
http://www.oraexplorer.com
and update your bookmarks.

Monday, December 29, 2008

Ubiquity for Oracle

Ubiquity is the FireFox extension allowing you to perform tasks including wiki, map, dictionary, etc., while still staying on the same web page (instead of having to jump around pages).

Even though it is still in version 0.1.x, there is a quite number of commands (at Ubiquity Herd and Ubiquity In The Wild) being developed to use it.

Couple of them are developed as search tools for Oracle -

The first one "oradoc" (I like the most) is developed by Eddie Awad. With preview feature, it is easier to filter out information.

image

The second one "tahiti" is from Don Seiler at the Pythian group. This one has no preview. Thus upon pressing "Enter", it will redirect to Oracle's Tahiti site.

image

image

Last one "search-oracle-docs" from Mayuresh Kadu's blog site is similar to that of Tahiti - no preview but redirected to the OTN's documentation site.

image

image

Tuesday, December 23, 2008

Generating HTML reports from SQL Plus

Last week I was asked by one of IT managers on how to generate reports from database. He'd like to remind his direct reports on ticket's backlog status. His requirement is just simply to run a simple SQL statement and email the result out weekly. I quickly told him that you can just cron or schedule the script. "Hold on! I'm not finished yet," he said. If possible, he'd like to have some report data color-coded so everyone can be visually reminded of meeting or missing goals. "And lastly, if possible, report should be formatted nicely - not just in plain text," he added.

Um...

This is the sample of report I tried to assist him. The required features would include a company logo, color-coded report data based on thresholds, and URL link on ID.

image

To have the query result in the html format, fortunately, the SQL Plus provides the "markup html" feature since version 8.1.6. There have been a quite number of discussions about this already. But the best place for reference is at Oracle SQL Plus User's Guide and Reference web site.

I started out with the current configuration of the markup html which by default is OFF.

SQL> show markup
markup HTML OFF HEAD "<style type='text/css'> body {font:10pt Arial,Helvetica,sans-serif; color:black; background:White;} p {font:10pt Arial,Helvetica,sans-serif; color:black; background:White;} table,tr,td {font:10pt Arial,Helvetica,sans-serif; color:Black; background:#f7f7e7; padding:0px 0px 0px 0px; margin:0px 0px 0px 0px;} th {font:bold 10pt Arial,Helvetica,sans-serif; color:#336699; background:#cccc99; padding:0px 0px 0px 0px;} h1 {font:16pt Arial,Helvetica,Geneva,sans-serif; color:#336699; background-color:White; border-bottom:1px solid #cccc99; margin-top:0pt; margin-bottom:0pt; padding:0px 0px 0px 0px;} h2 {font:bold 10pt Arial,Helvetica,Geneva,sans-serif; color:#336699; background-color:White; margin-top:4pt; margin-bottom:0pt;} a {font:9pt Arial,Helvetica,sans-serif; color:#663300; background:#ffffff; margin-top:0pt; margin-bottom:0pt; vertical-align:top;}</style><title>SQL*Plus Report</title>" BODY "" TABLE "border='1' width='90%' align='center' summary='Script output'" SPOOL OFF ENTMAP ON PREFORMAT OFF

This looks like it is a lot, but actually it is just a bunch of CSS syntaxes which control how the data content to be formatted. If you re-arrange it, it should look like this -

markup HTML ON HEAD "<style type='text/css'> -
body { -
  font:10pt Arial,Helvetica,sans-serif; -
  color:black; background:white; } -
p { -
  font:8pt Arial,sans-serif; -
  color:grey; background:white; } -
table,tr,td { -
  font:10pt Arial,Helvetica,sans-serif; -
  text-align:right; -
  color:black; background:white; -
  padding:0px 0px 0px 0px; margin:0px 0px 0px 0px; } -
th { -
  font:bold 10pt Arial,Helvetica,sans-serif; -
  color:#336699; -
  background:#cccc99; -
  padding:0px 0px 0px 0px;} -
h1 { -
  font:16pt Arial,Helvetica,Geneva,sans-serif; -
  color:#336699; -
  background-color:White; -
  border-bottom:1px solid #cccc99; -
  margin-top:0pt; margin-bottom:0pt; padding:0px 0px 0px 0px;} -
h2 { -
  font:bold 10pt Arial,Helvetica,Geneva,sans-serif; -
  color:#336699; -
  background-color:White; -
  margin-top:4pt; margin-bottom:0pt;} -
a { -
  font:9pt Arial,Helvetica,sans-serif; -
  color:#663300; -
  background:#ffffff; -
  margin-top:0pt; margin-bottom:0pt; vertical-align:top;} -
</style> -
<title>SQL*Plus Report</title>" -
BODY "" -
TABLE "border='1' width='90%' align='center' -
summary='Script output'" -
SPOOL OFF ENTMAP ON PREFORMAT OFF
Note that I added "-" (hyphen) so the tool will treat the next line as the continued line.

To make the query result to be in the html format, the "markup html" must be enabled - MARKUP HTML ON. Also, I disabled the ENTMAP to be OFF, so the SQL Plus won't replace special characters <,>, " and & with HTML entitles &lt;, &gt;, &quot; and &amp; respectively. This is needed so I can use the HTML tags in SQL statement. This could be done at the column level as well.

So this is the updated version with a "set" syntax to be ran at the SQL prompt -
$ cat /scripts/set_markup.sql
set markup HTML ON HEAD "<style type='text/css'> -
body { -
  font:10pt Arial,Helvetica,sans-serif; -
  color:blue; background:white; } -
p { -
  font:8pt Arial,sans-serif; -
  color:grey; background:white; } -
table,tr,td { -
  font:10pt Arial,Helvetica,sans-serif; -
  text-align:right; -
  color:Black; background:white; -
  padding:0px 0px 0px 0px; margin:0px 0px 0px 0px; } -
th { -
  font:bold 10pt Arial,Helvetica,sans-serif; -
  color:#336699; -
  background:#cccc99; -
  padding:0px 0px 0px 0px;} -
h1 { -
  font:16pt Arial,Helvetica,Geneva,sans-serif; -
  color:#336699; -
  background-color:White; -
  border-bottom:1px solid #cccc99; -
  margin-top:0pt; margin-bottom:0pt; padding:0px 0px 0px 0px;} -
h2 { -
  font:bold 10pt Arial,Helvetica,Geneva,sans-serif; -
  color:#336699; -
  background-color:White; -
  margin-top:4pt; margin-bottom:0pt;} -
a { -
  font:9pt Arial,Helvetica,sans-serif; -
  color:#663300; -
  background:#ffffff; -
  margin-top:0pt; margin-bottom:0pt; vertical-align:top;} -
.threshold-critical { -
  font:bold 10pt Arial,Helvetica,sans-serif; -
  color:red; } -
.threshold-warning { -
  font:bold 10pt Arial,Helvetica,sans-serif; -
  color:orange; } -
.threshold-ok { -
  font:bold 10pt Arial,Helvetica,sans-serif; -
  color:green; } -
</style> -
<title>SQL*Plus Report</title>" -
BODY "<img src=http://www.acme.com/company_logo..gif>" -
TABLE "border='1' width='90%' align='center'" -
ENTMAP OFF SPOOL ON 
For ease of execution, I placed above syntax in a SQL file named /scripts/set_markup.sql which will be called when report runs.

I added new classes (".threshold-XXX") so different texts can be displayed into different colors based on defined thresholds. I also added the company logo's image on report under BODY section.

Please note that you can remove unneeded CSS formats, i.e., a{} or margins, to make script cleaner. However, for a demonstration purpose, I leave everything as is.

The report part /scripts/run_weekly_backlog_report.sql is something like this -
$ cat /scripts/run_weekly_backlog_report.sql
connect user/password
@/scripts/report_set_markup.sql
set pages 100
TTITLE LEFT _DATE CENTER '<h1>Weekly Top Backlog Report : Database Team NA Region</h1>' -
RIGHT 'Page:' FORMAT 999 SQL.PNO SKIP CENTER '<h2>Red = Backlog > 30 days, Orange > 10 days</h2>'
spool d:\temp\backlog_report.htm
select '<a href="http://www.acme-intra.com/pls/apex/f?p=100:3:::::PID:'||ID||'">'||ID||'</a>' ID,
DESCRIPTION, ASSIGNED_TO, OPEN_DATE,
CASE
  when SYSDATE-OPEN_DATE > 30 then
   '<span class="threshold-critical">'||to_char(trunc(SYSDATE-OPEN_DATE))||'</span>'
  when SYSDATE-OPEN_DATE > 10 then
   '<span class="threshold-warning">'||to_char(trunc(SYSDATE-OPEN_DATE))||'</span>'
ELSE
   '<span class="threshold-ok">'||to_char(trunc(SYSDATE-OPEN_DATE))||'</span>'
END BACKLOG
from TBL_TICKETS
where STATUS='Open'
order by SYSDATE-OPEN_DATE DESC;
spool off
exit
This will execute "set_markup.sql" first to enable markup html. For the rest, there is nothing unusual. The ID column is embedded with an URL, so users can view the content of the ticket if needed. Also please note the use of the <h1>, <h2> and <span class> tags to format data based on defined thresholds.

This script can be called just by using
sqlplus /nolog @/scripts/run_weekly_backlog_report.sql
The last thing is just put above syntax in a batch file and add sending email (using mail or blat for Windows) with the content of the spooled html file.

Thursday, December 18, 2008

11g OCP upgrade exam

I just passed the 11g OCP upgrade after many excuses to postpone it.

I have to admit I was nervous a little bit because the last Oracle exam I've taken was more than one year ago. I was struggling a little bit at first. I tend to read too quickly (= careless). So at the beginning I missed couple phrases in question especially those saying please select two (or more) answers. I just answered one and then clicked Next. Note that system won't prompt you if you answer less than what it is looking for, but it will prompt if your answer more. :-(  After about 30 minutes, I realized something was not right. Fortunately I still had just enough time to go back and fix it. Whew!

Sunday, December 14, 2008

See initialization parameters from memory

One of Oracle 11g's new features is an ease of capturing the initialization parameter values currently in memory into a file.

select pfile from memory;
select spfile from memory;
select pfile='/tmp/cur_pfile.ora' from memory;

This comes in handy when you'd like to quickly verify changes especially after executing "alter system set" with scope=memory.

It also lets you see the current values of memory allocation in the Automatic Memory Management (AMM). Note that those values are at the top of the list prefixing with "__" (double underscores).

In addition to that it allows you peek into the current values of some hidden parameters too. This is a good alternative to having to run a query like below; Sample below is looking for a value of the "_b_tree_bitmap_plans" parameter. I got this code from Coskan's blog.

col name format a20
col value format a7
col deflt format a7
col description format a10
select a.ksppinm name,
b.ksppstvl value,
b.ksppstdf deflt,
decode
(a.ksppity, 1,
'boolean', 2,
'string', 3,
'number', 4,
'file', a.ksppity) type,
a.ksppdesc description
from
sys.x$ksppi a,
sys.x$ksppcv b
where
a.indx = b.indx
and a.ksppinm like '\_%' escape '\'
and a.ksppinm='_b_tree_bitmap_plans'
order by name
NAME                 VALUE   DEFLT   TYPE    DESCRIPTIO
-------------------- ------- ------- ------- ----------
_b_tree_bitmap_plans TRUE    TRUE    boolean enable the
                                              use of bi
                                             tmap plans
                                              for table
                                             s w. only
                                             B-tree ind
                                             exes

Note that the output of "select pfile from memory" does not show all initialization values - just those currently in memory. If you're interested in finding out, the orafaq web site has the complete list of all initialization parameters including hidden ones of all versions as early as version 7.3.4.

Friday, December 12, 2008

First Error with OLE 5

I just have time to install Oracle Enterprise Linux (OLE) on VMWare. The first error I encountered after trying to login into the 11g (11.1.0.6) database is this -

[oracle@oralnx1 ~]$ sqlplus / as sysdba

sqlplus: error while loading shared libraries:

/opt/oracle/product/11.1.0/db_1/lib/libnnz11.so:

cannot restore segment prot after reloc:

Permission denied.


Well, I guess this is not a new error. I googled for it and found the answer on Ravi's blog (Thanks!!!). As Metalink note 454196.1 says, it is a bug due to more aggressive way that SELinux policies are enforced in RHEL 5 and OEL 5. The fix is to make SELinux is running in "Permissive" mode instead of its default "enforcing" mode. The syntax is provided in Metalink document.

[root@oralnx1 ~]# setenforce 0

[oracle@oralnx1 ~]$ sqlplus / as sysdba

SQL*Plus: Release 11.1.0.6.0 - Production on Fri Dec 12 08:14:32 2008

Copyright (c) 1982, 2008, Oracle. All rights reserved.

Connected to an idle instance.

Saturday, December 6, 2008

A new extended partition syntax in 11g

A new extended partition syntax can be used to designate a partition without knowing its name. The syntax must refer to a possible value for the partition. This syntax works for all cases when you have to reference a partition, whether it be range, list, interval, or hash. It supports all operations such as drop, merge, split, and so on.

Some samples are shown below -

create table SALES (
  id              number,
  order_date      date
)
partition by range (order_date)
(
  partition p1 values less than
  (to_date('01/01/2008','mm/dd/yyyy')),
  partition p2 values less than
  (to_date('02/01/2008','mm/dd/yyyy')),
  partition p3 values less than
  (to_date('03/01/2008','mm/dd/yyyy'))
);

Generally when you want to merge partitions, the syntax will have to refer to the partition names.

alter table SALES merge partitions
p2, p3
into partition p2_3; 

However, in 11g, the same can be accomplished by referring to a possible value for the partition with use of "for" syntax.

alter table SALES merge partitions
for(to_date('01/12/2008','mm/dd/yyyy')),
for(to_date('02/15/2008','mm/dd/yyyy'))
into partition p2_3;
SQL> select table_name, partition_name, high_value
from user_tab_partitions
where table_name = 'SALES';
TABLE_NAME PARTITION_ HIGH_VALUE
---------- ---------- ------------------------------
SALES      P1         TO_DATE(' 2008-01-01 00:00:00'
                      , 'SYYYY-MM-DD HH24:MI:SS', 'N
                      LS_CALENDAR=GREGORIA
SALES      P2_3       TO_DATE(' 2008-03-01 00:00:00'
                      , 'SYYYY-MM-DD HH24:MI:SS', 'N
                      LS_CALENDAR=GREGORIA

Or with dropping a partition -

SQL> alter table SALES drop partition
for(to_date('02/15/2008','mm/dd/yyyy'));
Table altered.
SQL> select table_name, partition_name, high_value
from user_tab_partitions
where table_name = 'SALES';   
TABLE_NAME PARTITION_ HIGH_VALUE
---------- ---------- ------------------------------
SALES      P1         TO_DATE(' 2008-01-01 00:00:00'
                      , 'SYYYY-MM-DD HH24:MI:SS', 'N
                      LS_CALENDAR=GREGORIA

Saturday, October 18, 2008

APEX - Requests to execute DML operations through "Automatic Row Processing (DML)" process

As a part of the button's properties, an execution of "Automatic Row Processing (DML)" process either INSERT, UPDATE or DELETE (assuming those operations are allowed) can be controlled by selecting an appropriate Database Action as shown below.

image

Many times, instead through a use of button, page submission is done by calling JavaScript "onSubmit" function. How will we select a DML's database actions through this approach?

APEX provides a way. The DML process will execute a requested database's action based on the request value containing one of the listed values here -

image

By default, the request value of a button is the button name itself. But for onSubmit function, the request value is what in the passing value. For example, onSubmit('SAVE') or onSubmit('APPLY CHANGES') will execute database's UPDATE operation.

The one I found the most useful is APPLY%CHANGES%. The wildcard allows the request value to be flexible.

I could use doSubmit('APPLY_CHANGES_D1') and doSubmit('APPLY_CHANGES_U1') to cause the update operation of all items of the current page. At the same time, it allows me to perform other different operations based on request values from using conditional processing.

The application I'm working on has two created-on-the-fly buttons in the "Display Only" item. The VIEW FILE link and Delete button are visible when file is stored in table. If not, only Upload button is visible.

  1: declare
  2:   v_link  varchar2(300);
  3: begin
  4: if :P8_UPLOAD_DOC_ID <> '0' then
  5:   select '<td><a href="#OWNER#.pr_download_file?p_file=' || :P8_UPLOAD_DOC_ID || '">VIEW FILE</a></td> <td><a href="javascript:confirmDelete(htmldb_delete_message,''APPLY_CHANGES_D1'');"> <img border="0" src="#WORKSPACE_IMAGES#delete.jpg" id="img_delete1"</a></td>'
  6:   into v_link
  7:   from PRODUCT
  8:   where ID = :P8_PRODUCT_ID;
  9: else
 10:   v_link := '<td></td> <td><a href="javascript:doSubmit(''APPLY_CHANGES_U1'')"><img border="0" src="#WORKSPACE_IMAGES#upload.jpg" id="img_upload1"></a></td>'; 
 11: end if;
 12:   return v_link;
 13: end;
 14: 

When either button is clicked, all item information on the form will be saved (through DML's update process). If Upload button is pressed, then page will be re-directed to the upload page. If Delete button is pressed, after confirmation, it will remove the actual file which is stored in a different table.

Monday, September 15, 2008

Programming for kids

I've been looking for a way to help my kid learning computer programming. My daughter and I tried out the trial version of "Phrogram" which is listed in the top hits when googling for "kid programming". It is nice, well-made and powerful by just looking at provided samples. Its look & feel and language look a lot like Visual Basic. But I think it is still considered as intermediate to advanced levels because you have to know syntaxes and actually typing them in. It would be definitely something I'd like her to learn if she grows up a little bit.

This week, I ran into this new open-source programming for kids called "Scratch" by MIT Media Lab. image Not only word "open source" interests me, the drag-n-drop feature makes it a lot easier to learn programming. Even though this is not really focusing on computer language learning, it, instead, emphasizes on developing design process skill which I think it is better in a long-term because it can universally apply not only to all programming languages but also other areas related to mathematic and science.

The other nice thing is the ability to upload and share your project on the web site.

Friday, August 15, 2008

Oracle APEX displays report's column heading 90 degree rotation

One of the cool things about Oracle APEX is ability to embed HTML tags into everything you could display. This includes simple HTML tags like

Add a break Employee<br>Name

Add color <font color="#FF0000">Employee Name</font>

image

Or more complex one like

Rotate 90 degree vertically (work with IE only)

<div style="writing-mode: tb-rl">Employee Name</div>

Friday, July 4, 2008

WOT - Web of Trust

Yesterday I just downloaded Firefox 3, which just set the Guinness World Records for the most software downloads in a day, and started looking around for its add-ons. This one is interesting and useful.

WOT (Web of Trust) is the free Internet security add-on for web browsers. The reputation ratings are categorized into four – trustworthiness, vendor reliability, privacy, and child safely. These ratings are ranked by the WOT web community. The goal is to helps make the Internet safer by sharing experiences.

The nice thing is the visual icons in different colors (green is good, red is bad) showing the web site’s ratings on search web sites like Google. This definitely helps me to proceed to the low-ranking web site cautiously.

clip_image002[5]

Have a safe surf.

Tuesday, June 24, 2008

A Million Thanks to Mom

My kid found this e-card on the Hallmark web site for the Mother's day. We really like the voices of hoops and yoyo - two cartoon characters. Since the card says, "A Million Thanks to Mom", we initially thought it'd probably be done by one million. But apparently it is not. So for fun, we let it run, and it keeps going and going. We've decided to let it continue to see how far it can go. Please note that it takes about one whole day to reach 1M on my desktop machine.




If you want to try out, here is the link, select "A Million Thanks for Mom".

Let me know how far you make it.

[Updated 6/3] Reached 3 millions and still going...
 


[Updated 6/4] Wow 4 millions now. Umm.. I don't know whether or not I should stop it, or let it continue.

 

[Updated 6/10] Now I'm reaching the 10 million “Thanks”. I can’t believe this thing can go on and on. I'm tempted to let it continue and see how far it can go.

[Updated 6/20] After about twenty days of this journey, I just reached 20 million Thanks. Wow..

My daughter urged me to continue. Well, let’s do it.

ThankYou20M_0620

[Update 6/23] Somehow, my XP desktop was rebooted unexpectedly over weekend :-( Well, I guess my 20-day “FUN” trip has to come to the end. It is sad but I feel relief because finally I can use my computer without annoying noises.

Sunday, June 15, 2008

Oracle SQL Developer Migration Workbench

The Oracle SQL developer is not only a great tool for SQL development, with its migration workbench, it is an excellent tool for database migration. Did I also mention it is free?

To get it started, you will need to download the latest version of the tool which is version 1.5.1. Also it is recommended to install the latest updates. The current release of update as of 6/15 is 1.5.1.54.40.

Next, you will need to create a repository. An database account, which has CREATE SESSION, RESOURCE, and CREATE VIEW must be created first. Then logon into SQL Developer as that account. From the tool, create a repository from Migration menu > Repository Management > Create Repository. This process creates a bunch of MD* and MIGR* tables and packages.

To connect to other non-Oracle databases, you will need to create connections through provided JDBC drivers. If somehow, your SQL Developer does not show these 3-rd party connection tabs, you will have to configure it. Instruction is clearly documented on Oracle site here.

image

In my case, I migrate one of our legacy applications on MS SQL to Oracle. Unfortunately this application contains column name named “rowid”, which is Oracle’s reserved word, in most of tables. The tool has a mechanism to append a suffix “_” (with no quotes) if it encounters these reserved words. So “rowid” will be converted to “rowid_”. To see the list of all reserved words, you can just query “KEYWORD” column in MIGRATION_RESERVEDW_WORDS table under the repository schema. Unfortunately, the “rowid” is not really in this table, I have to insert this manually. I added a keyword “privilege” as well because, again, there is a column named “privilege” used in application.

insert into migration_reserved_words values ('rowid');
insert into migration_reserved_words values ('privilege');
I encountered a bug (which Turloch O'Tierney pointed out - thanks) when using version 1.5.1 without the latest patch. In the function “first_char_check” under MIGRATION_TRANSFER package, a number “4” is missing. The impact of this is that If the column name is numeric prefix, for example, 3Q2008, a letter “A” will be prefixed into it to be “A3Q2008”. But due to this bug, it won’t do it with, for example, 4Q2008, resulting in a failure when trying to create table. With the latest patch, it seems like it was fixed already because I now see number 4.

v_allowed := C_DISALLOWED_CHARS || '012356789_$';

The process of migration is straight-forward. You will start with capture then convert. You can capture and convert the whole database at once. But I would not recommend that because if error is encountered, it might be difficult to troubleshoot.

You can just capture only the table first, this will create a converted script. Before running it, please inspect it first and comment un-needed sections especially CREATE default USER syntax and CONNECT using default user. By running the converted script, it will create the definitions of tables, sequences, triggers and constraints. If there is no error, then you can run to move data.

Once data is there, repeat the steps with stored procedures and views. Obviously, you will just need to run the converted script – there is no need for data movement.

Monday, June 9, 2008

Statistic Calculation - DBMS_STAT_FUNCS

Currently I'm working on a project dealing with lot of statistic calculations particularly that of quartiles. First, I have no idea what it is. Thanks to Wiki for explanation. Now the tough part is to do the actual calculation. Fortunately, Oracle provides DBMS_STAT_FUNCS which is exactly what I'm looking for.

List of available calculations -

TYPE summaryType IS RECORD (
count NUMBER,
min NUMBER,
max NUMBER,
range NUMBER,
mean NUMBER,
cmode num_table,
variance NUMBER,
stddev NUMBER,
quantile_5 NUMBER,
quantile_25 NUMBER,
median NUMBER,
quantile_75 NUMBER,
quantile_95 NUMBER,
plus_x_sigma NUMBER,
minus_x_sigma NUMBER,
extreme_values num_table,
top_5_values n_arr,
bottom_5_values n_arr);
Sample -
set serveroutput on;
DECLARE
sfsumtype dbms_stat_funcs.summaryType;
BEGIN
dbms_stat_funcs.summary(p_ownername=>'SCHEMA_NAME',
p_tablename=>'TABLE_NAME',
p_columnname=>'COLUMN_NAME',
s=>sfsumtype);
dbms_output.put_line('Quantile 5 => ' || sfsumtype.quantile_5);
dbms_output.put_line('Quantile 25 => ' || sfsumtype.quantile_25);
dbms_output.put_line('Median => ' || sfsumtype.median);
dbms_output.put_line('Quantile 75 => ' || sfsumtype.quantile_75);
dbms_output.put_line('Quantile 95 => ' || sfsumtype.quantile_95);
END;
/

Saturday, March 15, 2008

11g SQL*Plus

In 11g SQL*Plus, when session is terminated, somehow it displays the process ID, SID and Serial#. Not quite sure what is really for? I guess it is for debugging purpose.

10g Client

user @db10w1> select * from dual;
select * from dual
*
ERROR at line 1:
ORA-01012: not logged on

11g Client
user @db10w1> select * from dual;
select * from dual
*
ERROR at line 1:
ORA-01012: not logged on
Process ID: 0
Session ID: 135 Serial number: 29158

show spparameters

I found one of the interesting features in SQL*Plus 11g for Oracle11g database when doing “help show” from the tool.

SHOW  SPPARAMETERS [parameter_name]
This is similar to what we’re all familiar with but for spfile parameters instead.

Show specific parameters -
SYSTEM @db11r1> show spparameters sga

SID NAME TYPE VALUE
-------- ----------------------------- ----------- ----------------------------
* lock_sga boolean
* pre_page_sga boolean
* sga_max_size big integer
* sga_target big integer

Show all parameters -
SYSTEM @db11r1> show spparameters

SID NAME TYPE VALUE
-------- ----------------------------- ----------- ------------------
* O7_DICTIONARY_ACCESSIBILITY boolean
* active_instance_count integer
* aq_tm_processes integer 2
* archive_lag_target integer
* asm_diskgroups string
* asm_diskstring string
* asm_power_limit integer
* asm_preferred_read_failure_gr string
:
:
:
* use_indirect_data_buffers boolean
* user_dump_dest string
* utl_file_dir string
* workarea_size_policy string
* xml_db_events string
Originally I thought it is a feature of SQL*Plus 11g, but if I connect to the 10g database, it does not display anything. Note that error indicates that Server version too low for this feature.
SYSTEM @db10w1> show spparameters
SP2-0614: Server version too low for this feature
SP2-0735: unknown SHOW option beginning "lege'@'_co..."
SP2-0158: unknown SHOW option """
If database is started up with pfile, all values of “show spparameters” will be empty.

Tuesday, February 12, 2008

What is the current status of Data Guard?

While working in one of Data Guard projects, I was asked about the current sync status of standby. I started talking about gap, SCN, or applied and received archive log numbers, and so on, which obviously did not make sense to business users. The only thing they'd like to know is whether or not data at standby is up-to-date with that of primary, or if not, what date/time of standby data it is at right now.

All existing scripts we do have in house are just checking the received or applied SCNs or thread# of archive logs. In order to make sense out of these numbers for business users or managers, I will need to convert them into date and time. Fortunately, I recalled the "scn_to_timestamp" function which allows me to convert the SCN number to its corresponding timestamp.

I can get the current_scn from v$database of the standby. However, in the case of physical standby, when database is being mounted (recovery mode), this function does not work. It should work fine with the logical standby which is opened all the time.

SQL> select scn_to_timestamp(current_scn) from v$database;
select scn_to_timestamp(current_scn) from v$database
*
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-01219: database not open: queries allowed on fixed tables/views only
To resolve this, once getting the current_scn on standby, I can log on to the primary and get the time stamp corresponding to the SCN number.

Sample below is the KSH script to obtain the date/time based on a SCN. Note that the syntax to check the gap is added as well. The account connecting to primary just needs SELECT_CATALOG_ROLE.

# Get SCN number from DR
DRSCN=/tmp/drscn$$.log
${SQLPLUS} -s /nolog <<EOF
connect / as sysdba
set heading off
set feedback off
col current_scn format 999999999999999999999999
spool ${DRSCN}
select current_scn from v\$database;
spool off
exit
EOF
DR_SCN=`cat ${DRSCN}`

rm ${DRSCN}

# Get Timestamp from Primary
TSDR=/tmp/tsdr$$.log
TSSTAT=/tmp/tsstat$$.log
${SQLPLUS} -s /nolog &lt&ltEOF
connect user/password@PRIMARY
set heading off
set feedback off
spool ${TSDR}
select
to_char(scn_to_timestamp(${DR_SCN}),'MM/DD/YYYY HH24:MI')
from dual;
spool off
spool ${TSSTAT}
select
case
when
scn_to_timestamp(${DR_SCN}) > systimestamp - interval '1' hour
then 'OK'
when
scn_to_timestamp(${DR_SCN}) > systimestamp - interval '2' hour
then 'WARNING'
else 'CRITICAL'
end "STATUS"
from dual;
spool off
exit
EOF

rm ${TSDR}
rm ${TSSTAT}

Thursday, January 3, 2008

Unconventional way to create an Oracle database

This is so funny. It probably takes longer for the guy to create a database if he has a cold or flu.

http://www.youtube.com/watch?v=CHzV4LZnvHc

BTW, I like the name of database, "nosejob".

Friday, December 28, 2007

Select-only-privileged user can lock table

This is an interesting post by Tanel Poder on "Your read only accounts aren't that read only". Basically a read-only account with the select privilege only on a table can issue the lock on that table even though it does not have any DML privileges. This means that it could prevent any further DMLs (causing denial of service) to other valid sessions. This behavior is not new. But explanation, examples and work-around/semi-solution by Tanel are clear. Good Job!!!

Tuesday, December 4, 2007

SQL Plus Copy

The SQL*Plus COPY command can copy data between two databases via SQL*Net.

Syntax:

USER1 @srcdb> copy
usage: COPY FROM [db] TO [db] [opt] [table] { ([cols]) } USING [sel]
[db] : database string, e.g., hr/your_password@d:chicago-mktg
[opt] : ONE of the keywords: APPEND, CREATE, INSERT or REPLACE
[table]: name of the destination table
[cols] : a comma-separated list of destination column aliases
[sel] : any valid SQL SELECT statement
A missing FROM or TO clause uses the current SQL*Plus connection.
Sample:
@Target database, the table initially does not exist.
USER1 @targetdb> select * from rep_tab;
select * from rep_tab
*
ERROR at line 1:
ORA-00942: table or view does not exist
@Source database, run copy command within SQL Plus.
USER1 @srcdb> copy from user1/user1@srcdb -
> to user1/user1@target_host:1521/target_sid -
> create rep_tab -
> using -
> select * from rep_tab;

Array fetch/bind size is 15. (arraysize is 15)
Will commit when done. (copycommit is 0)
Maximum long size is 80. (long is 80)
Table REP_TAB created.

1 rows selected from user1@SRCDB.
1 rows inserted into REP_TAB.
1 rows committed into REP_TAB at user1@host1:1521/targetsid.

@Target database, now table is copied here.
USER1 @targetdb> select * from rep_tab;

A
----------
1

This is a quick and easy way to copy data between two databases especially on where the usage of database link is restricted. It only requires SQL*Net service name (or host/port/service) and proper privileges.

Friday, November 30, 2007

APEX to upload a text file and write into a table

One of the web development projects using Oracle APEX I’m working on is to upload the content of a text file in csv format into database. By default, all files using the “File Browse..” element will be uploaded to the “wwv_flow_files” table which has structure as follows -


SQL> desc wwv_flow_files
Name Type Nullable Default Comments
------------ -------------- -------- ------- --------
ID NUMBER
FLOW_ID NUMBER
NAME VARCHAR2(90)
FILENAME VARCHAR2(400) Y
TITLE VARCHAR2(255) Y
MIME_TYPE VARCHAR2(48) Y
DOC_SIZE NUMBER Y
DAD_CHARSET VARCHAR2(128) Y
CREATED_BY VARCHAR2(255) Y
CREATED_ON DATE Y
UPDATED_BY VARCHAR2(255) Y
UPDATED_ON DATE Y
LAST_UPDATED DATE Y
CONTENT_TYPE VARCHAR2(128) Y
BLOB_CONTENT BLOB Y
LANGUAGE VARCHAR2(30) Y
DESCRIPTION VARCHAR2(4000) Y
FILE_TYPE VARCHAR2(255) Y
FILE_CHARSET VARCHAR2(128) Y

Even though the text file contains character data, the uploaded file content will be stored in the “binary format” in a BLOB column named BLOB_CONTENT. Due to nature of BLOB, to read character out, the conversion using “chr” function is required. Please see a good article about this concept and conversion by Natalka Roshak on the orafaq at http://www.orafaq.com/node/895.

I modified the sample script provided in above article to suite my need – reading each line of the text file and insert into a target table.

DECLARE
v_blob_data BLOB;
v_blob_len NUMBER;
v_position NUMBER;
v_raw_chunk RAW(10000);
v_char CHAR(1);
c_chunk_len number := 1;
v_line VARCHAR2 (32767) := NULL;
v_data_array wwv_flow_global.vc_arr2;
BEGIN
-- Read data from wwv_flow_files
select blob_content into v_blob_data
from wwv_flow_files where name = 'F29800/Data_CSV.csv';

v_blob_len := dbms_lob.getlength(v_blob_data);
v_position := 1;

-- Read and convert binary to char
WHILE ( v_position <= v_blob_len ) LOOP
v_raw_chunk := dbms_lob.substr(v_blob_data,c_chunk_len,v_position);
v_char := chr(hex_to_decimal(rawtohex(v_raw_chunk)));
v_line := v_line || v_char;
v_position := v_position + c_chunk_len;
-- When a whole line is retrieved
IF v_char = CHR(10) THEN
-- Convert comma to : to use wwv_flow_utilities
v_line := REPLACE (v_line, ',', ':');
-- Convert each column separated by : into array of data
v_data_array := wwv_flow_utilities.string_to_table (v_line);
-- Insert data into target table
EXECUTE IMMEDIATE 'insert into TABLE_X (v1, v2, v3, v4)
values (:1,:2,:3,:4)'
USING
v_data_array(1),
v_data_array(2),
v_data_array(3),
v_data_array(4);
-- Clear out
v_line := NULL;
END IF;
END LOOP;
END;
/