Вы находитесь на странице: 1из 26

Pragma is the keyword that is used to tell the compiler what to do.

Types of Pragma: EXCEPTION_INIT: In PL/SQL, the pragma EXCEPTION_INIT tells the compiler to associate an exception name with an Oracle error number. That lets you refer to any internal exception by name and to write a specific handler for it. When you see an error stack, or sequence of error messages, the one on top is the one that you can trap and handle. SERIALLY_REUSABLE: SERIALLY_REUSABLE packages let you design applications that manage memory better for scalability. If a package is not SERIALLY_REUSABLE, its package state is stored in the user global area (UGA) for each user. Therefore, the amount of UGA memory needed increases linearly with the number of users, limiting scalability. The package state can persist for the life of a session, locking UGA memory until the session ends. In some applications, such as Oracle Office, a typical session lasts several days. If a package is SERIALLY_REUSABLE, its package state is stored in a work area in a small pool in the system global area (SGA). The package state persists only for the life of a server call. After the server call, the work area returns to the pool. If a subsequent server call references the package, then Oracle Database reuses an instantiation from the pool. Reusing an instantiation re-initializes it; therefore, changes made to the package state in previous server calls are invisible. (For information about initialization, see "Package Instantiation and Initialization".)

AUTONOMOUS_TRANSACTION: It is independence transaction RESTRICTED_REFERENCES: The RESTRICT_REFERENCES pragma asserts that a user-defined subprogram does not read or write database tables or package variables. ===================================================================== What is explain plan: When you fire an SQL query to Oracle, Oracle database internally creates a query execution plan in order to fetch the desired data from the physical tables. The query execution plan is nothing but a set of methods on how the database will access the

data from the tables. This query execution plan is crucial as different execution plans will need different cost and time for the query execution. How the Execution Plan is created actually depends on what type of query optimizer is being used in your Oracle database. There are two different optimizer options Rule based (RBO) and Cost based (CBO) Optimizer. For Oracle 10g, CBO is the default optimizer. Cost Based optimizer enforces Oracle to generate the optimization plan by taking all the related table statistics into consideration. On the other hand, RBO uses a fixed set of pre-defined rules to generate the query plan. Obviously such fixed set of rules may not always be able to create the plan that is most efficient in nature. This is because an efficient plan will depend heavily on the nature and volume of tables data. Because of this reason, CBO is preferred over RBO. Understanding Oracle Query Execution Plan But this article is not for comparing RBO and CBO (In fact, there is not much point in comparing these two). This article will briefly help you understand, 1. How can we see Query Execution Plan 2. How do we understand (or rather interpret) the execution plan. So lets begin. I will be using Oracle 10g server and SQL *Plus client to demonstrate all the details. Oracle Full Table Scan (FTS) Lets start by creating a simple product table with the following structure, ID number(10) NAME varchar2(100) DESCRIPTION varchar2(255) SERVICE varchar2(30) PART_NUM varchar2(50) LOAD_DATE date Next I will insert 15,000 records into this newly created table (data taken from one of my existing product table from one of my clients production environment). Remember, currently there is no index on the table. So we start our journey by writing a simple select statement on this table as below,

SQL> explain plan for select * from product; Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT ---------------------------------------------------------Plan hash value: 3917577207 ------------------------------------| Id | Operation | Name | ------------------------------------| 0 | SELECT STATEMENT | | | 1 | TABLE ACCESS FULL | PRODUCT| ------------------------------------Note ----- rule based optimizer used (consider using cbo)

Notice that optimizer has decided to use RBO instead of CBO as Oracle does not have any statistics for this table. Lets now build some statistics for this table by issuing the following command, SQL> Analyze table product compute statistics; Now lets do the same experiment once again, SQL> explain plan for select * from product; Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT ----------------------------------------------------Plan hash value: 3917577207 ----------------------------------------------------| Id | Operation | Name | Rows | Bytes | ----------------------------------------------------| 0 | SELECT STATEMENT | | 15856 | 1254K| | 1 | TABLE ACCESS FULL | PRODUCT | 15856 | 1254K| -----------------------------------------------------

