Monday, 24 August 2020

Basic Walkthrough Oracle Part-5

 

Basic Walkthrough Oracle Part-5

In this part we will study some more useful database objects. For example, VIEWS, TRIGGERS, PROCEDURES and few other.

As we had an introduction to trigger creation in part 2, we will discuss how we run scripts first. Oracle supports different kind of scripts. You can run system shell scripts (.bat, .cmd, .js, .vbs,.sh and many more).  Let us try to understand how we can run scripts. Simple SQL script looks like

Create a file with .sql extension and save it on the disk. Then run it with ‘@’ prefix.

 



host notepad script.sql ;

@script.sql ;

select id,name,dept,job from total;

select count(*) from trans;

   WEEKNUM     INCOME    EXPENSE

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

        32      224.2       49.4

 

 

  COUNT(*)

----------

         5

 

This was a simple SQL script. This is to be run in command window. The syntax has been indicated in blue. Being an example script, I just listed few commands. In actual scripts these lines are usually over hundreds. Scripts can also be invoked in verbose mode (as echo on in DOS).

 

 

C:\Documents and Settings\sgill>echo.quit;|sqlplus -s user1/password1 @script2.sql

 

 

set lines 200;

select weeknum,income,expense, timeupdate from total;

 



This is not a common way, but with each script sqlplus will quit its shell as it encounters ‘quit’. So, feeding inline quit command to sqlplus takes effect after the execution of the script is completed.

The scripts are usually written for various tasks including generating daily reports. As a rule of thumb, add all the commands to script file that are to be repeated in future and invoke the script using one of above syntaxes.

Let us create another trigger on TRANS table (created in part 2) to ensure that user uses in or out keywords only in code column. Using anything else will be waste of data. So, we will try to reject entry if the code is not set properly.

sqlplus -S user1/password1 @trig2.sql

CREATE OR REPLACE TRIGGER Check_Code

 BEFORE INSERT ON TRANS

 FOR EACH ROW

BEGIN

   IF (upper(:NEW.CODE)<>'IN' AND upper(:NEW.CODE)<>'OUT') THEN

 

      raise_application_error (-20100, 'Code must be either "in" or "out"');

 

   END IF;

     

END;

/

quit;


 

This trigger will stop us from entering wrong ‘Code’ in TRANS table. This is to ensure that data entered will be usable by the trigger update_total trigger to update TOTAL tables.

 

set lines 200;

select * from total

   WEEKNUM     INCOME    EXPENSE TIMEUPDATE

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

        32      224.2       49.4 19-08-06 08:11:27.826000

 

insert into TRANS values (6, 120.00,'EN');

   insert into TRANS values (6, 120.00,'EN')

            *

ERROR at line 1:

ORA-20100: Code must be either "in" or "out"

ORA-06512: at "USER1.CHECK_CODE", line 4

ORA-04088: error during execution of trigger 'USER1.CHECK_CODE'

 

insert into TRANS values (6, 120.00,'In');

1 row created.

select * from total

WEEKNUM INCOME   EXPENSE  TIMEUPDATE

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

     32    344.2     49.4 19-08-06 11:53:30.972000

 

            Cool, the transaction was applied to TOTAL table when we entered the correct code. Remember we had used ‘case free’ iN and OuT key words. It will work with any case.

Let us try to have some flavor of VIEWS. As explained earlier the VIEW is combination of columns from different tables. We will create another table called PERSONS with names of all family members. Then we will create a view joining TRANS and PERSONS tables to save info about who had carried out the transaction. For this purpose, we will add a column PID to TRANS table.

alter table TRANS add PID CHAR(2)

Table altered.

Now create table PERSONS as below.

create table PERSONS (PID CHAR(2) not null primary key, FNAME CHAR(16), LNAME CHAR(12))

Table created.

Add some data to the table.

insert into PERSONS values (‘00’,’David’,’Boon’);

1 row created.

insert into PERSONS values (‘01’,’Marry’,’Boon’);

1 row created.

insert into PERSONS values (‘02’,’John’,’Boon’);

1 row created.

 

