Showing posts with label Oracle Database. Show all posts
Showing posts with label Oracle Database. Show all posts

Thursday, March 14, 2013

Object Relational Database Features Implemented with Oracle

Oracle is a modern and feature-full database that supports many features of an object relational database system. Oracle supports type definition, type inheritance, collection type, member function, nested table, association and aggregation relationships. In this article, I have implemented all features other than association and aggregation relationships.

1. Database Structure
I have considered a database for a simple ecommerce site. The database will consist of different type of products having a bunch of attributes inherited from Products table whereas each table will have some other attributes of its own. So here I have a product object and a Clothes table that inherits the product object. Each clothe is available in multiple sizes. Further, each clothe tuple is available in multiple colors represented by a collection array in this example. For simplicity, I have included only one such table that inherits from products table where there could be other tables like Jewellery, Bags, Cosmetics and so on. Further, each product has multiple categories which is implemented by a nested category table. In our example, we charger 10% extra on the price of each product. Hence I have used a member function that returns 10% extra of the price.

2. Object Relational Structure
Product is an object, not the table, from which another object or type ClotheType is inherited. Product also contains a nested table Category so that each product row contains a reference to an instance of the table Category. Finally we create a table Clothes of the type ClotheType. ClotheType consists of two attributes: clothesize and clothecolor where clothesize is another Type and clothecolor is a collection array.

The object oriented concept of function has been included in ClotheType object which we call member function in Oracle.

3. DDL Script for the Database Objects

Create a type CategoryType
Create or replace type CategoryType as object(
categoryid int,
categoryname varchar2(50)
) not final

Create a table of CategoryType
Create or replace type ProductCategory as Table of CategoryType

Create an inheritable (specified by "not final" construct) object Product
Create or replace type Product as object(
productid int,
productname varchar2(100),
price number(7,2)
) not final

Create type ProductSize
Create or replace type ProductSize as object(
sizecode varchar2(20),
sizevalue varchar2(20)
)

Create collection array for colors
create or replace type ColorArray as varray(20) of varchar2(20)

Create a type ClotheType that inherits from Product
Create or replace type ClotheType under Products(
clothesize productsize,
clothecolor colorarray,
clothecategory productcategory,
member function total_price return number
)

--define the body for the member function total_price
create or replace type body ClotheType as
 member function  total_price return number is
 begin
                 return (price + price * 0.1);  
 end;
end;

Finally create a table of the type ClotheType
create or replace table Clothes of clothetype
nested table clothecategory store as prod_cat

4. Inserting rows into the Clothes table
Now we insert rows into the Clothes table.
  
   insert into clothes
   values(3,'V-neck tshirts with full sleeve',250,
   productsize('M','Medium'),
   colorarray('White','Blue','Black'),
          productcategory(categorytype('1','T-Shirts'),
                     categorytype('2','Men''s Wears')
   )
      );
   
   insert into clothes
   values(2,'Round-neck tshirts',450,
   productsize('L','Large'),colorarray('Red','Black','Green'),
          productcategory(categorytype('1','T-Shirts'),
                     categorytype('2','Men''s Wears')
      )
      );
     
   insert into clothes
   values(1,'Both side design tshirts',600,
   productsize('S','Small'),colorarray('Red','Blue','Black'),
             productcategory(categorytype('1','T-Shirts'),
                     categorytype('2','Men''s Wears')
      )
      );    
5. Querying the table Clothes
a. Normal query to select the columns productid, productname, pirce and productsize's columns sizecode and sizevalue

select c.productid,c.productname,c.price,
 c.clothesize.sizecode,c.clothesize.sizevalue
from clothes c

select from a table in object relational database Oracle


b. Querying the categories in a product from the nested table clothecategory

select c.productid,c.productname,p.categoryid,p.categoryname
 from clothes c,table(c.clothecategory) p
where c.productid=1;

select c.productid,c.productname,p.categoryid,p.categoryname
 from clothes c,table(c.clothecategory) p
where c.productid=2;

select from nested table in object relational database Oracle


c. Querying the colors associated with a product

select c.productid, c.productname,p.*
 from clothes c, table(c.clothecolor) p
where c.productid=2;

select from collection array in object relational database Oracle