You can easily see that this time optimizer has used Cost Based Optimizer (CBO) and has also detailed some additional information (e.g. Rows etc.) The point to note here is, Oracle is reading the whole table (denoted by TABLE ACCESS FULL) which is very obvious because the select * statement that is being fired is trying to read everything. So, theres nothing interesting up to this point. Index Unique Scan Now lets add a WHERE clause in the query and also create some additional indexes on the table. SQL> create unique index idx_prod_id on product (id) compute statistics; Index created. SQL> explain plan for select id from product where id = 100; Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT --------------------------------------------------------Plan hash value: 2424962071 --------------------------------------------------------| Id | Operation | Name | Rows | Bytes | --------------------------------------------------------| 0 | SELECT STATEMENT | | 1| 4| |* 1 | INDEX UNIQUE SCAN | IDX_PROD_ID | 1| ---------------------------------------------------------

4|

So the above statement indicates that CBO is performing Index Unique Scan. This means, in order to fetch the id value as requested, Oracle is actually reading the index only and not the whole table. Of course this will be faster than FULL TABLE ACCESS operation shown earlier. Table Access by Index RowID Searching the index is a fast and an efficient operation for Oracle and when Oracle finds the desired value it is looking for (in this case id=100), it can also find out the

rowid of the record in product table that has id=100. Oracle can then use this rowid to fetch further information if requested in query. See below, SQL> explain plan for select * from product where id = 100; Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT ---------------------------------------------------------Plan hash value: 3995597785 ---------------------------------------------------------| Id | Operation | Name |Rows | Bytes| ---------------------------------------------------------| 0 | SELECT STATEMENT | | 1 | 81 | | 1 | TABLE ACCESS BY INDEX ROWID| PRODUCT| 1 | 81 | |* 2 | INDEX UNIQUE SCAN | IDX_PROD_ID | 1 | | ----------------------------------------------------------

TABLE ACCESS BY INDEX ROWID is the interesting part to check here. Since now we have specified select * for id=100, so Oracle first use the index to obtain the rowid of the record. And then it selects all the columns by the rowid. Index Range Scan But what if we specify a >, or between criteria in the WERE clause instead of equality condition? Like below, SQL> explain plan for select id from product where id <10 Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT --------------------------------------------Plan hash value: 1288034875 ------------------------------------------------------| Id | Operation | Name | Rows | Bytes | ------------------------------------------------------| 0 | SELECT STATEMENT | | 7 | 28 |

|* 1 | INDEX RANGE SCAN| IDX_PROD_ID | -------------------------------------------------------

7|

28 |

So this time CBO goes for an Index Range Scan instead of INDEX UNIQUE SCAN. The same thing will normally happen if we use a between clause also. Index Fast Full Scan Now, lets see another interesting aspect of INDEX scan here by just altering the 10. Before we see the outcome, just remind yourself that there are 15000 over products with their ids starting from 1 to 15000+. So if we write 10 we are likely to get almost 14990+ records in return. So does Oracle go for an INDEX RANGE SCAN in this case? Lets see, SQL> explain plan for select id from product where id>10; Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT -----------------------------------------------Plan hash value: 2179322443 -------------------------------------------------------| Id | Operation | Name | Rows |Bytes | -------------------------------------------------------| 0 | SELECT STATEMENT | | 15849|63396 | |* 1 | INDEX FAST FULL SCAN| IDX_PROD_ID| 15849|63396 | ---------------------------------------------------------

So, Oracle is actually using a INDEX FAST FULL SCAN to quickly scan through the index and return the records from table. This scan is "quick" because unlike index full scan or index unique scan, INDEX FAST FULL SCAN utilizes multiple-block inputoutput (I/O) whereas the formers utilizes single block I/O. Note on QUERY PLAN FTS or Full Table Scan

Whole table is read upto high water mark

Uses multiblock input/output Buffer from FTS operation is stored in LRU end of buffer cache

Index Unique Scan

Single block input/output

Index Fast Full Scan


Multi block i/o possible Returned rows may not be in sorted order

Index Full Scan


Single block i/o Returned rows generally will be in sorted order

