informatica
March 7, 2017 | Author: Jeremy Collins | Category: N/A
Short Description
informatica...
Description
Solution for Informatica problems
>> Scenario based solutions
Classic
Flipcard
Magazine
Mosaic
Sidebar
Snapshot
Timeslide
1. DEC
3
Diff between Primary key and unique key Scenario: Diff between Primary key and unique key Solution:
Unique key display the unique values which can have one null value where Primary key has unique values without null. Whenever you create the primary key constraints, Oracle by default create a unique index with not null.
Posted 3rd December 2012 by Prafull Dangore 0
Add a comment 2.
3. JUN
15
SQL Transformation with examples ==================================================================================== =========
SQL Transformation with examples Use: SQL Transformation is a connected transformation used to process SQL queries in the midstream of a pipeline. We can insert, update, delete and retrieve rows from the database at run time using the SQL transformation. Use SQL transformation in script mode to run DDL (data definition language) statements like creating or dropping the tables.
The following SQL statements can be used in the SQL transformation. Data Definition Statements (CREATE, ALTER, DROP, TRUNCATE, RENAME) DATA MANIPULATION statements (INSERT, UPDATE, DELETE, MERGE) DATA Retrieval Statement (SELECT) DATA Control Language Statements (GRANT, REVOKE) Transaction Control Statements (COMMIT, ROLLBACK) Scenario: Let’s say we want to create a temporary table in mapping while workflow is running for some intermediate calculation. We can use SQL transformation in script mode to achieve the same. Below we will see how to create sql transformation in script mode with an example where we will create a table in mapping and will insert some rows in the same table. Solution:
Step 1: Create two text files in the $PMSourceFileDir directory with some sql queries. 1. sql_script.txt File contains the below Sql queries (you can have multiple sql queries in file separated by semicolon) create table create_emp_table (emp_id number,emp_name varchar2(100)) 2.
sql_script2.txt File contains the below Sql queries (you can have multiple sql queries in file separated by semicolon)
insert into create_emp_table values (1,'abc') These are the script files to be executed by SQL transformation on database server. Step 2: We need a source which contains the above script file names with a complete path. So, I created another file in the $PMSourceFileDir directory to store these script file names as Sql_script_input.txt. File contains the list of files with their complete path: E:\softs\Informatica\server\infa_shared\SrcFiles\sql_script.txt E:\softs\Informatica\server\infa_shared\SrcFiles\sql_script2.txt Step 3: Now we will create a mapping to execute the script files using the SQL transformation. Go to the mapping designer tool, source analyzer and Import from file =>then creates source definition by selecting a file Sql_script_input.txt Located E:\softs\Informatica\server\infa_shared\SrcFiles. Source definition will look like
at
Similarly create a target definition, go to target designer and create a target flat file with result and error ports. This is shown in the below image
Step 4: Go to the mapping designer and create a new mapping. Drag the flat file into the mapping designer. Go to the Transformation in the toolbar, Create, select the SQL transformation, enter a name and click on create. Now select the SQL transformation options as script mode and DB type as Oracle and click ok.
The SQL transformation is created with the default ports. Now connect the source qualifier transformation ports to the SQL transformation input port. Drag the target flat file into the mapping and connect the SQL transformation output ports to the target. Save the mapping. The mapping flow image is shown in the below picture.
Go to the workflow manager; create a new workflow and session. Edit the session. For source, enter the source & target file directory. For the SQL transformation, enter the oracle database relational connection as shown below.
Save the workflow and run it. Open the target file, you will find the below data. "PASSED"; "PASSED"; "PASSED"; -: for sql_script.txt, where it will crate the table and "PASSED"; -: For sql_scriptw.txt, where it will insert rows in to the table
Fire a select query on the database to check whether table is created or not.
=============================================================================
Posted 15th June 2012 by Prafull Dangore 0
Add a comment
4. JUN
7
Efficient SQL Statements : SQL Tunning Tips
Efficient SQL Statements This is an extremely brief look at some of the factors that may effect the efficiency of your SQL and PL/SQL code. It is not intended as a thorough discussion of the area and should not be used as such.
Check Your Stats Why Indexes Aren't Used Caching Tables EXISTS vs. IN Presence Checking Inequalities When Things Look Bad! Driving Tables (RBO Only) Improving Parse Speed Packages Procedures and Functions Check Your Stats The Cost Based Optimizer (CBO) uses statistics to decide which execution plan to use. If these statistics are incorrect the decision made by the CBO may be incorrect. For this reason it is important to make sure that these statistics are refreshed regularly. The following article will help you achieve this aim.
Cost Based Optimizer (CBO) and Database Statistics Why Indexes Aren't Used The presence of an index on a column does not guarantee it will be used. The following is a small list of factors that will prevent an index from being used.
The optimizer decides it would be more efficient not to use the index. If your query is returning the majority of the data in a table, then a full table scan is probably going to be the most efficient way to access the table. You perform a function on the indexed column i.e. WHERE UPPER(name) = 'JONES'. The solution to this is to use a Function-Based Index. You perform mathematical operations on the indexed column i.e. WHERE salary + 1 = 10001 You concatenate a column i.e. WHERE firstname || ' ' || lastname = 'JOHN JONES'
You do not include the first column of a concatenated index in the WHERE clause of your statement. For the index to be used in a partial match, the first column (leading-edge) must be used. Index Skip Scanning in Oracle 9i and above allow indexes to be used even when the leading edge is not referenced. The use of 'OR' statements confuses the Cost Based Optimizer (CBO). It will rarely choose to use an index on column referenced using an OR statement. It will even ignore optimizer hints in this situation. The only way of guaranteeing the use of indexes in these situations is to use an INDEX hint. EXISTS vs. IN The EXISTS function searches for the presence of a single row meeting the stated criteria as opposed to the IN statement which looks for all occurrences. TABLE1 - 1000 rows TABLE2 - 1000 rows (A) SELECT t1.id FROM table1 t1 WHERE t1.code IN (SELECT t2.code FROM table2 t2); (B) SELECT t1.id FROM table1 t1 WHERE EXISTS (SELECT '1' FROM table2 t2 WHERE t2.code = t1.code) For query A, all rows in TABLE2 will be read for every row in TABLE1. The effect will be 1,000,000 rows read from items. In the case of query B, a maximum of 1 row from TABLE2 will be read for each row of TABLE1, thus reducing the processing overhead of the statement. Rule of thumb:
If the majority of the filtering criteria are in the subquery then the IN variation may be more performant. If the majority of the filtering criteria are in the top query then the EXISTS variation may be more performant. I would suggest they you should try both variants and see which works the best. Note. In later versions of Oracle there is little difference between EXISTS and IN operations. Presence Checking The first question you should ask yourself is, "Do I need to check for the presence of a record?" Alternatives to presence checking include:
Use the MERGE statement if you are not sure if data is already present. Perform an insert and trap failure because a row is already present using theDUP_VAL_ON_INDEX exception handler. Perform an update and test for no rows updated using SQL%ROWCOUNT.
If none of these options are right for you and processing is conditional on the presence of certain records in a table, you may decide to code something like the following. SELECT Count(*) INTO v_count FROM items WHERE item_size = 'SMALL'; IF v_count = 0 THEN -- Do processing related to no small items present END IF; If there are many small items, time and processing will be lost retrieving multiple records which are not needed. This would be better written like one of the following. SELECT COUNT(*) INTO v_count FROM items WHERE item_size = 'SMALL' AND rownum = 1; IF v_count = 0 THEN -- Do processing related to no small items present END IF; OR SELECT COUNT(*) INTO v_count FROM dual WHERE EXISTS (SELECT 1 FROM items WHERE item_size = 'SMALL'); IF v_count = 0 THEN -- Do processing related to no small items present END IF; In these examples only single a record is retrieved in the presence/absence check. Inequalities If a query uses inequalities (item_no > 100) the optimizer must estimate the number of rows returned before it can decide the best way to retrieve the data. This estimation is prone to errors. If you are aware of the data and it's distribution you can use optimizer hints to encourage or discourage full table scans to improve performance. If an index is being used for a range scan on the column in question, the performance can be improved by substituting >= for >. In this case, item_no > 100 becomes item_no >= 101. In the first case, a full scan of the index will occur. In the second case, Oracle jumps straight to the first index entry with an item_no of 101 and range scans from this point. For large indexes this may significantly reduce the number of blocks read.
When Things Look Bad! If you have a process/script that shows poor performance you should do the following:
Write sensible queries in the first place! Identify the specific statement(s) that are causing a problem. The simplest way to do this is to use SQL Trace, but you can try running the individual statements using SQL*Plus and timing them (SET TIMING ON) Use EXPLAIN to look at the execution plan of the statement. Look for any full table accesses that look dubious. Remember, a full table scan of a small table is often more efficient than access by index. Check to see if there are any indexes that may help performance. Try adding new indexes to the system to reduce excessive full table scans. Typically, foreign key columns should be indexed as these are regularly used in join conditions. On occasion it may be necessary to add composite (concatenated) indexes that will only aid individual queries. Remember, excessive indexing can reduce INSERT, UPDATE and DELETE performance. Driving Tables (RBO Only) The structure of the FROM and WHERE clauses of DML statements can be tailored to improve the performance of the statement. The rules vary depending on whether the database engine is using the Rule or Cost based optimizer. The situation is further complicated by the fact that the engine may perform a Merge Join or a Nested Loop join to retrieve the data. Despite this, there are a few rules you can use to improve the performance of your SQL. Oracle processes result sets a table at a time. It starts by retrieving all the data for the first (driving) table. Once this data is retrieved it is used to limit the number of rows processed for subsequent (driven) tables. In the case of multiple table joins, the driving table limits the rows processed for the first driven table. Once processed, this combined set of data is the driving set for the second driven table etc. Roughly translated into English, this means that it is best to process tables that will retrieve a small number of rows first. The optimizer will do this to the best of it's ability regardless of the structure of the DML, but the following factors may help. Both the Rule and Cost based optimizers select a driving table for each query. If a decision cannot be made, the order of processing is from the end of the FROM clause to the start. Therefore, you should always place your driving table at the end of the FROM clause. Subsequent driven tables should be placed in order so that those retrieving the most rows are nearer to the start of the FROM clause. Confusingly, the WHERE clause should be writen in the opposite order, with the driving tables conditions first and the final driven table last. ie. FROM d, c, b, a WHERE a.join_column = 12345 AND a.join_column = b.join_column AND b.join_column = c.join_column AND c.join_column = d.join_column;
If we now want to limit the rows brought back from the "D" table we may write the following. FROM d, c, b, a WHERE a.join_column = 12345 AND a.join_column = b.join_column AND b.join_column = c.join_column AND c.join_column = d.join_column AND d.name = 'JONES'; Depending on the number of rows and the presence of indexes, Oracle my now pick "D" as the driving table. Since "D" now has two limiting factors (join_column and name), it may be a better candidate as a driving table so the statement may be better written as follows. FROM c, b, a, d WHERE d.name = 'JONES' AND d.join_column = 12345 AND d.join_column = a.join_column AND a.join_column = b.join_column AND b.join_column = c.join_column This grouping of limiting factors will guide the optimizer more efficiently making table "D" return relatively few rows, and so make it a more efficient driving table. Remember, the order of the items in both the FROM and WHERE clause will not force the optimizer to pick a specific table as a driving table, but it may influence it's decision. The grouping of limiting conditions onto a single table will reduce the number of rows returned from that table, and will therefore make it a stronger candidate for becoming the driving table. Caching Tables Queries will execute much faster if the data they reference is already cached. For small frequently used tables performance may be improved by caching tables. Normally, when full table scans occur, the cached data is placed on the Least Recently Used (LRU) end of the buffer cache. This means that it is the first data to be paged out when more buffer space is required. If the table is cached (ALTER TABLE employees CACHE;) the data is placed on the Most Recently Used (MRU) end of the buffer, and so is less likely to be paged out before it is re-queried. Caching tables may alter the CBO's path through the data and should not be used without careful consideration. Improving Parse Speed Execution plans for SELECT statements are cached by the server, but unless the exact same statement is repeated the stored execution plan details will not be reused. Even differing spaces in the statement will cause this lookup to fail. Use of bind variables allows you to repeatedly use the same statements whilst changing the WHERE clause criteria. Assuming the statement does not have a cached execution plan it must be parsed before execution. The parse phase for statements can be decreased by efficient use of aliasing. If an alias is not present, the engine must resolve which tables own the specified columns. The following is an example. Bad Statement
Good Statement
SELECT first_name, last_name, country FROM employee, countries WHERE country_id = id AND lastname = 'HALL';
SELECT e.first_name, e.last_name, c.country FROM employee e, countries c WHERE e.country_id = c.id AND e.last_name = 'HALL';
Packages Procedures and Functions When an SQL statement, or anonymous block, is passed to the server it is processed in three phases. Phase Actions Parse Syntax Check and Object Resolution Execution Necessary Reads and Writes performed Fetch Resultant rows are Retrieved, Assembled, Sorted and Returned The Parse phase is the most time and resource intensive. This phase can be avoided if all anonymous blocks are stored as Database Procedures, Functions, Packages or Views. Being database objects their SQL text and compiled code is stored in Data Dictionary and the executable copies reside in the Shared Pool.
Posted 7th June 2012 by Prafull Dangore 0
Add a comment
5. JUN
7
Function : NVL2 and COALESCE NVL2 The NVL2 function accepts three parameters. If the first parameter value is not null it returns the value in the second parameter. If the first parameter value is null, it returns the third parameter. The following query shows NVL2 in action. SQL> SELECT * FROM null_test_tab ORDER BY id; ID COL1 COL2 COL3 COL4 ---------- ---------- ---------- ---------- ---------1 ONE TWO THREE FOUR 2 TWO THREE FOUR
3 4
THREE THREE
FOUR THREE
4 rows selected. SQL> SELECT id, NVL2(col1, col2, col3) AS output FROM null_test_tab ORDER BY id; ID OUTPUT ---------- ---------1 TWO 2 THREE 3 THREE 4 THREE 4 rows selected. SQL> COALESCE The COALESCE function was introduced in Oracle 9i. It accepts two or more parameters and returns the first non-null value in a list. If all parameters contain null values, it returns null. SQL> SELECT id, COALESCE(col1, col2, col3) AS output FROM null_test_tab ORDER BY id; ID OUTPUT ---------- ---------1 ONE 2 TWO 3 THREE 4 THREE 4 rows selected. SQL>
Posted 7th June 2012 by Prafull Dangore 0
Add a comment 6.
7. FEB
8
Load the session statistics such as Session Start & End Time, Success Rows, Failed Rows and Rejected Rows etc. into a database table for audit/log purpose.
Scenario: Load the session statistics such as Session Start & End Time, Success Rows, Failed Rows and Rejected Rows etc. into a database table for audit/log purpose. Solution: After performing the below solution steps your end workflow will look as follows: START => SESSION1 => ASSIGNMENT TASK => SESSION2
SOLUTION STEPS SESSION1 This session is used to achieve your actual business logic. Meaning this session will perform your actual data load. It can be anything File Table.File or TableTable, File WORKFLOW
VARIABLES
Create
the
following
workflow
=> => => => =>
variables. $$Workflowname $$SessionStartTime $$SessionEndTime $$TargetSuccessrows $$TargetFailedRows
ASSIGNMENT Use
the
Expression
TASK tab
$$workflowname $$sessionStartTime $$SessionEndTime $$ TargetSuccessrows $$ TargetFailedRows
in
the
Assignment =
= = = =
Task
and
$ $ $ $
SESSION1. SESSION1.
assign
as
follows:
$PMWorkflowName SESSION1.StartTime SESSION1.Endtime TgtSuccessRows TgtFailedRows
SESSION2 This session is used to load the session statistics into a database table. => This should call a mapping say ‘m_sessionLog’ => This mapping m_sessionLog should have mapping variables for the above defined workflow variables such as $$wfname, $$Stime, $$Etime, $$TSRows and $$TFRows. => This mapping m_sessionLog should use a dummy source and it must have a expression transformation and a target => database Audit table) => Inside the expression you must assign the mapping variables to the output ports
workflowname=$$wfname starttime=$$Stime endtime=$$Etime SucessRows=$$TSRows FailedRows=$$TFRows => Create a target database table with the following columns Workflowname, start time, end time, success rows and failed rows. => Connect all the required output ports to the target which is nothing but your audit table. PRE-Session Variable => Session 2: In the Pre-session variable assignment tab assign the mapping variable = workflow variable => In our case $$wfname=$$workflowname $$Stime=$$sessionStartTime $$Etime=$$sessionEndTime $$TSRows=$$TargetSuccessrows $$TFRows=$$TargetFailedrows Workflow Execution Posted 8th February 2012 by Prafull Dangore 0
Add a comment
8. DEC
30
Use Target File Path in Parameter File Scenario: I want to use mapping parameter to store target file path. My question is can define file path in parameter file? If possible can anyone explain how to assign target file path as parameter? Solution: You can
define
$OutputFileName=your
the
file
path
file
in path
Give the above mentioned parameter in your parameter file. Posted 30th December 2011 by Prafull Dangore 0
Add a comment
parameter
file. here
9. DEC
27
Insert and reject records using update strategy. Scenario: Insert and reject records using update strategy. There is an emp table and from that table insert the data to targt where sal c: emp\%LOG_FILE_NAME% :exit
OR @echo off for /F "tokens=2,3,4 delims=/ " %%i in ('date/t') do set y=%%k for /F "tokens=2,3,4 delims=/ " %%i in ('date/t') do set d=%%k%%i%%j for /F "tokens=5-8 delims=:. " %%i in ('echo.^| time ^| find "current" ') do set t=%%i%%j set t=%t%_ if "%t:~3,1%"=="_" set t=0%t% set t=%t:~0,4% set "theFilename=%d%%t%" echo %theFilename% Posted 20th December 2011 by Prafull Dangore 0
Add a comment
22. DEC
19
PL/SQL Interview Questions 1. What is PL/SQL ? PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL's language syntax, structure and datatypes are similar to that of ADA. The language includes object oriented programming techniques such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings state-of-the-art programming to the Oracle database server and a variety of Oracle tools. PL SQL is a block structured programming language. It combines data manipulation & data processing power. It supports all SQL data types. Also has its own data types i,e BOOLEAN,BINARY INTEGER 2. What is the basic structure of PL/SQL ? A PL/SQL block has three parts: a declarative part, an executable part, and an exception-handling part.
First comes the declarative part, in which items can be declared. Once declared, items can be manipulated in the executable part. Exceptions raised during execution can be dealt with in the exception-handling part. 3. What are the components of a PL/SQL block ?
PL/SQL Declare : Variable Begin Procedural
Block
contains
:
: optional declaration Manadatory statements.
Exception : any End : 5. What are Following are Scalar BINARY_INTEGER DEC DECIMAL DOUBLE FLOAT INT INTEGER NATURAL NATURALN NUMBER NUMERIC PLS_INTEGER POSITIVE POSITIVEN REAL SIGNTYPE SMALLINT CHAR CHARACTER LONG LONG NCHAR NVARCHAR2 RAW ROWID STRING UROWID VARCHAR VARCHAR2 DATE INTERVAL INTERVAL TIMESTAMP TIMESTAMP TIMESTAMP
errors
the
to
datatypes
the
datatype
Optional trapped Mandatory
be
a
available
supported
in
in
PL/SQL
oracle
?
PLSQL Types
PRECISION
RAW
DAY YEAR WITH
TO TO LOCAL
WITH
SECOND MONTH TIME
TIME
ZONE ZONE
BOOLEAN Composite RECORD TABLE VARRAY LOB BFILE BLOB CLOB
Types
Types
NCLOB Reference REF REF object_type
Types CURSOR
6. What
are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?% TYPE provides the data type of a variable or a database column to that variable. % ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor. The advantages are : I. Need not know about variable's data type ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.
Advantage is, if one change the type or size of the column in the table, it will be reflected in our program unit without making any change. %type is used to refer the column's datatype where as %rowtype is used to refer the whole record in a table. 7. What is difference between % ROWTYPE and TYPE RECORD ? % ROWTYPE is to be used whenever query returns a entire row of a table or view. TYPE rec RECORD is to be used whenever query returns columns of different table or views and variables. E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type); e_rec emp% ROWTYPE cursor c1 is select empno,deptno from emp; e_rec c1 %ROWTYPE. 8. What is PL/SQL table ? A PL/SQL table is a one-dimensional, unbounded, sparse collection of homogenous elements, indexed by integers One-dimensional A PL/SQL table can have only one column. It is, in this way, similar to a one-dimensional array. Unbounded or Unconstrained There is no predefined limit to the number of rows in a PL/SQL table. The PL/SQL table grows dynamically as you add more rows to the table. The PL/SQL table is, in this way, very different from an array. Related to this definition, no rows for PL/SQL tables are allocated for this structure when it is defined. Sparse In a PL/SQL table, a row exists in the table only when a value is assigned to that row. Rows do not have to be defined sequentially. Instead you can assign a value to any row in the table. So row 15 could have a value of `Fox' and row 15446 a value of `Red', with no other rows defined in between. Homogeneous elements Because a PL/SQL table can have only a single column, all rows in a PL/SQL table contain values of the same datatype. It is, therefore, homogeneous. With PL/SQL Release 2.3, you can have PL/SQL tables of records. The resulting table is still, however, homogeneous. Each row simply contains the same set of columns. Indexed by integers PL/SQL tables currently support a single indexing mode: by BINARY_INTEGER. This number acts as the "primary key" of the PL/SQL table. The range of a BINARY_INTEGER is from -231-1 to 231-1, so you have an awful lot of rows with which to work 9. What is a cursor ? Why Cursor is required ? Cursor is a named private SQL area from where information can be Cursors are required to process rows individually for queries returning multiple rows. 10. Explain the two type of Cursors ?
accessed.
implicit cursor: implicit cursor is a type of cursor which is automatically maintained by the Oracle server itself.implicit cursor returns only one row.
Explicit Cursor: Explicit Cursor is defined by the Proframmer,and phases:declare,open,fetch and close.explicit Cursor returns more than one row.
it
has
for
11. What are the PL/SQL Statements used in cursor processing ? DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types, CLOSE cursor name. 12. What are the cursor attributes used in PL/SQL ? %ISOPEN - to check whether cursor is open or not % ROWCOUNT - number of rows fetched/updated/deleted. % FOUND - to check whether cursor has fetched any row. True if rows are fetched. % NOT FOUND - to check whether cursor has fetched any row. True if no rows are featched. These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit Cursors 13. What is a cursor for loop ? Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values from active set into fields in the record and closes when all the records have been processed. eg. FOR emp_rec IN C1 LOOP salary_total := salary_total +emp_rec sal; END LOOP; cursor for loop is use for automatically open ,fetch,close 15. Explain the usage of WHERE CURRENT OF clause in cursors ? PL/SQL provides the WHERE CURRENT OF clause for both UPDATE and DELETE statements inside a cursor in order to allow you to easily make changes to the most recently fetched row of data. The general format for the WHERE CURRENT OF clause is as follows:
UPDATE table_name SET set_clause WHERE CURRENT OF cursor_name;DELETE table_name WHERE CURRENT OF cursor_name;
FROM
Notice that the WHERE CURRENT OF clause references the cursor and not the record into which the next fetched row is deposited. The most important advantage to using WHERE CURRENT OF where you need to change the row fetched last is that you do not have to code in two (or more) places the criteria used to uniquely identify a row in a table. Without WHERE CURRENT OF, you would need to repeat the WHERE clause of your cursor in the WHERE clause of the associated UPDATEs and DELETEs. As a result, if the table structure changes in a way that affects the construction of the primary key, you have to make sure that each SQL statement is upgraded to support this change. If you use WHERE CURRENT OF, on the other hand, you only have to modify the WHERE clause of the SELECT statement. This might seem like a relatively minor issue, but it is one of many areas in your code where you can leverage subtle features in PL/SQL to minimize code redundancies. Utilization of WHERE CURRENT OF, %TYPE, and %ROWTYPE declaration attributes, cursor FOR loops, local modularization, and other PL/SQL language constructs can have a big impact on reducing the pain you may experience when you maintain your Oracle-based applications. Let's see how this clause would improve the previous example. In the jobs cursor FOR loop above, I want to UPDATE the record that was currently FETCHed by the cursor. I do this in the UPDATE statement by repeating the same WHERE used in the cursor because (task, year) makes up the primary key of this table:
WHERE task = job_rec.task
AND year = TO_CHAR (SYSDATE, 'YYYY');
This is a less than ideal situation, as explained above: I have coded the same logic in two places, and this code must be kept synchronized. It would be so much more convenient and natural to be able to code the equivalent of the following statements: Delete the record I just fetched. or: Update these columns in that row I just fetched.
A perfect fit for WHERE CURRENT OF! The next version of my winterization program below uses this clause. I have also switched to a simple loop from FOR loop because I want to exit conditionally from the loop:
DECLARE CURSOR fall_jobs_cur IS SELECT ... same as before fall_jobs_cur%ROWTYPE;BEGIN OPEN fall_jobs_cur; fall_jobs_cur INTO fall_jobs_cur%NOTFOUND THEN EXIT; ELSIF job_rec.do_it_yourself_flag = 'YOUCANDOIT' THEN SET responsible = 'STEVEN' WHERE fall_jobs_cur; COMMIT; EXIT; END LOOP; CLOSE fall_jobs_cur;END;
... ; job_rec LOOP FETCH job_rec; IF UPDATE winterize CURRENT OF IF; END
16. What is a database trigger ? Name some usages of database trigger ? A database trigger is a stored procedure that is invoked automatically when a predefined event occurs. Database triggers enable DBA's (Data Base Administrators) to create additional relationships between separate databases. For example, the modification of a record in one database could trigger the modification of a record in a second database. 17. How many types of database triggers can be specified on a table ? What are they ? Insert
Update
Before Row After Row
o.k. o.k.
Before Statement After Statement
Delete o.k. o.k.
o.k. o.k.
o.k. o.k.
o.k. o.k. o.k. o.k.
If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement. If WHEN clause is specified, the trigger fires according to the returned Boolean value. the different types of triggers: * Row Triggers and Statement Triggers * BEFORE and AFTER Triggers * INSTEAD OF Triggers * Triggers on System Events and User Events 18. What are two virtual tables available during database trigger execution ? The table columns are referred as OLD.column_name and NEW.column_name. For triggers related to INSERT only NEW.column_name values only available. For triggers related to UPDATE only OLD.column_name NEW.column_name values only available. For triggers related to DELETE only OLD.column_name values only available. The two virtual table available are old and new. 19.What happens if a procedure that updates a column of table X is called in a database trigger of the same table ?
To avoid the mutation table error ,the procedure should be declared as an AUTONOMOUS TRANSACTION. By this the procedure will be treated as an separate identity. 20. Write the order of precedence for validation of a column in a table ? I. done using Database triggers. ii. done using Integarity Constraints. 21. What is an Exception ? What are types of Exception ?
Predefined Do not declare and allow the Oracle server to raise implicitly NO_DATA_FOUND TOO_MANY_ROWS
INVALID_CURSOR ZERO_DIVIDE INVALID_CURSOR WHEN EXCEPTION THEN …
Non predefined
o o
Declare within the declarative section and allow allow Oracle server to raise implicitly SQLCODE – Returns the numeric value for the seeor code SQLERRM – Returns the message associated with error number DECLARE -- PRAGMA EXCEPTION_INIT (exception, error_number) RAISE – WHEN EXCEPTION_NAME THEN …
User defined Declare within the declarative section and raise explicitly. IF confidition the RAISE EXCEPTION or RAISE_APPLICATION_ERROR
22. What is Pragma EXECPTION_INIT ? Explain the usage ? Pragma exception_init Allow you to handle the Oracle predefined message by you'r own message. means you can instruct compiler toassociatethe specific message to oracle predefined message at compile time.This way you Improve the Readbility of your program,and handle it accoding to your own way. It should be declare at the DECLARE section. example declare salary number; FOUND_NOTHING exception; Pragma exception_init(FOUND_NOTHING ,100); begin select sal in to salaryfrom emp where ename ='ANURAG'; dbms_output.put_line(salary); exception WHEN FOUND_NOTHING THEN dbms_output.put_line(SQLERRM); end; 23. What is Raise_application_error ? Raise_application_error is used to create your own error messages which can be more descriptive than named exceptions. Syntax is:Raise_application_error (error_number,error_messages); where error_number is between -20000 to -20999.. 24. What are the return values of functions SQLCODE and SQLERRM ? Pl / Sql Provides Error Information via two Built-in functions, SQLCODE & SQLERRM. SQLCODE Returns the Current Error Code. Returns 1. SQLERRM Returns the Current Error Message Text. Returns " User Defined Exception " 25. Where the Pre_defined_exceptions are stored ? PL/SQL declares predefined exceptions in the STANDARD package.
26. What is a stored Stored Procedure is the PlSQL subprgram stored in the databasse .
procedure
?
Stored Procedure A program running in the database that can take complex actions based on the inputs you send it. Using a stored procedure is faster than doing the same work on a client, because the program runs right inside the databaseserver. Stored procedures are nomally written in PL/SQL or Java.
advantages fo Stored Procedure Extensibility,Modularity, Reusability, Maintainability and one time compilation. 28. What are the modes of parameters that can be passed to a procedure ? 1.in: in parameter mode is used to pass values to subprogram when invoked. 2.out: out is used to return values to callers of subprograms 3.in out: it is used to define in and out 29. What are the two parts of a procedure ? PROCEDURE name (parameter list.....) is local variable declarations BEGIN Executable statements. Exception. exception handlers end;
31. Give the structure of the function ? FUNCTION name (argument list .....) Return datatype is local variable declarations Begin executable statements Exception execution handlers End; 32. Explain how procedures and functions are
Procedure
can
a)
CALL
b) c)
EXCECUTE other
a
in
or the
?
ways direc
calling functions
block
environment or
packages
following
ways
a) EXCECUTE from calling environment. Always use a variable to get the return value. b) As part 33. What are two parts of package ?
of
an
SQL/PL
SQL
Expression
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. Package Specification contains declarations that are global to the packages and local to the schema. Package Body contains actual procedures and local declaration of the procedures and cursor declarations.
33.What is difference between a Cursor declared in a procedure and Cursor declared in a package specification ? A cursor declared in a package specification is global and can be accessed by other procedures or procedures in a package. A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures.
The scope of A cursor declared in a procedure is limited to that procedure only. The Scope of cursor declared in a package specification is global . Example: create or replace package curpack is cursor c1 is select * from emp; end curpack; This will create a package Now You can use this cursor any where. Like: set serveroutput on begin for r1 in curpack.c1 loop dbms_output.put_line(r1.empno||' '||r1.ename); end loop; end; this will dispaly all empno and enames. It will be better to use ref cursor in packages 35. How packaged procedures and functions are called from the following? a. Stored procedure or anonymous block b. an application program such a PRC *C, PRO* COBOL c. SQL *PLUS a. PACKAGE NAME.PROCEDURE NAME (parameters); variable := PACKAGE NAME.FUNCTION NAME (arguments); EXEC SQL EXECUTE b. BEGIN PACKAGE NAME.PROCEDURE NAME (parameters) variable := PACKAGE NAME.FUNCTION NAME (arguments); END; END EXEC; c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any out/in-out parameters. A function can not be called. 36.Name the tables where characteristics of Package, procedure and functions are stored ? The Data dictionary tables/ Views where the characteristics of subprograms and Packages are stored are mentioned below a)
USER_OBJECTS,
ALL_OBJECTS,
DBA_OBJECTS
b)
USER_SOURCE,
ALL_SOURCE,
DBA_SOURCE
c)
USER_DEPENCENCIES
d) USER_ERRORS, ALL_ERRORS, DBA_ERRORS 37. What is Overloading of procedures ?
Overloading procs are 2 or more procs with the same name but different arguments. Arguments needs to be different by class it self. ie char and Varchar2 are from same class. Packages The main advantages of packages are 1- Since packages has specification and body separate so, whenever any ddl is run and if any proc/func(inside pack) is dependent on that, only body gets invalidated and not the spec. So any other proc/func dependent on package does not gets invalidated.
2- Whenever any func/proc from package is called, whole package is loaded into memory and hence all objects of pack is availaible in memory which means faster execution if any is called. And since we put all related proc/func in one package this feature is useful as we may need to run most of the objects. 3- we can declare global variables in the package 38.Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger ? Why ? Autonomous Transaction is a feature of oracle 8i which maintains the state of its transactions and save it , to affect with the commit or rollback of the surrounding transactions. Here is the simple example to understand this :ora816
SamSQL
2
:>
declare
Procedure
InsertInTest_Table_B
3
is
4
BEGIN
5
INSERT
into
Test_Table_B(x)
values
(1);
6
Commit;
7
END
;
8 9
BEGIN INSERT
INTO
Test_Table_A(x)
values
(123);
10
InsertInTest_Table_B;
11
Rollback;
12
END;
13 ora816
/ SamSQL
PL/SQL :>
procedure Select
*
from
successfully Test_Table_A;
completed. X----------
123
ora816 SamSQL :> Select * from Test_Table_B; X---------- 1 Notice in above pl/sql COMMIT at line no 6 , commits the transaction at line-no 5 and line-no 9. The Rollback at line-no 11 actually did nothing. Commit/ROLLBACK at nested transactions will commit/rollback all other DML transaction before that. PRAGMA AUTONOMOUS_TRANSACTION override this behavior. Let us the see the following example with PRAGMA AUTONOMOUS_TRANSACTION. 39. What is difference between a PROCEDURE & FUNCTION ?
A function always return a values while procedure can return one or more values through Parameters. A function can call directly by sql statement like select "func_name" from dual while procedure cannot. 40. What is Data Concarency and Consistency?
Concurrency
How well can multiple sessions access the same data simultaneously
Consistency
How consistent is the view of the data between and within multiple sessions, transactions or statements 41. Talk about "Exception Handling" in PL/SQL?
the exception are written to handle the exceptions thrown by programs. we have user defined and system exception. user defined exception are the exception name given by user (explicitly decalred and used) and they are raised to handle the specific behaviour of program. system exceptions are raised due to invalid data(you dont have to deaclre these). few examples are when no_data_found, when others etc. 44. Can we use commit or rollback command in the exception part of PL/SQL block? Yes, we can use the TCL commands(commit/rollback) in the exception block of a stored procedure/function. The code in this part of the program gets executed like those in the body without any restriction. You can include any business functionality whenever a condition in main block(body of a proc/func) fails and requires a follow-thru process to terminate the execution gracefully! DECALRE ….. BEGIN ……. EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO err_log( err_code, code_desc) VALUES(‘1403’, ‘No data found’) COMMIT; RAISE; END 46. What is bulk binding please explain me in brief ?
Bulk Binds (BULK COLLECT , FORALL ) are a PL/SQL technique where, instead of multiple individual SELECT, INSERT, UPDATE or DELETE statements are executed to retrieve from, or store data in, at table, all of the operations are carried out at once, in bulk. This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL engine, then back to the PL/SQL engine, and so on, when you individually access rows one at a time. To do bulk binds with Insert, Update and Delete statements, you enclose the SQL statement within a PL/SQL FORALL statement. To do bulk binds with Select statements, you include the Bulk Collect INTO a collection clause in the SELECT Statement instead of using Simply into . Collections, BULK COLLECT and FORALL are the new features in Oracle 8i, 9i and 10g PL/SQL that can really make a different to you PL/SQL performance Bulk Binding is used for avoiding the context switching between the sql engine and pl/sql engine. If we use simple For loop in pl/sql block it will do context switching between sql and pl/sql engine for each row processing that degrades the performance of pl/sql bloack. So that for avoiding the context switching betn two engine we user FORALL keyword by using the collection pl/sql tables for DML. forall is pl/sql keyword. It will provides good result and performance increase. 47.Why Functions are used in oracle ?Can Functions Return more than 1 values?Why Procedures are used in oracle ?What are the Disadvantages of packages?What are the Global Variables in Packages?
The functions are used where we can't used the procedure.i.e we can use a function the in select statments,in the where clause of delete/update statments.But the procedure can't used like that. It is true that function can return only one value, but a function can be used to return more than one value,by using out parameters and also by using ref cursors.
There is no harm in using the out parameter,when functins are used in the DML statements we can't used the out parameter(as per rules). 49. What are the restrictions on Functions ?
Function cannot have DML statemets and we can use select statement in function If you create function with DML statements we get message function will be created But if we use in select statement we get error 50. What happens when a package is initialized ? when a package is initialised that is called for the first time the entire package is loaded into SGA and any variable declared in the package is initialises. 52. What is PL/SQL table? Pl/Sql table is a type of datatype in procedural language Extension.It has two columns.One for the index,say Binary index And another column for the datas,which might further extend to any number of rows (not columns)in future. PL/SQL table is nothing but one dimensional array. It is used to hold similar type of data for temporary storage. Its is indexed by binary integer. 3. can i write plsql block inside expection Yes you can write PL/SQL block inside exception section. Suppose you want to insert the exception detail into your error log table, that time you can write insert into statement in exception part. To handle the exception which may be raised in your exception part, you can write the PL/SQL code in exception part. 54. Can e truncate some of the rows from the table instead of truncating the full table. You can truncate few rows from a table if the table is partitioned. You can truncate a single partition and keep remaining.
CREATE state sales PARTITION PARTITION TABLESPACE PARTITION TABLESPACE INSERT INSERT INSERT INSERT COMMIT; SELECT ALTER TRUNCATE
TABLE
BY northwest southwest
INTO INTO INTO INTO
parttab parttab parttab parttab
parttab
LIST VALUES
(state) ('OR',
VALUES
VALUES VALUES VALUES VALUES
*
FROM TABLE PARTITION
('AZ',
('OR', ('WA', ('AZ', ('CA',
( VARCHAR2(2), NUMBER(10,2)) ( 'WA') uwdata, 'CA') uwdata); 100000); 200000); 300000); 400000); parttab; parttab southwest;
SELECT * FROM parttab; 56. What is the difference between a reference cursor and normal cursor ? REF cursors are different than your typical, standard cursors. With standard cursors, you know the cursor's query ahead of time. With REF cursors, you do not have to know the query ahead of time. With REF Cursors, you can build the cursor on the fly Normal Cursor is a Static Cursor. Refernce Cursor is used to create dynamic cursor. There are two types of Ref Cursors: 1. Weak cursor and 2.Strong cursor Type ref_name is Ref cursor [return type] [return type] means %Rowtype if Return type is mentioned then it is Strong cursor else weak cursor
The
Reference
cursor
does
not
support
For
update
clause.
Normal cursor is used to process more than one record in plsql. Refcusor is a type which is going to hold set of records which can be sent out through the procedure or function out variables. we can use Ref cursor as an IN OUT parameter . 58. Based on what conditions can we decide whether to use a table or a view or a materialized view ? Table is the basic entity in any RDBMS , so for storing data you need table . for view - if you have complex query from which you want to extract data again and again , moreover it is a standard data which is required by many other user also for REPORTS generation then create view . Avoid to insert / update / delete through view unless it is essential. keep view as read only (FOR SHOWING REPORTS) for materialized view - this view ia mainly used in datawarehousing . if you have two databases and you want a view in both databases , remember in datawarehousing we deal in GB or TB datasize . So create a summary table in a database and make the replica(materialized view) in other database. when to create materialized view[1] if data is in bulk and you need same data in more than one database then create summary table at one database and replica in other databases [2] if you have summary columns in projection list of query. main advatages of materialized view over simple view are [1] it save data in database whether simple view's definition is saved in database [2] can create parition or index on materialize view to enhance the performance of view , but cannot on simple view. 59. What is the difference between all_ and user_ tables ? An ALL_ view displays all the information accessible to the current user, including information from the current user's schema as well as information from objects in other schemas, if the current user has access to those objects by way of grants of privileges or roles. While
A USER_ view displays all the information from the schema of the current user. No special privileges are required to query these views. User_tables data dictionary contains all the tables created by the users under that schema. whereas All_tables stores all the tables created in different schema. If any user id have the Grants for access table of diff. schema then he can see that table through this dictionary. 61. what is p-code and sourcecode ? P-code is Pre-complied code stored in Public cache memory of System Global Area after the Oracle instance is started, whereas sourcecode is a simple code of sp, package, trigger, functions etc which are stored in Oracle system defined data dictionary. Every session of oracle access the p-code which have the Execute permission on that objects. Source code stored in user_objects data dictinary for user defined Store proc, Trigger, Package, Function. DBA_object stores all the db objects in sp. DB. ALL_objects stores all the db objects in sp. schema. Source code: The code say a PLSQL block that the user types for the exectionP-Code: The source code after -Syntax check, Parse tree generation, Symantic check, and further execution of the parse tree..giving the final P-code ready for data fetch or manipulation ... 63. Is there any limitation on no. of triggers that can be created on a table?
There is no you can write as if table has got n
limit on number of triggers on one many u want for insert,update or delte by diff columns. we can create n triggers based on each
table. names. column.
64.What happens when DML Statement fails?A.User level rollbackB.Statement Level RollbackC.Sustem evel Rollback When a DML statement executes (fails/sucess) an automatic Commit is executed. Eg : Create a table t1. Insert a record in t1. Then again to create the same object t1.
65.What steps should a programmer should follow for better tunning of the PL/SQL blocks? SQL Queries – Best Practices 1.
Always use the where clause in your select statement to narrow the number of rows returned. If we don’t use a where clause, the Oracle performs a full table scan on our table and returns all of the rows.
2.
Use EXISTS clause instead of IN clause as it is more efficient than IN and performs faster. Ex: Replace SELECT * FROM DEPT WHERE DEPTNO IN (SELECT DEPTNO FROM EMP E) With SELECT * FROM DEPT D WHERE EXISTS (SELECT 1 FROM EMP E WHERE D.DEPTNO = E.DEPTNO) Note: IN checks all rows. Only use IN if the table in the sub-query is extremely small.
3.
When you have a choice of using the IN or the BETWEEN clauses in your SQL, use the BETWEEN clause as it is much more efficient than IN. Depending on the range of numbers in a BETWEEN, the optimizer will choose to do a full table scan or use the index.
4.
Avoid WHERE clauses that are non-sargable. Non-sargable search arguments in the WHERE clause, such as "IS NULL", "OR", "", "!=", "!>", "! max_salary THEN RAISE salary_too_high; -- raise the exception END IF; EXCEPTION WHEN salary_too_high THEN -- first step in handling the error DBMS_OUTPUT.PUT_LINE('Salary ' || erroneous_salary || ' is out of range.'); DBMS_OUTPUT.PUT_LINE('Maximum salary is ' || max_salary || '.'); RAISE; -- reraise the current exception END; ------------ sub-block ends EXCEPTION WHEN salary_too_high THEN -- handle the error more thoroughly erroneous_salary := current_salary; current_salary := max_salary; DBMS_OUTPUT.PUT_LINE('Revising salary from ' || erroneous_salary || ' to ' || current_salary || '.'); END; / Handling Raised PL/SQL Exceptions When an exception is raised, normal execution of your PL/SQL block or subprogram stops and control transfers to its exception-handling part, which is formatted as follows:
EXCEPTION WHEN exception1 THEN -- handler for exception1 sequence_of_statements1 WHEN exception2 THEN -- another handler for exception2 sequence_of_statements2 ... WHEN OTHERS THEN -- optional handler for all other errors sequence_of_statements3 END; To catch raised exceptions, you write exception handlers. Each handler consists of a WHEN clause, which specifies an exception, followed by a sequence of statements to be executed when that exception is raised. These statements complete execution of the block or subprogram; control does not return to where the exception was raised. In other words, you cannot resume processing where you left off. The optional OTHERS exception handler, which is always the last handler in a block or subprogram, acts as the handler for all exceptions not named specifically. Thus, a block or subprogram can have only one OTHERS handler. Use of the OTHERS handler guarantees that no exception will go unhandled. If you want two or more exceptions to execute the same sequence of statements, list the exception names in the WHEN clause, separating them by the keyword OR, as follows: EXCEPTION WHEN over_limit OR under_limit OR VALUE_ERROR THEN -- handle the error If any of the exceptions in the list is raised, the associated sequence of statements is executed. The keyword OTHERS cannot appear in the list of exception names; it must appear by itself. You can have any number of exception handlers, and each handler can associate a list of exceptions with a sequence of statements. However, an exception name can appear only once in the exception-handling part of a PL/SQL block or subprogram. The usual scoping rules for PL/SQL variables apply, so you can reference local and global variables in an exception handler. However, when an exception is raised inside a cursor FOR loop, the cursor is closed implicitly before the handler is invoked. Therefore, the values of explicit cursor attributes are not available in the handler. Exceptions Raised in Declarations Exceptions can be raised in declarations by faulty initialization expressions. For example, the following declaration raises an exception because the constant credit_limit cannot store numbers larger than 999: Example 10-10 Raising an Exception in a Declaration DECLARE credit_limit CONSTANT NUMBER(3) := 5000; -- raises an error BEGIN NULL; EXCEPTION WHEN OTHERS THEN -- Cannot catch the exception. This handler is never called. DBMS_OUTPUT.PUT_LINE('Can''t handle an exception in a declaration.'); END; / Handlers in the current block cannot catch the raised exception because an exception raised in a declaration propagates immediately to the enclosing block. Handling Exceptions Raised in Handlers
When an exception occurs within an exception handler, that same handler cannot catch the exception. An exception raised inside a handler propagates immediately to the enclosing block, which is searched to find a handler for this new exception. From there on, the exception propagates normally. For example: EXCEPTION WHEN INVALID_NUMBER THEN INSERT INTO ... -- might raise DUP_VAL_ON_INDEX WHEN DUP_VAL_ON_INDEX THEN ... -- cannot catch the exception END; Branching to or from an Exception Handler A GOTO statement can branch from an exception handler into an enclosing block. A GOTO statement cannot branch into an exception handler, or from an exception handler into the current block. Retrieving the Error Code and Error Message: SQLCODE and SQLERRM In an exception handler, you can use the built-in functions SQLCODE and SQLERRM to find out which error occurred and to get the associated error message. For internal exceptions, SQLCODE returns the number of the Oracle error. The number that SQLCODE returns is negative unless the Oracle error is no data found, in which case SQLCODE returns +100. SQLERRM returns the corresponding error message. The message begins with the Oracle error code. For user-defined exceptions, SQLCODE returns +1 and SQLERRM returns the message User-Defined Exception unless you used the pragma EXCEPTION_INIT to associate the exception name with an Oracle error number, in which case SQLCODE returns that error number and SQLERRM returns the corresponding error message. The maximum length of an Oracle error message is 512 characters including the error code, nested messages, and message inserts such as table and column names. If no exception has been raised, SQLCODE returns zero and SQLERRM returns the message: ORA-0000: normal, successful completion. You can pass an error number to SQLERRM, in which case SQLERRM returns the message associated with that error number. Make sure you pass negative error numbers to SQLERRM. Passing a positive number to SQLERRM always returns the message user-defined exception unless you pass +100, in which caseSQLERRM returns the message no data found. Passing a zero to SQLERRM always returns the message normal, successful completion. You cannot use SQLCODE or SQLERRM directly in a SQL statement. Instead, you must assign their values to local variables, then use the variables in the SQL statement, as shown in Example 10-11. Example 10-11 Displaying SQLCODE and SQLERRM CREATE TABLE errors (code NUMBER, message VARCHAR2(64), happened TIMESTAMP); DECLARE name employees.last_name%TYPE; v_code NUMBER; v_errm VARCHAR2(64); BEGIN SELECT last_name INTO name FROM employees WHERE employee_id = -1; EXCEPTION WHEN OTHERS THEN v_code := SQLCODE; v_errm := SUBSTR(SQLERRM, 1 , 64); DBMS_OUTPUT.PUT_LINE('Error code ' || v_code || ': ' || v_errm); -- Normally we would call another procedure, declared with PRAGMA -- AUTONOMOUS_TRANSACTION, to insert information about errors.
INSERT INTO errors VALUES (v_code, v_errm, SYSTIMESTAMP); END; / The string function SUBSTR ensures that a VALUE_ERROR exception (for truncation) is not raised when you assign the value ofSQLERRM to err_msg. The functions SQLCODE and SQLERRM are especially useful in the OTHERS exception handler because they tell you which internal exception was raised. When using pragma RESTRICT_REFERENCES to assert the purity of a stored function, you cannot specify the constraints WNPS andRNPS if the function calls SQLCODE or SQLERRM. Catching Unhandled Exceptions Remember, if it cannot find a handler for a raised exception, PL/SQL returns an unhandled exception error to the host environment, which determines the outcome. For example, in the Oracle Precompilers environment, any database changes made by a failed SQL statement or PL/SQL block are rolled back. Unhandled exceptions can also affect subprograms. If you exit a subprogram successfully, PL/SQL assigns values to OUT parameters. However, if you exit with an unhandled exception, PL/SQL does not assign values to OUT parameters (unless they are NOCOPYparameters). Also, if a stored subprogram fails with an unhandled exception, PL/SQL does not roll back database work done by the subprogram. You can avoid unhandled exceptions by coding an OTHERS handler at the topmost level of every PL/SQL program. Tips for Handling PL/SQL Errors In this section, you learn techniques that increase flexibility. Continuing after an Exception Is Raised An exception handler lets you recover from an otherwise fatal error before exiting a block. But when the handler completes, the block is terminated. You cannot return to the current block from an exception handler. In the following example, if the SELECT INTO statement raises ZERO_DIVIDE, you cannot resume with the INSERT statement: CREATE TABLE employees_temp AS SELECT employee_id, salary, commission_pct FROM employees; DECLARE sal_calc NUMBER(8,2); BEGIN INSERT INTO employees_temp VALUES (301, 2500, 0); SELECT salary / commission_pct INTO sal_calc FROM employees_temp WHERE employee_id = 301; INSERT INTO employees_temp VALUES (302, sal_calc/100, .1); EXCEPTION WHEN ZERO_DIVIDE THEN NULL; END; / You can still handle an exception for a statement, then continue with the next statement. Place the statement in its own sub-block with its own exception handlers. If an error occurs in the sub-block, a local handler can
catch the exception. When the sub-block ends, the enclosing block continues to execute at the point where the sub-block ends, as shown in Example 10-12. Example 10-12 Continuing After an Exception DECLARE sal_calc NUMBER(8,2); BEGIN INSERT INTO employees_temp VALUES (303, 2500, 0); BEGIN -- sub-block begins SELECT salary / commission_pct INTO sal_calc FROM employees_temp WHERE employee_id = 301; EXCEPTION WHEN ZERO_DIVIDE THEN sal_calc := 2500; END; -- sub-block ends INSERT INTO employees_temp VALUES (304, sal_calc/100, .1); EXCEPTION WHEN ZERO_DIVIDE THEN NULL; END; / In this example, if the SELECT INTO statement raises a ZERO_DIVIDE exception, the local handler catches it and sets sal_calc to 2500. Execution of the handler is complete, so the sub-block terminates, and execution continues with the INSERT statement. See alsoExample 5-38, "Collection Exceptions". You can also perform a sequence of DML operations where some might fail, and process the exceptions only after the entire operation is complete, as described in "Handling FORALL Exceptions with the %BULK_EXCEPTIONS Attribute". Retrying a Transaction
1. 2. 3.
After an exception is raised, rather than abandon your transaction, you might want to retry it. The technique is: Encase the transaction in a sub-block. Place the sub-block inside a loop that repeats the transaction. Before starting the transaction, mark a savepoint. If the transaction succeeds, commit, then exit from the loop. If the transaction fails, control transfers to the exception handler, where you roll back to the savepoint undoing any changes, then try to fix the problem. In Example 10-13, the INSERT statement might raise an exception because of a duplicate value in a unique column. In that case, we change the value that needs to be unique and continue with the next loop iteration. If the INSERT succeeds, we exit from the loop immediately. With this technique, you should use a FOR or WHILE loop to limit the number of attempts. Example 10-13 Retrying a Transaction After an Exception CREATE TABLE results ( res_name VARCHAR(20), res_answer VARCHAR2(3) ); CREATE UNIQUE INDEX res_name_ix ON results (res_name); INSERT INTO results VALUES ('SMYTHE', 'YES'); INSERT INTO results VALUES ('JONES', 'NO'); DECLARE name VARCHAR2(20) := 'SMYTHE'; answer VARCHAR2(3) := 'NO'; suffix NUMBER := 1; BEGIN FOR i IN 1..5 LOOP -- try 5 times
BEGIN -- sub-block begins SAVEPOINT start_transaction; -- mark a savepoint /* Remove rows from a table of survey results. */ DELETE FROM results WHERE res_answer = 'NO'; /* Add a survey respondent's name and answers. */ INSERT INTO results VALUES (name, answer); -- raises DUP_VAL_ON_INDEX if two respondents have the same name COMMIT; EXIT; EXCEPTION WHEN DUP_VAL_ON_INDEX THEN ROLLBACK TO start_transaction; -- undo changes suffix := suffix + 1; -- try to fix problem name := name || TO_CHAR(suffix); END; -- sub-block ends END LOOP; END; /
Using Locator Variables to Identify Exception Locations Using one exception handler for a sequence of statements, such as INSERT, DELETE, or UPDATE statements, can mask the statement that caused an error. If you need to know which statement failed, you can use a locator variable: Example 10-14 Using a Locator Variable to Identify the Location of an Exception CREATE OR REPLACE PROCEDURE loc_var AS stmt_no NUMBER; name VARCHAR2(100); BEGIN stmt_no := 1; -- designates 1st SELECT statement SELECT table_name INTO name FROM user_tables WHERE table_name LIKE 'ABC%'; stmt_no := 2; -- designates 2nd SELECT statement SELECT table_name INTO name FROM user_tables WHERE table_name LIKE 'XYZ%'; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('Table name not found in query ' || stmt_no); END; / CALL loc_var(); Overview of PL/SQL Compile-Time Warnings To make your programs more robust and avoid problems at run time, you can turn on checking for certain warning conditions. These conditions are not serious enough to produce an error and keep you from compiling a subprogram. They might point out something in the subprogram that produces an undefined result or might create a performance problem. To work with PL/SQL warning messages, you use the PLSQL_WARNINGS initialization parameter, the DBMS_WARNING package, and theUSER/DBA/ALL_PLSQL_OBJECT_SETTINGS views. PL/SQL Warning Categories
PL/SQL warning messages are divided into categories, so that you can suppress or display groups of similar warnings during compilation. The categories are: SEVERE: Messages for conditions that might cause unexpected behavior or wrong results, such as aliasing problems with parameters. PERFORMANCE: Messages for conditions that might cause performance problems, such as passing a VARCHAR2 value to aNUMBER column in an INSERT statement. INFORMATIONAL: Messages for conditions that do not have an effect on performance or correctness, but that you might want to change to make the code more maintainable, such as unreachable code that can never be executed. The keyword All is a shorthand way to refer to all warning messages. You can also treat particular messages as errors instead of warnings. For example, if you know that the warning message PLW-05003represents a serious problem in your code, including 'ERROR:05003' in the PLSQL_WARNINGS setting makes that condition trigger an error message (PLS_05003) instead of a warning message. An error message causes the compilation to fail. Controlling PL/SQL Warning Messages To let the database issue warning messages during PL/SQL compilation, you set the initialization parameter PLSQL_WARNINGS. You can enable and disable entire categories of warnings (ALL, SEVERE, INFORMATIONAL, PERFORMANCE), enable and disable specific message numbers, and make the database treat certain warnings as compilation errors so that those conditions must be corrected. This parameter can be set at the system level or the session level. You can also set it for a single compilation by including it as part of the ALTER PROCEDURE ... COMPILE statement. You might turn on all warnings during development, turn off all warnings when deploying for production, or turn on some warnings when working on a particular subprogram where you are concerned with some aspect, such as unnecessary code or performance. Example 10-15 Controlling the Display of PL/SQL Warnings -- To focus on one aspect ALTER SESSION SET PLSQL_WARNINGS='ENABLE:PERFORMANCE'; -- Recompile with extra checking ALTER PROCEDURE loc_var COMPILE PLSQL_WARNINGS='ENABLE:PERFORMANCE' REUSE SETTINGS; -- To turn off all warnings ALTER SESSION SET PLSQL_WARNINGS='DISABLE:ALL'; -- Display 'severe' warnings, don't want 'performance' warnings, and -- want PLW-06002 warnings to produce errors that halt compilation ALTER SESSION SET PLSQL_WARNINGS='ENABLE:SEVERE', 'DISABLE:PERFORMANCE', 'ERROR:06002'; -- For debugging during development ALTER SESSION SET PLSQL_WARNINGS='ENABLE:ALL'; Warning messages can be issued during compilation of PL/SQL subprograms; anonymous blocks do not produce any warnings. The settings for the PLSQL_WARNINGS parameter are stored along with each compiled subprogram. If you recompile the subprogram with a CREATE OR REPLACE statement, the current settings for that session are used. If you recompile the subprogram with an ALTER ...COMPILE statement, the current session setting might be used, or the original setting that was stored with the subprogram, depending on whether you include the REUSE SETTINGS clause in the statement. For more information, see ALTER FUNCTION, ALTER PACKAGE, andALTER PROCEDURE in Oracle Database SQL Reference. To see any warnings generated during compilation, you use the SQL*Plus SHOW ERRORS command or query the USER_ERRORS data dictionary view. PL/SQL warning messages all use the prefix PLW.
Using the DBMS_WARNING Package If you are writing a development environment that compiles PL/SQL subprograms, you can control PL/SQL warning messages by calling subprograms in the DBMS_WARNING package. You might also use this package when compiling a complex application, made up of several nested SQL*Plus scripts, where different warning settings apply to different subprograms. You can save the current state of thePLSQL_WARNINGS parameter with one call to the package, change the parameter to compile a particular set of subprograms, then restore the original parameter value. For example, Example 10-16 is a procedure with unnecessary code that could be removed. It could represent a mistake, or it could be intentionally hidden by a debug flag, so you might or might not want a warning message for it. Example 10-16 Using the DBMS_WARNING Package to Display Warnings -- When warnings disabled, the following procedure compiles with no warnings CREATE OR REPLACE PROCEDURE unreachable_code AS x CONSTANT BOOLEAN := TRUE; BEGIN IF x THEN DBMS_OUTPUT.PUT_LINE('TRUE'); ELSE DBMS_OUTPUT.PUT_LINE('FALSE'); END IF; END unreachable_code; / -- enable all warning messages for this session CALL DBMS_WARNING.set_warning_setting_string('ENABLE:ALL' ,'SESSION'); -- Check the current warning setting SELECT DBMS_WARNING.get_warning_setting_string() FROM DUAL; -- Recompile the procedure and a warning about unreachable code displays ALTER PROCEDURE unreachable_code COMPILE; SHOW ERRORS; In Example 10-16, you could have used the following ALTER PROCEDURE without the call toDBMS_WARNINGS.set_warning_setting_string: ALTER PROCEDURE unreachable_code COMPILE PLSQL_WARNINGS = 'ENABLE:ALL' REUSE SETTINGS;
Posted 19th April 2011 by Prafull Dangore 0
Add a comment 76.
77. APR
19
What are the different types of pragma and where can we use them?
=========================================== ============================= What are the different types of pragma and where can we use them? Pragma is a keyword in Oracle PL/SQL that is used to provide an instruction to the compiler. The syntax for pragmas are as follows PRAMA The instruction is a statement that provides some instructions to the compiler. Pragmas are defined in the declarative section in PL/SQL. The following pragmas are available: AUTONOMOUS_TRANSACTION: Prior to Oracle 8.1, each Oracle session in PL/SQL could have at most one active transaction at a given time. In other words, changes were all or nothing. Oracle8i PL/SQL addresses that short comings with the AUTONOMOUS_TRANSACTION pragma. This pragma can perform an autonomous transaction within a PL/SQL block between a BEGIN and END statement without affecting the entire transaction. For instance, if rollback or commit needs to take place within the block without effective the transaction outside the block, this type of pragma can be used. EXCEPTION_INIT: The most commonly used pragma, this is used to bind a user defined exception to a particular error number. For example: Declare I_GIVE_UP EXCEPTION; PRAGMA EXCEPTION_INIT(I_give_up, -20000); BEGIN .. EXCEPTION WHEN I_GIVE_UP do something.. END; RESTRICT_REFERENCES: Defines the purity level of a packaged program. This is not required starting with Oracle8i. Prior to Oracle8i if you were to invoke a function within a package specification from a SQL statement, you would have to provide a RESTRICT_REFERENCE directive to the PL/SQL engine for that function.
Associating a PL/SQL Exception with a Number: Pragma EXCEPTION_INIT To handle error conditions (typically ORA- messages) that have no predefined name, you must use the OTHERS handler or the pragmaEXCEPTION_INIT. A pragma is a compiler directive that is processed at compile time, not at run time. 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. You code the pragma EXCEPTION_INIT in the declarative part of a PL/SQL block, subprogram, or package using the syntax
PRAGMA EXCEPTION_INIT(exception_name, -Oracle_error_number); where exception_name is the name of a previously declared exception and the number is a negative value corresponding to an ORA-error number. The pragma must appear somewhere after the exception declaration in the same declarative section, as shown inExample 10-4. Example 10-4 Using PRAGMA EXCEPTION_INIT DECLARE deadlock_detected EXCEPTION; PRAGMA EXCEPTION_INIT(deadlock_detected, -60); BEGIN NULL; -- Some operation that causes an ORA-00060 error EXCEPTION WHEN deadlock_detected THEN NULL; -- handle the error END; / Defining Your Own Error Messages: Procedure RAISE_APPLICATION_ERROR The procedure RAISE_APPLICATION_ERROR lets you issue user-defined ORA- error messages from stored subprograms. That way, you can report errors to your application and avoid returning unhandled exceptions. To call RAISE_APPLICATION_ERROR, use the syntax raise_application_error( error_number, message[, {TRUE | FALSE}]); where error_number is a negative integer in the range -20000 .. -20999 and message is a character string up to 2048 bytes long. If the optional third parameter is TRUE, the error is placed on the stack of previous errors. If the parameter is FALSE (the default), the error replaces all previous errors. RAISE_APPLICATION_ERROR is part of package DBMS_STANDARD, and as with package STANDARD, you do not need to qualify references to it. An application can call raise_application_error only from an executing stored subprogram (or method). When called,raise_application_error ends the subprogram and returns a user-defined error number and message to the application. The error number and message can be trapped like any Oracle error. In Example 10-5, you call raise_application_error if an error condition of your choosing happens (in this case, if the current schema owns less than 1000 tables): Example 10-5 Raising an Application Error With raise_application_error DECLARE num_tables NUMBER; BEGIN SELECT COUNT(*) INTO num_tables FROM USER_TABLES; IF num_tables < 1000 THEN /* Issue your own error code (ORA-20101) with your own error message. Note that you do not need to qualify raise_application_error with DBMS_STANDARD */ raise_application_error(-20101, 'Expecting at least 1000 tables'); ELSE NULL; -- Do the rest of the processing (for the non-error case). END IF; END; / The calling application gets a PL/SQL exception, which it can process using the error-reporting functions SQLCODE and SQLERRM in anOTHERS handler. Also, it can use the pragma EXCEPTION_INIT to
map specific error numbers returned by raise_application_error to exceptions of its own, as the following Pro*C example shows: EXEC SQL EXECUTE /* Execute embedded PL/SQL block using host variables v_emp_id and v_amount, which were assigned values in the host environment. */ DECLARE null_salary EXCEPTION; /* Map error number returned by raise_application_error to user-defined exception. */ PRAGMA EXCEPTION_INIT(null_salary, -20101); BEGIN raise_salary(:v_emp_id, :v_amount); EXCEPTION WHEN null_salary THEN INSERT INTO emp_audit VALUES (:v_emp_id, ...); END; END-EXEC; This technique allows the calling application to handle error conditions in specific exception handlers. Redeclaring Predefined Exceptions Remember, PL/SQL declares predefined exceptions globally in package STANDARD, so you need not declare them yourself. Redeclaring predefined exceptions is error prone because your local declaration overrides the global declaration. For example, if you declare an exception named invalid_number and then PL/SQL raises the predefined exception INVALID_NUMBER internally, a handler written forINVALID_NUMBER will not catch the internal exception. In such cases, you must use dot notation to specify the predefined exception, as follows: EXCEPTION WHEN invalid_number OR STANDARD.INVALID_NUMBER THEN -- handle the error END;
=========================================== ============================= Posted 19th April 2011 by Prafull Dangore 0
Add a comment
78. APR
13
A Comparison of Oracle's DATE and TIMESTAMP Datatypes ==============================================================
A Comparison of Oracle's DATE and TIMESTAMP Datatypes Oracle date and time data types, calculations around these data types, and just plain who to use them often plauge Oracle users more than they should. Here is an article I wrote a while back but still holds some good insight (I think) to using these data types. Hope you agree. If you want to store date and time information in Oracle, you really only have two different options for the column's datatype. Lets take a quick look at these two datatypes and what they offer. DATE datatype This is the datatype that we are all too familiar with when we think about representing date and time values. It has the ability to store the month, day, year, century, hours, minutes, and seconds. It is typically good for representing data for when something has happened or should happen in the future. The problem with the DATE datatype is its' granularity when trying to determine a time interval between two events when the events happen within a second of each other. This issue is solved later in this article when we discuss the TIMESTAMP datatype. In order to represent the date stored in a more readable format, the TO_CHAR function has traditionally been wrapped around the date as in Listing A. LISTING A: Formatting a date SQL> SELECT TO_CHAR(date1,'MM/DD/YYYY HH24:MI:SS') "Date" FROM date_table; Date --------------------------06/20/2003 16:55:14 06/26/2003 11:16:36 About the only trouble I have seen people get into when using the DATE datatype is doing arithmetic on the column in order to figure out the number of years, weeks, days, hours, and seconds between two dates. What needs to be realized when doing the calculation is that when you do subtraction between dates, you get a number that represents the number of days. You should then multiply that number by the number of seconds in a day (86400) before you continue with calculations to determine the interval with which you are concerned. Check out Listing B for my solution on how to extract the individual time intervals for a subtraction of two dates. I am aware that the fractions could be reduced but I wanted to show all the numbers to emphasize the calculation. LISTING B: Determine the interval breakdown between two dates for a DATE datatype 1 SELECT TO_CHAR(date1,'MMDDYYYY:HH24:MI:SS') date1, 2 TO_CHAR(date2,'MMDDYYYY:HH24:MI:SS') date2, 3 trunc(86400*(date2-date1))4 60*(trunc((86400*(date2-date1))/60)) seconds, 5 trunc((86400*(date2-date1))/60)6 60*(trunc(((86400*(date2-date1))/60)/60)) minutes, 7 trunc(((86400*(date2-date1))/60)/60)8 24*(trunc((((86400*(date2-date1))/60)/60)/24)) hours, 9 trunc((((86400*(date2-date1))/60)/60)/24) days, 10 trunc(((((86400*(date2-date1))/60)/60)/24)/7) weeks 11* FROM date_table DATE1 DATE2 SECONDS MINUTES HOURS DAYS WEEKS ----------------- ----------------- ---------- ---------- ---------- ---------- ---------06202003:16:55:14 07082003:11:22:57 43 27 18 17 2 06262003:11:16:36 07082003:11:22:57 21 6 0 12 1
TIMESTAMP datatype One of the main problems with the DATE datatype was its' inability to be granular enough to determine which event might have happened first in relation to another event. Oracle has expanded on the DATE datatype and has given us the TIMESTAMP datatype which stores all the information that the DATE datatype stores, but also includes fractional seconds. If you want to convert a DATE datatype to a TIMESTAMP datatype format, just use the CAST function as I do in Listing C. As you can see, there is a fractional seconds part of '.000000' on the end of this conversion. This is only because when converting from the DATE datatype that does not have the fractional seconds it defaults to zeros and the display is defaulted to the default timestamp format (NLS_TIMESTAMP_FORMAT). If you are moving a DATE datatype column from one table to a TIMESTAMP datatype column of another table, all you need to do is a straight INSERTSELECT FROM and Oracle will do the conversion for you. Look at Listing D for a formatting of the new TIMESTAMP datatype where everything is the same as formatting the DATE datatype as we did in Listing A. Beware while the TO_CHAR function works with both datatypes, the TRUNC function will not work with a datatype of TIMESTAMP. This is a clear indication that the use of TIMESTAMP datatype should explicitly be used for date and times where a difference in time is of utmost importance, such that Oracle won't even let you compare like values. If you wanted to show the fractional seconds within a TIMESTAMP datatype, look at Listing E. In Listing E, we are only showing 3 place holders for the fractional seconds. LISTING C: Convert DATE datatype to TIMESTAMP datatype SQL> SELECT CAST(date1 AS TIMESTAMP) "Date" FROM t; Date ----------------------------------------------------20-JUN-03 04.55.14.000000 PM 26-JUN-03 11.16.36.000000 AM LISTING D: Formatting of the TIMESTAMP datatype 1 SELECT TO_CHAR(time1,'MM/DD/YYYY HH24:MI:SS') "Date" FROM date_table Date ------------------06/20/2003 16:55:14 06/26/2003 11:16:36 LISTING E: Formatting of the TIMESTAMP datatype with fractional seconds 1 SELECT TO_CHAR(time1,'MM/DD/YYYY HH24:MI:SS:FF3') "Date" FROM date_table Date ----------------------06/20/2003 16:55:14:000 06/26/2003 11:16:36:000 Calculating the time difference between two TIMESTAMP datatypesdatatype. Look at what happens when you just do straight subtraction of the columns in Listing F. As you can see, the results are much easier to recognize, 17days, 18hours, 27minutes, and 43seconds for the first row of output. This means no more worries about how many seconds in a day and all those cumbersome calculations. And therefore the calculations for getting the weeks, days, hours, minutes, and seconds becomes a matter of picking out the number by using the SUBSTR function as can be seen in Listing G.
LISTING F: Straight subtraction of two TIMESTAMP datatypes 1 SELECT time1, time2, (time2-time1) 2* FROM date_table TIME1 TIME2 (TIME2-TIME1) ------------------------------ ---------------------------- ---------------------06/20/2003:16:55:14:000000 07/08/2003:11:22:57:000000 +000000017 18:27:43.000000 06/26/2003:11:16:36:000000 07/08/2003:11:22:57:000000 +000000012 00:06:21.000000 LISTING G: Determine the interval breakdown between two dates for a TIMESTAMP datatype 1 SELECT time1, 2 time2, 3 substr((time2-time1),instr((time2-time1),' ')+7,2) seconds, 4 substr((time2-time1),instr((time2-time1),' ')+4,2) minutes, 5 substr((time2-time1),instr((time2-time1),' ')+1,2) hours, 6 trunc(to_number(substr((time2-time1),1,instr(time2-time1,' ')))) days, 7 trunc(to_number(substr((time2-time1),1,instr(time2-time1,' ')))/7) weeks 8* FROM date_table TIME1 TIME2 SECONDS MINUTES HOURS DAYS WEEKS ------------------------- -------------------------- ------- ------- ----- ---- ----06/20/2003:16:55:14:000000 07/08/2003:11:22:57:000000 43 27 18 17 2 06/26/2003:11:16:36:000000 07/08/2003:11:22:57:000000 21 06 00 12 1 System Date and Time In order to get the system date and time returned in a DATE datatype, you can use the SYSDATE function such as : SQL> SELECT SYSDATE FROM DUAL; In order to get the system date and time returned in a TIMESTAMP datatype, you can use the SYSTIMESTAMP function such as: SQL> SELECT SYSTIMESTAMP FROM DUAL; You can set the initialization parameter FIXED_DATE to return a constant value for what is returned from the SYSDATE function. This is a great tool for testing date and time sensitive code. Just beware that this parameter has no effect on the SYSTIMESTAMP function. This can be seen in Listing H. LISTING H: Setting FIXED_DATE and effects on SYSDATE and SYSTIMESTAMP SQL> ALTER SYSTEM SET fixed_date = '2003-01-01-10:00:00'; System altered. SQL> select sysdate from dual; SYSDATE --------01-JAN-03 SQL> select systimestamp from dual; SYSTIMESTAMP --------------------------------------------------------09-JUL-03 11.05.02.519000 AM -06:00 When working with date and time, the options are clear. You have at your disposal the DATE and TIMESTAMP datatypes. Just be aware, while there are similarities, there are also differences that could create havoc if you try to convert to the more powerful TIMESTAMP datatype. Each of the two has strengths in simplicity and granularity. Choose wisely.
=========================================== ======================= Posted 13th April 2011 by Prafull Dangore 0
Add a comment
79. APR
13
Informatica Power Center performance – Concurrent Workflow Execution =========================================================================== Informatica Power Center performance – Concurrent Workflow Execution What is concurrent work flow? A concurrent workflow is a workflow that can run as multiple instances concurrently. What is workflow instance? A workflow instance is a representation of a workflow. How to configure concurrent workflow? 1) Allow concurrent workflows with the same instance name: Configure one workflow instance to run multiple times concurrently. Each instance has the same source, target, and variables parameters. Eg: Create a workflow that reads data from a message queue that determines the source data and targets. You can run the instance multiple times concurrently and pass different connection parameters to the workflow instances from the message queue. 2) Configure unique workflow instances to run concurrently: Define each workflow instance name and configure a workflow parameter file for the instance. You can define different sources, targets, and variables in the parameter file. Eg: Configure workflow instances to run a workflow with different sources and targets. For example, your organization receives sales data from three divisions. You create a workflow that reads the sales data and writes it to the database. You configure three instances of the workflow. Each instance has a different workflow parameter file that defines which sales file to process. You can run all instances of the workflow concurrently. How concurrent workflow Works? A concurrent workflow group’s logical sessions and tasks together, like a sequential workflow, but runs all the tasks at one time. Advantages of Concurrent workflow? This can reduce the load times into the warehouse, taking advantage of hardware platforms’ Symmetric Multi-Processing (SMP) architecture. LOAD SCENARIO: Source table records count: 150,622,276
===========================================================================
Posted 13th April 2011 by Prafull Dangore
0
Add a comment 80.
81. APR
13
Informatica Performance Improvement Tips =========================================================================== Informatica Performance Improvement Tips
We often come across situations where Data Transformation Manager (DTM) takes more time to read from Source or when writing in to a Target. Following standards/guidelines can improve the overall performance. Use Source Qualifier if the Source tables reside in the same schema Make use of Source Qualifer “Filter” Properties if the Source type is Relational. If the subsequent sessions are doing lookup on the same table, use persistent cache in the first session. Data remains in the Cache and available for the subsequent session for usage. Use flags as integer, as the integer comparison is faster than the string comparison. Use tables with lesser number of records as master table for joins. While reading from Flat files, define the appropriate data type instead of reading as String and converting. Have all Ports that are required connected to Subsequent Transformations else check whether we can remove these ports Suppress ORDER BY using the ‘–‘ at the end of the query in Lookup Transformations Minimize the number of Update strategies. Group by simple columns in transformations like Aggregate, Source Qualifier Use Router transformation in place of multiple Filter transformations. Turn off the Verbose Logging while moving the mappings to UAT/Production environment. For large volume of data drop index before loading and recreate indexes after load. For large of volume of records Use Bulk load Increase the commit interval to a higher value large volume of data Set ‘Commit on Target’ in the sessions ===========================================================================
Posted 13th April 2011 by Prafull Dangore 0
Add a comment
82. APR
13
What is Pushdown Optimization and things to consider ================================================================================= What is Pushdown Optimization and things to consider
The process of pushing transformation logic to the source or target database by Informatica Integration service is known as Pushdown Optimization. When a session is configured to run for Pushdown Optimization, the Integration Service translates the transformation logic into SQL queries and sends the SQL queries to the database. The Source or Target Database executes the SQL queries to process the transformations. How does Pushdown Optimization (PO) Works? The Integration Service generates SQL statements when native database driver is used. In case of ODBC drivers, the Integration Service cannot detect the database type and generates ANSI SQL. The Integration Service can usually push more transformation logic to a database if a native driver is used, instead of an ODBC driver. For any SQL Override, Integration service creates a view (PM_*) in the database while executing the session task and drops the view after the task gets complete. Similarly it also create sequences (PM_*) in the database. Database schema (SQ Connection, LKP connection), should have the Create View / Create Sequence Privilege, else the session will fail. Few Benefits in using PO
There is no memory or disk space required to manage the cache in the Informatica server for Aggregator, Lookup, Sorter and Joiner Transformation, as the transformation logic is pushed to database. SQL Generated by Informatica Integration service can be viewed before running the session through Optimizer viewer, making easier to debug. When inserting into Targets, Integration Service do row by row processing using bind variable (only soft parse – only processing time, no parsing time). But In case of Pushdown Optimization, the statement will be executed once. Without Using Pushdown optimization: INSERT INTO EMPLOYEES(ID_EMPLOYEE, EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT, MANAGER_ID,MANAGER_NAME, DEPARTMENT_ID) VALUES (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13) –executes 7012352 times With Using Pushdown optimization INSERT INTO EMPLOYEES(ID_EMPLOYEE, EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT, MANAGER_ID, MANAGER_NAME, DEPARTMENT_ID) SELECT CAST(PM_SJEAIJTJRNWT45X3OO5ZZLJYJRY.NEXTVAL AS NUMBER(15, 2)), EMPLOYEES_SRC.EMPLOYEE_ID, EMPLOYEES_SRC.FIRST_NAME, EMPLOYEES_SRC.LAST_NAME, CAST((EMPLOYEES_SRC.EMAIL || ‘@gmail.com’) AS VARCHAR2(25)), EMPLOYEES_SRC.PHONE_NUMBER, CAST(EMPLOYEES_SRC.HIRE_DATE AS date), EMPLOYEES_SRC.JOB_ID, EMPLOYEES_SRC.SALARY, EMPLOYEES_SRC.COMMISSION_PCT, EMPLOYEES_SRC.MANAGER_ID, NULL, EMPLOYEES_SRC.DEPARTMENT_ID FROM (EMPLOYEES_SRC LEFT OUTER JOIN EMPLOYEES PM_Alkp_emp_mgr_1 ON (PM_Alkp_emp_mgr_1.EMPLOYEE_ID = EMPLOYEES_SRC.MANAGER_ID)) WHERE ((EMPLOYEES_SRC.MANAGER_ID = (SELECT PM_Alkp_emp_mgr_1.EMPLOYEE_ID FROM EMPLOYEES PM_Alkp_emp_mgr_1 WHERE (PM_Alkp_emp_mgr_1.EMPLOYEE_ID = EMPLOYEES_SRC.MANAGER_ID))) OR (0=0)) – executes 1 time Things to note when using PO
There are cases where the Integration Service and Pushdown Optimization can produce different result sets for the same transformation logic. This can happen during data type conversion, handling null values, case sensitivity, sequence generation, and sorting of data. The database and Integration Service produce different output when the following settings and conversions are different: Nulls treated as the highest or lowest value: While sorting the data, the Integration Service can treat null values as lowest, but database treats null values as the highest value in the sort order. SYSDATE built-in variable: Built-in Variable SYSDATE in the Integration Service returns the current date and time for the node running the service process. However, in the database, the SYSDATE returns the current date and time for the machine hosting the database. If the time zone of the machine hosting the database is not the same as the time zone of the machine running the Integration Service process, the results can vary. Date Conversion: The Integration Service converts all dates before pushing transformations to the database and if the format is not supported by the database, the session fails. Logging: When the Integration Service pushes transformation logic to the database, it cannot trace all the events that occur inside the database server. The statistics the Integration Service can trace depend on the type of pushdown optimization. When the Integration Service runs a session configured for full pushdown optimization and an error occurs, the database handles the errors. When the database handles errors, the Integration Service does not write reject rows to the reject file.
=================================================================================
Posted 13th April 2011 by Prafull Dangore 0
Add a comment
83. APR
13
Informatica OPB table which have gives source table and the mappings and folders using an sql query SQL query select OPB_SUBJECT.SUBJ_NAME, OPB_MAPPING.MAPPING_NAME,OPB_SRC.source_name from opb_mapping, opb_subject, opb_src, opb_widget_inst where opb_subject.SUBJ_ID = opb_mapping.SUBJECT_ID and OPB_MAPPING.MAPPING_ID = OPB_WIDGET_INST.MAPPING_ID and OPB_WIDGET_Inst.WIDGET_ID = OPB_SRC.SRC_ID and OPB_widget_inst.widget_type=1; Posted 13th April 2011 by Prafull Dangore 0
Add a comment 84.
85. MAR
28
How to remove/trim special characters in flatfile source field? Consolidated Info Que. How to remove special characters like ## in the below ... Can any one suggest... Prod_Code --#PC97## #PC98## #PC99## #PC125# #PC156# ------#PC767#
#PC766# #PC921# #PC1020 #PC1071 #PC1092 #PC1221 i want to remove that special characters.... i want to load in the target just Prod_Code --PC9 PC98 PC99 PC125 PC156 . Ans: In expression ,use the replacechar function and in that just replace # with null char.
REPLACECHR Availability: Designer Workflow Manager Replaces characters in a string with a single character or no character. REPLACECHR searches the input string for the characters you specify and replaces all occurrences of all characters with the new character you specify.
Syntax REPLACECHR( CaseFlag, InputString, OldCharSet, NewChar )
Argument Required/ Description Optional CaseFlag Required Must be an integer. Determines whether the arguments in this function are case sensitive. You can enter any valid transformation expression. When CaseFlag is a number other than 0, the function is case sensitive. When CaseFlag is a null value or 0, the function is not case sensitive. InputString Required Must be a character string. Passes the string you want to search. You can enter any valid transformation expression. If you pass a numeric value, the function converts it to a character string.
OldCharSet Required
NewChar
Required
If InputString is NULL, REPLACECHR returns NULL. Must be a character string. The characters you want to replace. You can enter one or more characters. You can enter any valid transformation expression. You can also enter a text literal enclosed within single quotation marks, for example, 'abc'. If you pass a numeric value, the function converts it to a character string. If OldCharSet is NULL or empty, REPLACECHR returns InputString. Must be a character string. You can enter one character, an empty string, or NULL. You can enter any valid transformation expression. If NewChar is NULL or empty, REPLACECHR removes all occurrences of all characters inOldCharSet in InputString. If NewChar contains more than one character, REPLACECHR uses the first character to replaceOldCharSet.
Return Value String. Empty string if REPLACECHR removes all characters in InputString. NULL if InputString is NULL. InputString if OldCharSet is NULL or empty.
Examples The following expression removes the double quotes from web log data for each row in the WEBLOG port: REPLACECHR( 0, WEBLOG, '"', NULL )
WEBLOG
RETURN VALUE
"GET /news/index.html HTTP/1.1" GET /news/index.html HTTP/1.1 "GET /companyinfo/index.html HTTP/1.1" GET /companyinfo/index.html HTTP/1.1 GET /companyinfo/index.html HTTP/1.1 NULL
GET /companyinfo/index.html HTTP/1.1 NULL
The following expression removes multiple characters for each row in the WEBLOG port: REPLACECHR ( 1, WEBLOG, ']["', NULL )
WEBLOG
RETURN VALUE
[29/Oct/2001:14:13:50 -0700]
29/Oct/2001:14:13:50 -0700
[31/Oct/2000:19:45:46 -0700] "GET /news/index.html HTTP/1.1"
31/Oct/2000:19:45:46 -0700 GET /news/index.html HTTP/1.1
[01/Nov/2000:10:51:31 -0700] "GET /news/index.html HTTP/1.1"
01/Nov/2000:10:51:31 -0700 GET /news/index.html HTTP/1.1
NULL
NULL
The following expression changes part of the value of the customer code for each row in the CUSTOMER_CODE port: REPLACECHR ( 1, CUSTOMER_CODE, 'A', 'M' )
CUSTOMER_CODE RETURN VALUE ABA abA
MBM abM
BBC
BBC
ACC NULL
MCC NULL
The following expression changes part of the value of the customer code for each row in the CUSTOMER_CODE port: REPLACECHR ( 0, CUSTOMER_CODE, 'A', 'M' )
CUSTOMER_CODE RETURN VALUE ABA abA
MBM MbM
BBC ACC
BBC MCC
The following expression changes part of the value of the customer code for each row in the CUSTOMER_CODE port: REPLACECHR ( 1, CUSTOMER_CODE, 'A', NULL )
CUSTOMER_CODE RETURN VALUE ABA
B
BBC ACC
BBC CC
AAA aaa
aaa
NULL
NULL
[empty string]
The following expression removes multiple numbers for each row in the INPUT port: REPLACECHR ( 1, INPUT, '14', NULL )
INPUT
RETURN VALUE
12345
235
4141 111115
NULL 5
NULL
NULL
When you want to use a single quote (') in either OldCharSet or NewChar, you must use the CHR function. The single quote is the only character that cannot be used inside a string literal. The following expression removes multiple characters, including the single quote, for each row in the INPUT port: REPLACECHR (1, INPUT, CHR(39), NULL )
INPUT
RETURN VALUE
'Tom Smith' 'Laura Jones' Tom Smith Laura Jones Tom's Toms NULL
NULL
Posted 28th March 2011 by Prafull Dangore 0
Add a comment
86. MAR
25
What is Delta data load? -> Consolidated Info A delta load, by definition, is loading incremental changes to the data. When doing a delta load to a fact table, for example, you perform inserts only... appending the change data to the existing table.
Delta checks can be done in a number of ways. Different logics can accomplish this. One way is to check if the record exists or not by doing a lookup on the keys. Then if the Keys don't exist then it should be inserted as new records and if the record exist then compare the Hash value of non key attributes of the table which are candidates for change. If the Hash values are different then they are updated records. (For Hash Values you can use MD5 function in Informatica) If you are keeping History (Full History) for the table then it adds a little more complexity in the sense that you have to update the old record and insert a new record for changed data. This can also be done with 2 separate tables with one as current version and another as History version. Posted 25th March 2011 by Prafull Dangore 0
Add a comment
87. MAR
25
Define: Surrogate Key -> Consolidated Info
Definition:
Surrogate key is a substitution for the natural primary key in Data Warehousing. It is just a unique identifier or number for each row that can be used for the primary key to the table. The only requirement for a surrogate primary key is that it is unique for each row in the table. It is useful because the natural primary key can change and this makes updates more difficult. Surrogated keys are always integer or numeric.
Scenario overview and details To illustrate this example, we will use two made up sources of information to provide data about customers dimension. Each extract contains customer records with a business key (natural key) assigned to it. In order to isolate the data warehouse from source systems, we will introduce a technical surrogate key instead of re-using the source system's natural (business) key. A unique and common surrogate key is a one-field numeric key which is shorter, easier to maintain and understand, and independent from changes in source system than using a business key. Also, if a surrogate key generation process is implemented correctly, adding a new source system to the data warehouse processing will not require major efforts. Surrogate key generation mechanism may vary depending on the requirements, however the inputs and outputs usually fit into the design shown below: Inputs: - an input respresented by an extract from the source system - datawarehouse table reference for identifying the existing records - maximum key lookup Outputs: - output table or file with newly assigned surrogate keys - new maximum key - updated reference table with new records Posted 25th March 2011 by Prafull Dangore 0
Add a comment 88.
Loading Send feedback
View more...
Comments