d. Querying the total price by calling the member function total_price

select p.productid, p.productname,p.price,p.total_price() "Total Price"
 from clothes p;

select using member function in object relational database Oracle


6.Conclusion
we realized and implemented a bunch of object relational features of Oracle database. Some of the features we worked with were type inheritance, type as a column, datatype collection and nested table, as well as member function. We developed DDL script to create such objects and performed select queries. All in all, we got the good glimspe of object oriented programming in Oralce database.

Friday, November 28, 2008

Dealing with apostrophe (‘) problem in asp.net, sql server, oracle database query

The use of apostrophe (') character as an input text in an sql query troubles the query operation. Say, you have a textbox in which user can input her search text and she inputs "john's" as her search text. Now your employee query will look like:

SELECT *FROM [Employee] WHERE Employee].Employee_Name LIKE 'john's' AND [Your other WHERE conditions]

See the problem? You are right. The database engine treats the query segment:

SELECT * FROM [Employee] WHERE [Employee].Employee_Name LIKE john

And the remaining portion will unfortunately contribute to syntax error.It is the problem and I tried my best to elaborate it. Then solution? Yeah, there exists simple but tricky one! Just replace the apostrophe (') character in the search text with double apostrophe ('') character and you are done. Let me put it simply.

string searchText = txtSearchInput.Text;
if xtSearchInput.Text.Contains("'"))
{
searchText = txtSearchInput.Text.Replace("'", "\''");
}
Happy Programming! Happy dot-netting!!

kick it on DotNetKicks.com

Monday, September 15, 2008

Create unique id in oracle table using trigger and sequence

In one of my recent projects, I had to insert into a table where one column had to be unique and auto generated. Further I also had to maintain the data so that it was in serial with previously inserted data.

In oracle this can be accomplished by the combined use of Trigger and Sequence. I am going to describe the technique in this post.

Sequence: A sequence can generate unique number. User can limit the minimum and maximum value and also the starting value of the generated number. In other words a sequence is like a unique number generator whose nature can be controlled by a user. One sequence can be maintained per table so that we can provide unique and serial id for each table.

Trigger: A trigger can be fired before insert, update or delete operations in any table. This can be designed to help apply business logic while using data manipulations using insert, update and delete plsql programming.

Create a sequence

CREATE SEQUENCE SEQ_EMPLOYEE INCREMENT BY 1 START WITH 10000 MINVALUE 10000 MAXVALUE 99999 NOCYCLE NOCACHE NOORDER;

Create a Trigger on Employee Table

CREATE OR REPLACE TRIGGER TRIGGER_EMPLOYEE
BEFORE INSERT ON EMPLOYEE
FOR EACH ROW
begin
select SEQ_EMPLOYEE.nextval into :new.EMPLOYEE_ID from dual;
end;

Insert into Employee Table

INSERT INTO Employee (Name, Address, Post)
VALUES ('sangam','New Road-10', 'Software Developer')

Note: Since the trigger fetches unique number from sequence and inserts into Employee_id field, we need not to put this column in Insert statement as above.

Happy Oracling!!

Thursday, August 21, 2008

System.Data.OracleClient requires Oracle client software version 8.1.7 or greater

I have oracle database installed in my computer. My Operating system is XP. I wrote an application in asp.net. It connected to oracle database. I had the connection string in web.config where I used the OracleClient as the provider.




(Fig: Connection string with provider as OracleClient )

But I could not connect to the database. A connection error occured. The error speaks:
System.Data.OracleClient requires Oracle client software version 8.1.7 or greater
But the odd is that I could easily connect to the database using OLEDB provider.

(Fig: Connection string with OLEDB provider)

I pasted the error statement in the google search textbox. I got almost same solutionfrom most of the sites. I will state the solution as suggested by the sites and put my experiences along with it.

Solution
Oracle 9.2 Client software requires that you give the Authenticated User privilege to the Oracle Home by following these steps:

1. Log on to Windows as a user with Administrator privileges.

2. Launch Windows Explorer from the Start Menu and and navigate to the ORACLE_HOME folder. This is typically the "Ora92" folder under the "Oracle" folder (i.e. D:\Oracle\Ora92).

3. Right-click on the ORACLE_HOME folder and choose the "Properties" option from the drop down list. A "Properties" window should appear.