This time we will explore and try to understand query plan for joins. Lets take on joining of two tables and lets find out how Oracle query plan changes. We will start with two tables as following, Product Table - Stores 15000 products. Each product has unique numeric id. Buyer Table - Stores 15,000,00 buyers who buy the above products. This table has unique id field as well as a prodid (product id) field that links back to the product table. Before we start, please note, we do not have any index or table statistics present for these tables. SORT MERGE JOIN SQL> explain plan for SELECT * 2 FROM PRODUCT, BUYER 3 WHERE PRODUCT.ID = BUYER.PRODID;

Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT ----------------------------------------------------------------------------------| Id | Operation | Name | --------------------------------------| 0 | SELECT STATEMENT | | | 1 | MERGE JOIN | | | 2 | SORT JOIN | | | 3 | TABLE ACCESS FULL| BUYER | |* 4 | SORT JOIN | | | 5 | TABLE ACCESS FULL| PRODUCT | ---------------------------------------

Above plan tells us that CBO is opting for a Sort Merge join. In this type of joins, both tables are read individually and then sorted based on the join predicate and after that sorted results are merged together (joined). Read Product ---> Sort by product id ------| |---> join Read Buyer ---> Sort by product id ------| Joins are always a serial operation even though individual table access can be parallel. Now lets create some statistics for these tables and lets check if CBO does something else than SORT MERGE join. HASH JOIN SQL> analyze table product compute statistics; Table analyzed. SQL> analyze table buyer compute statistics; Table analyzed. SQL> explain plan for SELECT * 2 FROM PRODUCT, BUYER 3 WHERE PRODUCT.ID = BUYER.PRODID;

Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT -----------------------------------------------------Plan hash value: 2830850455 -----------------------------------------------------| Id | Operation | Name | Rows | Bytes | -----------------------------------------------------| 0 | SELECT STATEMENT | | 25369 | 2279K| |* 1 | HASH JOIN | | 25369 | 2279K| | 2 | TABLE ACCESS FULL| PRODUCT | 15856 | 1254K| | 3 | TABLE ACCESS FULL| BUYER | 159K| 1718K| ------------------------------------------------------

CBO chooses to use Hash join instead of SMJ once the tables are analyzed and CBO has enough statistics. Hash join is a comparatively new join algorithm which is theoretically more efficient than other types of joins. In hash join, Oracle chooses the smaller table to create an intermediate hash table and a bitmap. Then the second row source is hashed and checked against the intermediate hash table for matching joins. The bitmap is used to quickly check if the rows are present in hash table. The bitmap is especially handy if the hash table is too huge. Remember only cost based optimizer uses hash join. Also notice the FTS operation in the above example. This may be avoided if we create some index on both the tables. Watch this, SQL> create index idx_prod_id on product (id); Index created. SQL> create index idx_buyer_prodid on buyer (prodid); Index created. SQL> explain plan for select product.id 2 FROM PRODUCT, BUYER 3 WHERE PRODUCT.ID = BUYER.PRODID; Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT ------------------------------------------------------------------

-----------------------------------------------------------------| Id | Operation | Name | Rows | Bytes | -----------------------------------------------------------------| 0 | SELECT STATEMENT | | 25369 | 198K| |* 1 | HASH JOIN | | 25369 | 198K| | 2 | INDEX FAST FULL SCAN| IDX_PROD_ID | 15856 | 63424 | | 3 | INDEX FAST FULL SCAN| IDX_BUYER_PRODID | 159K| 624K| -----------------------------------------------------------------NESTED LOOP JOIN There is yet another kind of joins called Nested Loop Join. In this kind of joins, each record from one source is probed against all the records of the other source. The performance of nested loop join depends heavily on the number of records returned from the first source. If the first source returns more record, that means there will be more probing on the second table. If the first source returns less record, that means, there will be less probing on the second table. To show a ne sted loop, lets introduce one more table. We will just copy the product table into a new table, product_new. All these tables will have index. Now I write a simple query below, select * from buyer, product, product_new where buyer.prodid=product.id and buyer.prodid = product_new.id; And then I checked the plan. But the plan shows a HASH JOIN condition and not a NESTED LOOP. This is, in fact, expected because as discussed earlier hash-join is more efficient compared to other joins. But remember hash join is only used for cost based optimizer. So if I force Oracle to use rule based optimizer, I might be able to see nested joins. I can do that by using a query hint. Watch this, SQL> explain plan for 2 select /*+ RULE */ * 3 from buyer, product, product_new 4 where buyer.prodid=product.id 5 and buyer.prodid = product_new.id; Explained. SQL> select * from table(dbms_xplan.display);