select * from persons;

 

PID FNAME            LNAME

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

00  David            Boon

01  Marry            Boon

02  John             Boon

 

Now we need to enter these PID in TRANS table to indicate who carried the transactions out. Let’s do that.

 

select * from TRANS;

 

        ID     AMOUNT CODE PI

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

         1     123.45 in

         2       34.4 out

         3        100 in

         4         15 out

         5        .75 in

         6        120 In

 

6 rows selected.

 

update TRANS set PID='00' where ID=1;

 

1 row updated.

 

update TRANS set PID='01' where ID=2;

 

1 row updated.

 

update TRANS set PID='00' where ID=3;

 

1 row updated.

 

update TRANS set PID='02' where ID=4;

 

1 row updated.

 

update TRANS set PID='02' where ID=5;

 

1 row updated.

 

update TRANS set PID='00' where ID=6;

 

1 row updated.

 

select * from TRANS

 

        ID     AMOUNT CODE PI

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

         1     123.45 in   00

         2       34.4 out  01

         3        100 in   00

         4         15 out  02

         5        .75 in   02

         6        120 In   00

 

6 rows selected.

 

                        Now we can create a view name trans_view to reflect name of the person instead of PID. PID is usually handy for use with managing multiple tables within database. Views are very handy and useful for creating end-user reports.     

 

    AMOUNT CODE FNAME            LNAME

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

    123.45 in   David            Boon

      34.4 out  Marry            Boon

       100 in   David            Boon

        15 out  John             Boon

       .75 in   John             Boon

       120 In   David            Boon

 

6 rows selected.

CREATE VIEW trans_view as SELECT t.AMOUNT,t.CODE,p.FNAME,p.LNAME from TRANS t, PERSONS p where p.PID=t.PID ;

 

View created.

 

select * from trans_view;

 

    AMOUNT CODE FNAME            LNAME

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

    123.45 in   David            Boon

      34.4 out  Marry            Boon

       100 in   David            Boon

        15 out  John             Boon

       .75 in   John             Boon

       120 In   David            Boon

 

6 rows selected.

 

            So, we had an idea how Views work. In actual practice, the views are rarely so simple. But the logic behind a view is always the same. JOIN tables to appear like one table. Please note that for simplicity of examples, we did not use TIMESTAMP column in TRANS table, which is mostly used to keep track of transaction along with some other more useful info.

            For simplest use of database system, we have already covered most objects. In actual usage I hardly need anything other than what we have covered so far. The other objects are for some more sophisticated actions. For example, PROCEDURES and FUNCTIONS are very useful but for the scope of this tutorial these will be covered in last parts.

Let’s discuss some of useful built-in functions.

 

LOWER

All the letters converted to lowercase.

UPPER   

All the letters in converted to uppercase.

LTRIM   

All spaces removed from the left.

RTRIM   

All spaces removed from the right.

SUBSTR 

Returns 'n' number of characters from string starting from the 'm' position.

LENGTH 

Number of characters in string is returned.

TO_CHAR(datetime)

TO_CHAR (datetime) function returns a datetime or interval value of DATE. TIMESTAMP, TIMESTAMP WITH TIME ZONE.

CURRENT_TIMESTAMP

The CURRENT_TIMESTAMP() function returns the current date and time in the session time zone, in a value of datatype TIMESTAMP WITH TIME ZONE.

SYSTIMESTAMP

The SYSTIMESTAMP function returns the system date, including fractional seconds and time zone.

RAWTOHEX

Converts raw to a character value containing its hexadecimal equivalent. The raw argument must be RAW datatype.

TO_CHAR

Converts Numeric and Date values to a character string value. It cannot be used for calculations since it is a string value.

TO_DATE

Converts a valid Numeric and Character values to a Date value. Date is formatted to the format specified by 'date_format'.

ABS (x)

Absolute value of the number 'x'

CEIL (x)

Integer value that is Greater than or equal to the number 'x'

FLOOR (x)

Integer value that is Less than or equal to the number 'x'

MOD

 returns the remainder of n2 divided by n1. Returns n2 if n1 is 0.