4. Click on the "Security" tab of the "Properties" window.

5. Click on "Authenticated Users" item in the "Name" list (on Windows XP the "Name" list is called "Group or user names").

6. Uncheck the "Read and Execute" box in the "Permissions" list under the "Allow" column (on Windows XP the "Permissions" list is called "Permissions for Authenticated Users").

7. Re-check the "Read and Execute" box under the "Allow" column (this is the box you just unchecked).

8. Click the "Advanced" button and in the "Permission Entries" list make sure you see the "Authenticated Users" listed there with:
Permission = Read & Execute Apply To = This folder, subfolders and files

If this is NOT the case, edit that line and make sure the "Apply onto" drop-down box is set to "This folder, subfolders and files". This should already be set properly but it is important that you verify this.

9. Click the "Ok" button until you close out all of the security properties windows. The cursor may present the hour glass for a few seconds as it applies the permissions you just changed to all subfolders and files.

10. Reboot your computer to assure that these changes have taken effect.
Re-execute the application and it should now work.

Thank you Paul for the solution.

My Experiences-I got the problem in Oracle 8i.-I use Windows xp. My ORACLE_HOME is ora81 folder. When I select the properties, Iget the following window.

(Fig. When I right click and select properties of Ora81 folder in Windows XP)

As we can see there is no security tab. I tried the Web Sharing tab but with vain. So I had to follow the following steps to view the security tab.

1. Open the C:/ folder.
2. From Tools menu and click Folder Options.
3. The Folder Options window opens. Click the View tab.
4. In the advanced setting go to the last check box- Use simple file sharing(Recommended) and uncheck it.
5. Click apply and then Ok.

(Fig: How to see security tab in properties of the folder Ora81 in Windows XP)

Now again view the properties of Ora81 folder you will see the security tab.

(Fig: Security tab displayed in folder properties in windows xp)
I could see the security tab but there was no Authenticated User group.
So I added it using the Add button. And I followed all above mentioned steps.But the problem persisted.

My Solution
I just completely uninstalled the Oracle product from my PC. Then I reinstalled it.To my surprise it worked now.

I am surprised now, is to reinstall the oracle database the only feasible solution?May someone listen and reply me.

Meantime, you may be interested in object relational features of Oracle implemented using a simple yet practical ecommerce database.

Happy dot-netting! Happy Oracling!!

Sunday, August 17, 2008

ORA-02270: no matching unique or primary key for this column-list

I generated this error this morning. I was a little bit upset when the error occured. Mostly the error source of this error has been described in the Internet as follows:

Cause: A REFERENCES clause in a CREATE/ALTER TABLE statement gives a column-list for which there is no matching unique or primary key constraint in the referenced table.

Action: Find the correct column names using the ALL_CONS_COLUMNS catalog view

In my case, this error occured when I tried to add a foreign key constraint to a table.Later I found that there did not exist primary key in the referenced table or the column being referenced was not a primary key.

I think the better way to describe this would be to list out all possible reasons like the one I wrote above. Any way, I had to make the referenced column a primary key and it was done the next time!

At the end, you may also be interested in implementing object relational database features like inheritance, member function, collection array, nested table etc. in Oracle illustrated using a simple yet useful ecommerce scenario.

Happy Oracling! Happy programming!!

Thursday, August 14, 2008

ORA-00955: name is already used by an existing object

When I tried to create a new table in database I got the error:

ORA-00955: name is already used by an existing object

In fact, I had just deleted a table from TOAD.

( I use TOAD- perhaps most users use TOAD (Tool for Application Developer), I actually don't know how much users useTOAD! I think it is a very good tool if one uses Oracle as the backend. For only those who are beginning to use Oracle as the backend, here is where you can find what the TOAD is. You can download it and use it easily.I bet you will not require any training. Just look at it and find how easy it is! Not more than 28 MB. It is exactly 27.4 MB in the BackUP folder of my D- Drive! Ok, I will blog about it sometime later. A marvellous product-TOADSoft.com - Home of the World's #1 Tool for Database Professionals! (as they claim!!)

Click here: http://www.toadsoft.com.
You will be welcomed with the following messages:

Toad®, Market-leading tool that provides quick and easy database development and administration.Welcome to ToadSoft!

Toad is a powerful, low-overhead tool that makes database and application development faster and easier and simplifies day-to-day administration tasks.

Whether you are a database developer, application developer, DBA or business analyst, Toad offers specific features to make you more productive than ever before.
).
I thought I dropped the table Equipments and tried to run the script to create a table with exactly the same again. So I found out that ORA-00955 is not a severe error. I just dropped the table Equipements and regenerated it using the scriptI had already generated. It worked!