PLAN_TABLE_OUTPUT ----------------------------------------------------------Plan hash value: 3711554028 ----------------------------------------------------------| Id | Operation | Name | ----------------------------------------------------------| 0 | SELECT STATEMENT | | | 1 | TABLE ACCESS BY INDEX ROWID | PRODUCT | | 2 | NESTED LOOPS | | | 3 | NESTED LOOPS | | | 4| TABLE ACCESS FULL | PRODUCT_NEW | | 5| TABLE ACCESS BY INDEX ROWID| BUYER | |* 6 | INDEX RANGE SCAN | IDX_BUYER_PRODID | |* 7 | INDEX RANGE SCAN | IDX_PROD_ID | ----------------------------------------------------------Voila! I got nested loops! As you see, this time I have forced Oracle to use rule based optimizer by providing /*+ RULE */ hint. So Oracle has now no option but to use nested loops. As apparent from the plan, Oracle performs a full scan of product_new and index scans for other tables. First it joins buyer with product_new by feeding each row of buyer to product_new and then it sends the result set to probe against product. Example: explain plan for select * from emp2; Select * from table (DBMS_XPLAN.display); SQL> set autotrace on explain ====================================================================== == Join 3 tables (table1, table2 & table3) in a single query. Inner join should be applied for table1 & table 2 and left outer join for table1 & table3 where table2.dept is ABC SELECT * FROM table1 t1 INNER JOIN table2 t2 on t1.key = t2.key LEFT OUTER join table3 t3 on t1.key = t3.key Where t2.dept ='ABC' SELECT * FROM (table t1 INNER JOIN table2 t2 ON t1.col = t2.col AND t2.dept = 'ABC') LEFT JOIN table t3 ON t1.col = t3.col OR

SELECT * FROM (table t1 INNER JOIN (SELECT * FROM table2 WHERE dept = 'ABC') t2 ON t1.col = t2.col) LEFT JOIN table t3 ON t1.col = t3.col ====================================================================== == Views are classified in to two types. 1. Simple View 2. Complex View DML Operations are not possible in complex views, because, If u create a view more than one table or If u create a view using group function or aggregate function If u create a view using distinct keyword etc., Those are called complex view. ====================================================================== == How to get fist and last record from a table in oracle? SELECT * FROM customer WHERE ROWNUM = 1 UNION SELECT * FROM customer WHERE ROWID = (SELECT MAX (ROWID) FROM Customer); SELECT * FROM table_name WHERE ROWID = (SELECT MIN (ROWID) FROM tanle_name) UNION SELECT * FROM table_name WHERE ROWID = (SELECT MAX (ROWID) FROM table_name);

How to get every fourth regard from table SELECT * FROM ANISH0609_BFORE a WHERE 4 = (SELECT COUNT (ROWID)

FROM ANISH0609_BFORE b WHERE a.ROWID >= b.ROWID); SELECT * FROM employee WHERE (ROWID, 0) IN (SELECT ROWID, MOD (ROWNUM, 4) FROM employee); SELECT * FROM (SELECT ROWNUM rn, acct_id, dbase_id FROM asg_t) temp WHERE MOD (temp.rn, 4) = 0; ====================================================================== == how to achieve this problem?i am having table with two colums like empno,gender.in gender column, i am having records male,female like that .my final output will be select sum(decode(gender, 'male', 1)) as Male, sum(decode(gender, 'female', 1)) as Female from emp1; ====================================================================== == What are the different types of joins and explain them briefly. equi join , non-equi join, self join, outer join, cross join ====================================================================== ==

What is difference between decode and case function? 1) Performance wise Case is good. 2) Case is easy to understand and debug.