CHR

returns the character having the binary equivalent to n as a VARCHAR2 value in either the database character set or, if you specify USING NCHAR_CS, the national character set.

Basic Walkthrough Oracle Part-4

 

Basic Walkthrough Oracle Part-4

In previous part we had created the database (single table database) and populated the table with some data. The data seemed all right and we had nice time retrieving the data. Except one that (friend of friend)’s last name begins with small ‘w’. We will correct this and move on to creating triggers and other stuff.

Let us try updating the last name with capital ‘W’. We will see contents and update the row based on some unique parameters. Which means that while updating if our predicate selects more than one row, all selected rows will be updated. So be careful while identifying the target row.

Update ADDRESS SET LNAME=’Walker’ Where PHONE=’419-932-9322’

1 row updated.

Thank God. The correction was cool.

To have a look at the modified data issue the command: SELECT * FROM ADDRESS. The * basically means all columns.

select * from address;

FNAME            MNAME        LNAME            PHONE           CELL            ADDR

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

Tai                           Tang             647-647-6477    416-614-6144    64 Pluto Way Brampton,ON,CA

Sabar                         Raikoti          905-509-5099    419-914-9144    1032 Mavis Rd Mississauga,ON,CA

David            M.           Brown            905-264-2644    647-746-7466    1216 Morning Star Drive Miss,ON,CA

 

FNAME            MNAME        LNAME            PHONE           CELL            ADDR

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

Dilshaad         Sufi         Akhtar           905-932-9322    416-417-4177    3456 Horner Ave Etobicoke,ON,CA

Tai                           Tng              647-647-6477    416-614-6144    64 Pluto Way Brampton,ON,CA

John             D            Walker           419-932-9322    647-417-4879    promised help with JOB

 

6 rows selected.

When you look at above output you will find last name corrected. Secondly you see word ‘promised’ in ADDR column. That means you are free to insert any text in ADDR column. There is no CONSTRAINT set up. Usually there are no CONSTRAINTS in text fields like address.

There was an extra entry for Tai, with wrong last name (Tng). We did that intentionally to test behavior of primary key. Let us delete it.

Delete from ADDRESS where lname='Tng'

1 row deleted.

 

Select fname,lname,addr from address

 

FNAME            LNAME            ADDR

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

Tai              Tang             64 Pluto Way Brampton,ON,CA

Sabar            Raikoti          1032 Mavis Rd Mississauga,ON,CA

David            Brown            1216 Morning Star Drive Miss,ON,CA

Dilshaad         Akhtar           3456 Horner Ave Etobicoke,ON,CA

John             Walker           promised help with JOB

So, we have seen how to remove ROWS from a table. A word of caution. Do not use DELETE FROM ADDRESS. This will delete all rows. This command should always have where predicate to limit the rows being deleted.

The most liked part of database is input format routines. The user will enter the data and smart systems accept a wide variety of data in loose format and will try its best to format it strict before inserting into table. This seems that this is part of programming. Well, yes, but basic programming that can be handled in small triggers. So I will help you write trigger to adjust hyphens (‘-‘) in the input data when it is fed to PHONE and CELL columns. Please go over Oracle help center for triggers’ definition and syntax for more detail.

Next step will be to create a trigger to validate the data being input into the database table.

Create a text file with any extension having following SQL code in it. Do not worry about everything for now. Just create the trigger definition file and get it created. This trigger will check for existence of hyphens in appropriate position in phone numbers.

CREATE TRIGGER INS_CELL_PHONE

 BEFORE INSERT ON ADDRESS

 REFERENCING NEW AS N

 FOR EACH ROW

BEGIN

 IF (SUBSTR(:N.PHONE,4,1)<>'-' OR SUBSTR(:N.PHONE,8,1)<>'-'

        OR SUBSTR(:N.CELL,4,1)<>'-' OR SUBSTR(:N.CELL,8,1)<>'-' ) THEN

raise_application_error (-20100,'Phone Numbers Expected as 999-999-999');

END IF;

END;

/

Trigger created.