Cause: The "error ORA-00955: name is already used by an existing object" occurs if there isalready a database object (table, synonym, view, index, or cluster) and we try to create an object with the same name.

Note: I described that I was creating a table by running a script against the database from thetool TOAD. In fact, one can do it using the graphical interface of TOAD also. TOAD is in fact an IDE for Oracle database management and programming. I also love graphical tools!!

Before completing this post, I would like to invite you to read on implementation of object relational database features like inheritance, collection array, nested table etc. in Oracle which has been well illustrated using a simple ecommerce database scenario.

Happy Oracling! Happy Programming!!

Monday, August 11, 2008

Create New User In Oracle

In my previous post, I mentioned how to change the password of the default user that is created during the installation of the Oracle database. Now here I will put the simple but mention-worthy PL/SQL programming to create a new user in Oracle.

Steps of Creating New User in Oracle

1. Create a new user providing user name and password.

Connect to the Oracle SQLPLUSW. Run the following code:

CREATE USERNAME IDENTIFIED BY PASSWORD;

Example:

CREATE USER sams
IDENTIFIED BY myoracle;

While creating the user, you can define the default tablespace and default temporary space also. The combined syntax will then be like below:


CREATE USER sams
IDENTIFIED BY myoracle
DEFAULT TABLESACE system
TEMPORARY TABLESPACE temp;


2. Grant the user with essential privileges. One should consider well before granting access to the newly created user. The privileges can be assigned in many layers. For example you can assign the user with the DBA administrative privilege. On the other hand you can also limit the general user with the SELECT, INSERT, UPDATE or DELETE privileges to certain table(s).

The syntax follows:

GRANT CONNECT, RESOURCE to sams

GRANT DBA to sams

GRANT (SELECT INSERT UPDATE DELETE) ON TableName to UserName;

Example:
GRANT SELECT ON Employees to sams;

Happy Oracling!

Monday, August 4, 2008

How to Change Password of Default User in Oracle Database ?

When you install Oracle database, two default users are already created. You can log in using those user ID. here are the usersand their password.

UserName: SYSTEM
Password: MANAGER

UserName: SYS
Password: [change_on_install]

New user also can be added in many ways. (I will blog about this later)

Tips: Typically, these users hold standard data dictionary information for the database. So experts suggest to change the passwords of thesedefault users as soon as possible. Then How? Follow me.

1. Open SQLPLUSW.

2. Connect to the database using system/manager.

SQL> alter user system identified by ;
User altered.

SQL> alter user sys identified by ;
User altered.


This way you are safe. You can also add new user to the database. I have made up mind to talk about creating new user in Oracle database in my next post.

You may also like to read on implementation of object relational database features like inheritance, collection array, nested table etc. in Oracle .

Happy Oracling!!

Friday, August 1, 2008

5 Most Asked Oracle Interview Questions: Part 1

Here are five most asked interview questions related to Oracle PL/SQL Programming. Please feel free to share your answers/ comments/ suggestions with other readers. I will be live on scene to followup along with you!

Question#1 How do you remove duplicate row(s) from Oracle data table ?

Question#2 What is the difference between WHERE clause and HAVING clause? How do you use HAVING clause with the aggregate functions?

Question#3 When should you use the GROUP BY clause? Write PL/SQL code to select EmployeeID, Name, Address and Total Number of Employees of an organization.


Question4# What is self-join? Write code to display the Name of Employee, and Name of his/her Manager from the table below.

Question#5 Write PL/SQL code to display total number of employees who get salary less than the average salary of all employees of an organization.


Table: Employee


Hope we all benifit from the question and answering.

While ending this set of questions, I would like to invite you understand the implementation of object relational features of oracle like nested table, inheritance, collection array, member function etc.