3) Case is ANSI stranded and Decode is property of oracle. 4) We can use Decode only in SQL but we can use Case any Where like Function/procedure. 5) Decode can be use only for continuous data not for range Value. But case can be use for range value and it allowed Operator like ">" "between" also. ====================================================================== == Write a query to find second highest salary of an employee. SELECT MAX (SALARY) FROM EMP WHERE ROWNUM < 2; SELECT * FROM (SELECT ENAME, SAL, RANK () OVER (ORDER BY SAL DESC) RANK FROM EMP) E1 WHERE E1.RANK = 2;

SELECT * FROM (SELECT salary, DENSE_RANK () OVER (ORDER BY salary) RANK FROM TABLE_NAME) WHERE RANK = 2; SELECT DISTINCT (A.SAL) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (B.SAL)) FROM EMP B WHERE A.SAL <= B.SAL);

Define candidate key, alternate key, composite key. A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key. Explain different isolation levels

An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level.

What are SQLCODE and SQLERRM and why are they important for PL/SQL developers? Expected answer: SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception. Pseudo columns are 1 2 3 4 5 nextval currval rowid rownum sysdate USER, UID, NULL, AND LEVEL.

How to replace the employee table which having the genter M to F and F to M update employee set genter = case genter when 'M' then 'F' when 'F' then 'M' else genter end; how to replace the value which are having xxxx@bt.com to xxxx@btlocalbusniess.com update employee set email_id = replace( xxxx@bt.com, xxxx@btlocalbusniess.com) where condition.

How to easys way to find out the table having four column value like business_phone,home_phone,cel_no. Employess table; empname anish kumar Raja Ramo business_phone 456666 NUll NUll 15456 home_phone 45662 NUll 789 4578 cel_phone NUll 4578 123 458 Office_phone NUll 457 789 4567

select COALESCE(business_phone, home_phone, cel_phone),empname from Employess

sub queries Cursor Type Description Implicit: Implicit cursors are declared by PL/SQL implicitly for all DML and PL/SQL SELECT statements, including queries that return only one row. Explicit: For queries that return more than one row, explicit Cursors are declared and named by the programmer And manipulated through specific statements in the Blocks executable actions. Declare Cursor cursor name is Select statement; Begin Open cursorename; FETCH cursor_name INTO [variable1, variable2, ...]

| record_name]; CLOSE cursor_name; Explicit Cursor Attributes


1. 2. 3. 4.

%ISOPEN %NOTFOUND %FOUND %ROWCOUNT

Example: DECLARE v_empno employees.employee_id%TYPE; v_ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO v_empno, v_ename; EXIT WHEN emp_cursor%ROWCOUNT > 10 OR emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE (TO_CHAR (v_empno) || ' ' || v_ename); END LOOP; CLOSE emp_cursor; END;

Handling Exceptions: An exception is an identifier in PL/SQL that is raised during the execution of a block that terminates its main body of actions Two Methods for Raising an Exception An Oracle error occurs and the associated exception is raised automatically. For example, if the error ORA-01403 occurs when no rows are retrieved from the database in a SELECT statement, then PL/SQL raises the exception NO_DATA_FOUND.

You raise an exception explicitly by issuing the RAISE statement within the block. The exception being raised may be either user-defined or predefined. Trapping an Exception If the exception is raised in the executable section of the block, processing branches to the corresponding exception handler in the exception section of the block. If PL/SQL successfully handles the exception, then the exception does not propagate to the enclosing block or environment. The PL/SQL block terminates successfully. EXCEPTION WHEN exception1 [OR exception2 . . .] THEN statement1; statement2; ... [WHEN exception3 [OR exception4 . . .] THEN statement1; statement2; . . .] [WHEN OTHERS THEN statement1; statement2; . . .] Sample predefined exceptions: NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR ZERO_DIVIDE - STORAGE_ERROR DUP_VAL_ON_INDEX Trapping Predefined Oracle Server Errors Trap a predefined Oracle Server error by referencing its standard name within the corresponding exception-handling routine. For a complete list of predefined exceptions, see PL/SQL Users Guide and Reference, Error Handling. Note: PL/SQL declares predefined exceptions in the STANDARD package. It is a good idea to always handle the NO_DATA_FOUND and TOO_MANY_ROWS exceptions, which are the most common. Instructor Note The NO_DATA_FOUND exception is not propagated when used inside a function.

