11.07.2015 Views

Oracle Database 11 g - Online Public Access Catalog

Oracle Database 11 g - Online Public Access Catalog

Oracle Database 11 g - Online Public Access Catalog

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

126 CHAPTER 3 ■ DATABASE ADMINISTRATIONCreating a Table with a Virtual ColumnTo create a virtual column, you must use the clause generated always as after the virtual columnname when you create a table. Here’s an example showing how to incorporate a virtual columnin a table:SQL> create table emp (2 empno NUMBER(5) PRIMARY KEY,3 ename VARCHAR2(15) NOT NULL,4 ssn NUMBER(9),5 sal NUMBER(7,2),6* hrly_rate NUMBER(7,2) generated always as (sal/2080));Table created.SQL>Line 6 in the previous example creates the virtual column hrly_rate. If you want, you canalso use the keyword virtual after this line to make it syntactically complete, but the keywordis purely optional. The following example shows how to use the optional keyword virtual aspart of a table creation statement that also creates a check constraint on the virtual column:SQL> create table emp32 (sal number (7,2),3 hrly_rate number (7,2) generated always as (sal/2080)4 virtual5* constraint HourlyRate CHECK (hrly_rate > 8.00));Table created.SQL>The column hrly_rate is a virtual column since the column values are generated by evaluatingthe expression sal/2080 for each row in the table emp. The generated always as clausemeans the values of the virtual column are created on the fly in response to a query on thevirtual column. The values for the hrly_rate column for each employee are derived by dividingthe employee’s annual salary by the total number of hours the employee worked during thatyear. The column expression can refer to a user-created function. A virtual column can use anyscalar datatype or the XML type.You can modify a table containing a virtual column just as you would a table with onlynormal columns by using the alter table statement.Adding a Virtual Column to a TableYou can add a virtual column to an existing table just as you would a normal column. In thefollowing example, we show how to add a new virtual column named income, which is derivedby computing the product of the salary and commission_pct columns for each row:SQL> alter table employees add (income as (salary*commission_pct));Table altered.SQL>

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!