Happy PL/SQL-ing along with Oracling!!

Tuesday, July 29, 2008

Oracle Error ORA-01722: Invalid Number

ORA-01722: Invalid Number mostly occurs in runtime. There are some errors in programming that may generate ORA-01722: Invalid Number error. Let me present this formally.

Cause:
The attempted conversion of a character string to a number failed because the character string was not a valid numeric literal. Only numeric fields or character fields containing numeric data may be used in arithmetic functions or expressions. Only numeric fields may be added to or subtracted from dates.

Action:
Check the character strings in the function or expression. Check that they contain only numbers, a sign, a decimal point, and the character "E" or "e" and retry the operation

Experience:
I got the error in runtime when I assigned numeric value to a varchar2 parameter passed to a package. There may other so many possible reasons as discussed above. 

At the end, you may also like to read on implementing object relational database features in oracle like nested table, inheritance, collection array, member function etc.

Happy Programming!

Friday, July 25, 2008

Oracle Error ORA-12704: character set mismatch

One gets much worried by ORA-12704:character set mismatch. It is hard to track what is going on. But the guideline below will give relief.

Causes of Oracle Error ORA-12704: character set mismatch

-The string operands(other than an nlsparams argument) to an operator or built-in function do not have the same character set.

- An nlsparams operand is not in the database character set.

- String data with character set other than the database character set is passed to a built-in function not expecting it.

- The second argument to CHR() or CSCONVERT() is not CHAR_CS or NCHAR_CS.

- A string expression in the VALUES clause of an INSERT statement, or the SET clause of an UPDATE statement, does not have the same character set as the column into which the value would be inserted.

- A value provided in a DEFAULT clause when creating a table does not have the same character set as declared for the column.

- An argument to a PL/SQL function does not conform to the character set requirements of the corresponding parameter.

Action to be taken


Check one of the suspected region in your coding in PL/SQL and find the error occuring part. Then you can fix it and get rid of it! Happy error detection!!

Finally I would like to welcome you to get insight on implementing object relational features in oracle illustrated with a simple ecommerce scenario.

Happy Programming!

Wednesday, July 23, 2008

Oracle Error: PLS-00323

I encountered Oracle Error: PLS-00323 this morning. It took me time to resolve and fix it. In much cases, PLS-00323 get around you and you have to wander from here to there in Internet. Before going to Internet, you might have been tired of doing all your brains! This is all because of the oracle package that consists of a package specification and its corresponding body definition. Say, you have a package with three variables defined in your sub program and only two defined in your package body. Exactly here you get the error PLS-00323.

PLS-00323: subprogram or cursor 'BANK_GETBYPRIMARYKEY' is declared in a package specification and must be defined in the package body.

Here 'BANK_GETBYPRIMARYKEY' is my sub program.

Fixes: To be sure you can just check the matches in package specification and package body. Happy database programming.

Tuesday, July 22, 2008

How to encrypt decrypt password in Oracle data table?

Programmers sometimes need to store user password and some other fields in database data table in encrypted format. There exists an easy way to do this. I have used in my database. In my system, I have a table called Users which contains fields: UserID, UserName, Password,and Email. I have encrypted the password field.

[While continuing the journey, you may also be interested in implementing object relational database features of Oracle illustrated for a simple ecommerce database.]

With this scenario, I get following issues to be solved.Encrypt input password before inserting into data table.Decrypt password before reading it.

For all these requirements I use two functions, one for encrypting password and another for decrypting password.

--create two function: one for encrypt--the other for decrypt:

FUNCTION encrypt( iValue in varchar2, iKey in varchar2 )
return varchar2
is
vEncrypted varchar2(4000);
begin
-- encrypt input string
dbms_obfuscation_toolkit.desencrypt (input_string => iValue,
key_string => iKey,
encrypted_string => vEncrypted);
return vEncrypted;
end;/

FUNCTION decrypt( iValue in varchar2, iKey in varchar2 )

return varchar2
is
vDecrypted varchar2(4000);
begin
-- decrypt input string
dbms_obfuscation_toolkit.desdecrypt (input_string => iValue,
key_string => iKey,
decrypted_string => vDecrypted);
return vDecrypted;
end/

Popular Posts

Recent Articles