Propagating an Exception If the exception is raised in the executable section of the block and there is no corresponding exception Handler, the PL/SQL block terminates with failure and the exception is propagated to the calling environment.

What Is a Procedure? CREATE [OR REPLACE] PROCEDURE procedure name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] IS|AS BEGIN EXECPTIOIN END; Deference between function and procedure: A function must return a value to the calling environment, whereas a procedure returns zero or more values to its calling environment. Like a procedure, a function has a header, a declarative part, an executable part, and an optional exceptionhandling part. A function must have a RETURN clause in the header and at least one RETURN statement in the executable section. FUNCTION CREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] RETURN datatype IS|AS PL/SQL Block; PROCEDURES Execute as a PL/SQL Statement Do not contain RETURN clause in the header Can return none, one, or many values FUNCTIONS Invoke as part of an expression Must contain a RETURN clause in the header Must return a single value Must contain at least one

Can contain a RETURN statement

RETURN statement

A procedure containing one OUT parameter can be rewritten as a function containing a RETURN Statement.

What you mean by Autonomous Transactions Oracle Autonomous Transactions are 'sub transactions' that can take place independently of any transaction that calls it. Pragma autonomous transaction; An autonomous transaction (AT) is an independent transaction started by another Transaction, the main transaction (MT). It lets you suspend the main transaction, do SQL operations, commit or roll back those operations, then resume the main Transaction.

Explicitly cursor:

DECLARE emp_name employee1.first_name%TYPE; emp_last employee1.last_name%TYPE; emp_email employee1.email%TYPE; emp_id employee1.employee_id%TYPE; emp_date employee1.hire_date%TYPE; emp_job employee1.JOB_ID%type; v_count NUMBER (15); CURSOR ac IS SELECT first_name, last_name,email,employee_id,hire_Date,job_id

FROM employees; BEGIN OPEN ac; loop FETCH ac INTO emp_name, emp_last,emp_email,emp_id,emp_date,emp_job; INSERT INTO employee1 (first_name, last_name,email,employee_id,hire_date,job_id ) VALUES (emp_name, emp_last,emp_email,emp_id,emp_date,emp_job ); v_count := ac%ROWCOUNT; DBMS_OUTPUT.put_line (v_count); EXIT WHEN ac%NOTFOUND;--must be provide for avoid infinity loop END LOOP; CLOSE ac; END;

DECLARE emp_reco employee1%ROWTYPE; CURSOR c IS SELECT * FROM employee1; BEGIN OPEN c;

--LOOP FETCH c INTO emp_reco; --EXIT WHEN c%ROWCOUNT > 10 OR c%NOTFOUND; DBMS_OUTPUT.put_line (emp_reco.first_name || ',' ||emp_reco.last_name); -- END LOOP; CLOSE c; END;

Output: Steven,Kingfirst record

For loop cursor: ---------------

/* Formatted on 2011/08/31 08:58 (Formatter Plus v4.8.8) */ DECLARE CURSOR c IS SELECT * FROM employee1; BEGIN for emp_reco in c loop --EXIT WHEN c%ROWCOUNT > 10 OR c%NOTFOUND; DBMS_OUTPUT.put_line (emp_reco.first_name || ',' ||emp_reco.last_name); END LOOP; END; Looping format. MATERIALIZED VIEW: Use the CREATE MATERIALIZED VIEW LOG statement to create a materialized view log, which is a table associated with the master table of a materialized view. When DML changes are made to master table data, Oracle Database stores rows describing those changes in the materialized view log and then uses the materialized view log to refresh materialized views based on the master table. This process is called incremental or fast refresh. Without a materialized view log, Oracle Database must reexecute the materialized view query to refresh the materialized view. This process is called a complete refresh. Usually, a fast refresh takes less time than a complete refresh. CREATE MATERIALIZED VIEW LOG ON customers PCTFREE 5 TABLESPACE example STORAGE (INITIAL 10K NEXT 10K);