This will create a trigger which will look far hyphens (‘-‘) at specified locations.  If any of hyphens are missing, trigger will raise an error with message as specified as second parameter of raise_application_error function.

            To create the trigger from script, I suppose you have stored the file as INS_PHONE.TRIG in current folder. See the syntax and note that we had used @ character for calling the script.

@ins_phone.trig

Trigger created.

            Please note that to run SQL files you have to run it from SQLPLUS Command Line and not Windows cmd. These two windows are different although they look the same. If you are on windows cmd, then type sqlplus . So now trigger has been created which checks for ‘-‘  at 4th and 8th position in PHONE and CELL. If there is any one missing, trigger will force rejection of whole row and nothing will be added.

 

insert into address values ( 'Gurmit' ,'S', 'Randhawa', '416-742-9242','6477204020','1230 The Walkers

 Road')

ORA-20100: Phone Numbers Expected as 999-999-999

ORA-06512: at "USER1.INS_CELL_PHONE", line 4

ORA-04088: error during execution of trigger 'USER1.INS_CELL_PHONE'

 

Let us try little different. This time we won’t provide the CELL number.

 

insert into address values ('Gurmit', 'S', 'Randhawa', '416-742-9242','','1230 The Walkers Road')

ORA-20100: Phone Numbers Expected as 999-999-999

ORA-06512: at "USER1.INS_CELL_PHONE", line 4

ORA-04088: error during execution of trigger 'USER1.INS_CELL_PHONE'

Same, because trigger wants two hyphens in both numbers. So now you are forced tom enter the phone numbers exactly as 999-999-9999. By the way, we have designed the trigger just for practice, so we kept it simple; and you can provide any bad data except ‘-‘ on 4th and 8th places in phone numbers.

Now try providing the data in strict format.

insert into address values ('Gurmit','S','Randhawa','416-742-9242','647-720-4020','1230 The Walkers Road');

 

1 row created.

Cool, This works, and is much better because the chances of omission are ruled out this way.

            Triggers are not primarily for this purpose. However being an database object it works faster and ensures data integrity; these triggers can be put to different uses. Normally triggers are used to make calculations based on some columns and populate the other columns with the result. More sophisticated use can be thought of updating other tables based on transaction data entered into main table (usually called TRANSACTION table).

            As a last section of this walkthrough part I would like to mention here that entering all data on command line is usually not welcome. But the good thing is that if you do it manually you get more familiar with your database objects; i.e. tables, views, triggers and sequences etc.

            Still we do not have to go long way. If you so wish, you can use the batch file listed below. This one will allow you to enter data into your table. I will keep it simple for this tutorial.

@echo off

:another

set /p fname=First Name :

if [%fname%]==[] goto done

set /p mname=Middle Name :

set /p lname=Last Name :

set /p phone=Phone Number :

set /p cell=Cell Number :

set /p addr=Address :

set /p ok=      Ok ?

if [%ok%]==[y] goto doit

if [%ok%]==[Y] goto doit

if [%ok%]==[Yes] goto doit

if [%ok%]==[yes] goto doit

if [%ok%]==[YES] goto doit

goto redo

:doit

@echo "insert into address values ('%fname%','%mname%','%lname%','%phone%','%cell%','%addr%');" | sqlplus user1/password1

echo.

:redo

set fname=

set mname=

set lname=

set phone=

set cell=

set addr=

set ok=

goto another

:done

set fname=

set mname=

set lname=

set phone=

set cell=

set addr=

set ok=

Please take care saving this script. This will need .bat or .cmd filename extension. Go ahead and practice with data entry. Remember when you want to finish, enter nothing in First Name: If you miss it then say no to ‘Ok?’ prompt and then give it empty First Name again. This batch file will keep looping until you provide empty (NULL) for First Name. For each entry you will be expecting following string from Oracle. Oracle confirms the successful entry this way. Anything else will signal an error.

 1 row created.

If you see an error then you need to repeat the entry. Keep in mind that you have a trigger in action to check your phone numbers. That should be good enough for this part of tutorial. In next part, we will see how we can build a simple application to retrieve data from our database remotely.