Normal indexes. (By default, Oracle Database creates B-tree indexes.) 1. Bitmap indexes, which store rowids associated with a key value as a bitmap 2. Partitioned indexes, which consist of partitions containing an entry for each value that appears in the indexed column(s) of the table 3. Function-based indexes, which are based on expressions. They enable you to construct queries that evaluate the value returned by an expression, which in turn may include built-in or user-defined functions. 4 Domain indexes, which are instances of an application-specific index of type indextype

FUNTION: CREATE OR REPLACE FUNCTION dml_statement (p_emp_id VARCHAR2) RETURN VARCHAR2 IS v_first_name VARCHAR2 (10); v_last_name VARCHAR2 (10); v_employee_id VARCHAR2 (10); BEGIN SELECT employee_id, first_name, last_name INTO v_employee_id, v_first_name, v_last_name FROM employees WHERE employee_id = p_emp_id; --dbms_output.put_line(v_first_name || v_last_name); RETURN v_last_name || ' ' || v_first_name; END; --------------/* Formatted on 2011/09/19 08:00 (Formatter Plus v4.8.8) */ SELECT dml_statement (100) FROM DUAL; --------------out put: King Steven

SELECT LEVEL FROM DUAL

CONNECT BY LEVEL <= 10

File generating using utl_file: declare f_dir varchar2(50) :='/adder/adder/data/report/reward_reco_letters'; f_name varchar2(5000) :='anish.txt'; sql_query varchar2(10000); f_handle UTL_FILE.FILE_TYPE; cursor anis is select * from ASG_TESL where contract_number is not null order by contract_number desc; begin f_handle :=UTL_FILE.FOPEN(f_dir,f_name,'w'); UTL_FILE.PUTF (f_handle,'CUSTOMER INFORMATION REPORT: GENERATED ON %s\n', SYSDATE); FOR v_emp_rec IN anis LOOP utl_file.putf(f_handle,v_emp_rec.customer_code || '|' || v_emp_rec.contract_id||'|' ||v_emp_rec.contract_number); UTL_FILE.PUT_LINE(f_handle,' ');

end loop; UTL_FILE.PUT_LINE (f_handle, '*** END OF REPORT ***'); UTL_FILE.FCLOSE (f_handle); sql_query := fn_sendmail( p_from_name => 'anishkumar.swaminathan@bt.com' , p_to_name => 'anishkumar.swaminathan@bt.com' , p_subject => 'A' , p_message => 'test', p_filename1 => '/adder/adder/data/report/reward_reco_letters/anish.txt', p_filename2 => '/adder/adder/data/report/reward_reco_letters/anish.txt'); EXECUTE IMMEDIATE sql_query; EXCEPTION WHEN UTL_FILE.INVALID_FILEHANDLE THEN

RAISE_APPLICATION_ERROR (-20001, 'Invalid File.'); WHEN UTL_FILE.WRITE_ERROR THEN RAISE_APPLICATION_ERROR (-20002, 'Unable to write to file'); end;

How to use the hints: /*+ INDEX (employees emp_department_ix)*/ The INDEX_FFS hint instructs the optimizer to perform a fast full index scan rather than a full table scan. SELECT /*+ INDEX_FFS(e emp_name_ix) */ first_name FROM employees e; The INDEX_JOIN hint instructs the optimizer to use an index join as an access path. For the hint to have a positive effect, a sufficiently small number of indexes must exist that contain all the columns required to resolve the query. SELECT /*+ INDEX_JOIN(e emp_manager_ix emp_department_ix) */ department_id FROM employees e WHERE manager_id < 110 AND department_id < 50; how to find out the locked session by the user: v$locked_object maga lakshmi

B-tree indexes: the default and the most common B-tree cluster indexes: defined specifically for cluster Hash cluster indexes: defined specifically for a hash cluster Global and local indexes: relate to partitioned tables and indexes Reverse key indexes: most useful for Oracle Real Application Clusters applications Bitmap indexes: compact; work best for columns with a small set of values Function-based indexes: contain the precomputed value of a function/expression Domain indexes: specific to an application or cartridge.

Overloading: Overloading means that you create more than one function or procedure with the same identifier (or component name) but different formal parameter lists.

Вам также может понравиться