What is a CO-RELATED SUBQUERY A CO-RELATED SUBQUERY is one that has a correlation name as table or view designator in the FROM clause of the outer query and the same correlation name as a qualifier of a search condition in the WHERE clause of the subquery. 2. eg 3. SELECT field1 from table1 X 4. WHERE field2>(select avg(field2) from table1 Y 5. where field1=X.field1); (The subquery in a correlated subquery is revaluated for every row of the table or view named in the outer query.) What are various joins used while writing SUBQUERIES Self join-Its a join foreign key of a table references the same table. Outer Join–Its a join condition used where One can query all the rows of one of the tables in the join condition even though they don’t satisfy the join condition. Equi-join–Its a join condition that retrieves rows from one or more tables in which one or more columns in one table are equal to one or more columns in the second table. What are various constraints used in SQL NULL, NOT NULL, CHECK, DEFAULT What are different Oracle database objects TABLES, VIEWS, INDEXES, SYNONYMS, SEQUENCES, TABLESPACES etc What is difference between Rename and Alias Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column which do not exist once the SQL statement is executed. What is a view A view is stored procedure based on one or more tables, its a virtual table. What are various privileges that a user can grant to another user SELECT, CONNECT, RESOURCE What is difference between UNIQUE and PRIMARY KEY constraints A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys. The columns that compose PK are automatically define NOT NULL, whereas a column that compose a UNIQUE is not automatically defined to be mandatory must also specify the column is NOT NULL. Can a primary key contain more than one columns
Yes How you will avoid duplicating records in a query By using DISTINCT What is difference between SQL and SQL*PLUS SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. Its a command line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQL is a language used to query the relational database(DML,DCL,DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and PL/SQL. Which datatype is used for storing graphics and images LONG RAW data type is used for storing BLOB’s (binary large objects). How will you delete duplicating rows from a base table DELETE FROM table_name A WHERE rowid>(SELECT min(rowid) from table_name B where B.table_no=A.table_no); CREATE TABLE new_table AS SELECT DISTINCT * FROM old_table; DROP old_table RENAME new_table TO old_table DELETE FROM table_name A WHERE rowid NOT IN (SELECT MAX(ROWID) FROM table_name GROUP BY column_name) What is difference between SUBSTR and INSTR SUBSTR returns a specified portion of a string eg SUBSTR(’BCDEF’,4) output BCDE INSTR provides character position in which a pattern is found in a string. eg INSTR(’ABC-DC-F’,'-’,2) output 7 (2nd occurence of ‘-’ )
What does Opening a cursor do ? - It executes the query and identifies the Result set What does Fetching a cursor do ? - It reads the Result Set row by row. What does Closing a cursor do ? - It clears the private SQL area and de-allocates the memory. What are Cursor Variables ? - Also called REF CURSORS.
- They are not tied to a single SQL. They point to any SQL area dynamically. - Advantage is : You can declare variables at Client side and open them Server side. You can thus centralize data retrieval. Why use Cursor Variables? - You can pass cursor RESULT SETS between PL/SQL stored programs and clients. What are SQLCODE and SQLERRM ? - Oracle Error code and detailed error message - They are actually functions with no arguments, that can be used only in procedural statements ( not SQL) What are Pseudocolumns ? - They are not actual columns. They are like Functions without arguments. - They typically give a different value for each row. - Examples: ROWNUM, NEXTVAL, ROWID, VERSION_STARTTIME Why use Truncate over Delete while deleting all rows ? - Truncate is efficient. Triggers are not fired. - It deallocates space (Unless REUSE STORAGE is given). What is a ROWID composed of ? - It's a hexadecimal string representing the address of a row. Prior to Oracle 8, it's a restricted rowid comprising block.row.file. Extended rowid ( the default on higher releases) comprises data object number as well ( comprising the segment number ). What is the use of a ROWID ? - Retrieve data faster with ROWID. - Shows you the physical arrangement of rows in the table. - Also unique identifier for each row. Can rows from two different tables have the same ROWID? - Possible, if they are in a Cluster What is ROWNUM and ROW_NUMBER ? - ROWNUM is a pseudocolumn which is the number assigned to each row retrieved.
- ROW_NUMBER is an analytic function which does something similar, but has all the capabilities of PARTITION BY and ORDER BY clauses.. What is an inline view? - It's not a schema object - It's a subquery in the FROM clause with an alias that can be used as a view within the SQL statement. What are Nested and Correlated subqueries ? - The subquery used in WHERE clause is a nested subquery. - If this subquery refers to any column in the parent statement, it becomes a correlated subquery. How do you retrieve a dropped table in 10g? - FLASHBACK table to BEFORE DROP What are PSPs? - PL/SQL Server Pages. Web pages developed in PL/SQL What is an index-organized table? - The physical arrangement of rows of this table changes with the indexed column. - It's. in-short, a table stored like an index itself. What is an implicit cursor? - Oracle opens an implicit cursor to process each SQL statement not associated with an explicit cursor. Name a few implicit cursor attributes. - %FOUND, %ROWCOUNT, %NOTFOUND, %ISOPEN, %BULK_ROWCOUNT, %BULK_EXCEPTIONS How to fill a refcursor with dataset in C#.i want to pass a dataset as parameter and fill a refcursor with the same dataset. Latest Answer: you need to use ODP.Net connector.In OracleCommand object add OracleParameter object with following propertiesOracleDbType = OracleDbType.RefCursor;Direction= ParameterDirection.Output;give the name of your stored procedures's refcursor parameter ... what is the maximum size of the message that we can give in dbms_output.putline();
The maximum output is determined by the size you specified in dbms_output.enable(). Here is an Error when i tried to give too many characters in Dbms_Output.put_lineORU10028:Search results: The following seemingly harmless statement produces an ORU-10028: line length overflow, limit of 255 bytes per line error: This is because dbms_output.put_line ... Is the order in which the conditions are given in the 'WHERE' clause are important? Mean I heard from Oracle 8i onwards the order of where clause condition does not matter which oracle creates the explain plan...and execute..Is it true? Can you add not null column to a table already containing data ? Yes But we have to Specify a Default value for the column ... What is flash back query and trip stop Flahsback is used to take your database at old state like a system restore in windows. No DDL and DML is allowed when database is in flashback condition. user should have execute permission on dbms_flashback package for example: at 1030 am from scott user : delete from emp; commit; at 1040 am I want all my data from emp table then ? declare cursor c1 is select * from emp; emp_cur emp%rowtype; begin dbms_flashback.enable_at_time(sysdate - 15/1440); open c1; dbms_flashback.disable; loop fetch c1 into emp_cur; exit when c1%notfound; insert into emp values(emp_cur.empno, emp_cur.ename, emp_cur.job, emp_cur.mgr,emp_cur.hiredate, emp_cur.sal, emp_cur.comm, emp_cur.deptno); end loop; commit; end; /
select * from emp; Through flash back queries you can get the data which has been deleted permanently. Different types of methods are there : Use the following links to get the complete information :http://download.oracle.com/docs/cd/B14117_01/appdev.101/b10795/adfns_fl.htm ... Write a PL/SQL fuction named say TRUN, which does the same work as the oracle predefined function "TRUNCATE". Latest Answer: It will truncate/delete all the rows in the table emp very fast as compared of delete command, but the table must have no Foriegn keyMr. Ajaz Ahmad Kumar ... what is the rollforward in pl/sql Roll forward refers to the process Oracle goes through to apply changes contained in the redo log files (both online and archive). The database clock (as measured by the system change number) is moved forward within the blocks of the datafile that are changed within the redo log vectors. Roll forward occurs during database, tablespace or datafile recovery and during crash recovery. Rollback is the process of undoing uncommitted database transactions. The blocks copied to the rollback segments during transactions as a copy of the block for other transaction to read. When the instance aborts, the undo information in the redo log files must be applied to the database during the roll forward process of recovery. Therefore, during recovery, the database must roll forward and roll back. Procedure in package perfomes fastly over normal procedure, Explain. All the database objects defined inside a package gets loaded in memory for first and only call to database from application, thus executing procedures in packages requires less communication time from database thus faster. The procedures inside a package using other private procedures does not require to communicate from database again, it is already in the memory.....thus executing procedures from packages is faster. In case of stand alone procedures, each procedures or d/b objects requires one call to database to be loaded in memory and then executed from application, the number of calls to database makes the execution slower. What is the purpose of Ref Cursor and OUT Parameter in PLSQL Function? Give Examples for each? A function can return one value by return statement itself. Both are used to return more than one value in the function. As long as we are executing function same as procedure (i.e. not from any select statement or DML), out parameter is sufficient to return more than one value from function. Example : Create or replace function func1 (id1 IN , id2 OUT , id3 OUT , id4 OUT , id5 OUT ,
id6 OUT , ..... ) return AS BEGIN --body of procedure END func1; Calling function from any block BEGIN ..... var1= func1(var2,var3,var4,var5,var6,var7,......); .... END; ---------------But when we need to call the function from any select statement or DML, we cant write OUT or IN OUT parameter in function, thus we can take the help of ref cursor to return more than one values without using out parameters. Or without using OUT parameter, we can return more than one value from function normally (function not called from select , DML). Also, definition of ref cursor can be decided at run time. Example of ref cursor: DECLARE A NUMBER := 10; B NUMBER ; C NUMBER ; D NUMBER ; FUNCTION TEST_FUN (A IN NUMBER, B OUT NUMBER, C IN OUT NUMBER) RETURN NUMBER IS D NUMBER; BEGIN B := A; C := B + A; D := A + B + C; RETURN (D); END ; BEGIN D := TEST_FUN(A,B,C); DBMS_OUTPUT.PUT_LINE(' A =' || A); DBMS_OUTPUT.PUT_LINE(' B =' || B); DBMS_OUTPUT.PUT_LINE(' C =' || C); DBMS_OUTPUT.PUT_LINE(' D =' || D); END; Using REF CURSOR we can return objects as return type. Here is example DECLARE TYPE EMP_REFCUR IS REF CURSOR; EMP_CURVAR EMP_REFCUR; TYPE EMP_REC IS RECORD ( V_EMPNO EMP.EMPNO%TYPE, V_ENAME EMP.ENAME%TYPE,
V_JOB EMP.JOB%TYPE, V_SAL EMP.SAL%TYPE ); EMP_RECVAR EMP_REC; FUNCTION TEST_FUN (V_EMPNO IN EMP.EMPNO%TYPE) RETURN EMP_REFCUR IS BEGIN OPEN EMP_CURVAR FOR SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE EMPNO = V_EMPNO; RETURN(EMP_CURVAR); END ; BEGIN EMP_CURVAR := TEST_FUN(7369); FETCH EMP_CURVAR INTO EMP_RECVAR; DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME IS ' || EMP_RECVAR.V_ENAME); DBMS_OUTPUT.PUT_LINE('EMPLOYEE DESIGNATION IS ' || EMP_RECVAR.V_JOB); DBMS_OUTPUT.PUT_LINE('EMPLOYEE SALARY IS ' || EMP_RECVAR.V_SAL); END; What are Return Statement and OUT Parameter in PLSQL Function? Function must have return statement by which it returns one value. Though we can use out parameter in function(function not getting called from select statement or DML), it is not good programming practice to write OUT and IN OUT in function. In case we wanted to return values using OUT parameters, always use procedures. In case we wanted to return more than one value from function, use of ref cursor is preferred solution not OUT parameters.
What is Raise_application_error ? Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an user_defined error messages from stored sub-program or database trigger. Raise_application_error (error_number,error_messages); where error_number is between -20000 to -20999.. Latest Answer : You can use this procedure to issue user-defined error messages from stored subprograms.You can report errors to your application and avoid returning unhandled exceptions.Syntax: raise_application_error (error_number,message[, {TRUE | FALSE}]); ... Where the Pre_defined_exceptions are stored ? In the standard package. Procedures, Functions & Packages ; Predefined exceptions are globally declared in standard package What is Overloading of procedures ?
The Same procedure name is repeated with parameters of different datatypes and parameters in different positions, varying number of parameters is called overloading of 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. 30 we can declare global variables in the package Advantages Modularity Easier application design Hiding information Added functionality Better performance Overloading
What are two parts of package ? 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 Latest Answer : A package usually has a specification and a body, stored separately in the database.The specification is the interface to your applications. It declares the types, variables, constants, exceptions, cursors, and subprograms available for use. The package ... 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. Ref cursors are used when you want cursor to hold any no. of columns in the row.
If you are not sure about row type at complile time you use ref cursors. Sys_ref_cursors used when you want cursors to be passed from one procedures to another procedures or functions. 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.
a. PACKAGE NAME.PROCEDURE NAME (parameters); variable := PACKAGE NAME.FUNCTION NAME (arguments); b. BEGIN PACKAGE NAME.PROCEDURE NAME (parameters) variable := PACKAGE NAME.FUNCTION NAME(arguments); END; END EXEC;
c. EXECUTE PACKAGE NAME.PROCEDURE VARIABLE g_salary NUMBER EXECUTE :g_salary := get_sal(117) Name the tables where characteristics of Package, procedure and functions are stored ? User_objects, User_Source and User_error. USER_OBJECTS, ALL_OBJECTS, DBA_OBJECTS b) USER_SOURCE, ALL_SOURCE, DBA_SOURCE c) USER_DEPENCENCIES d) USER_ERRORS, ALL_ERRORS, DBA_ERRORS What is the output of the following pl/sql block ? declare v_empno emp.empno%type; begin select empno into v_empno from emp where empno = 10;exception when others then dbms_output.put_line ( 'no data found'); when no_data_found then dbms_output.put_line ( 'ther is no data found '); end; when others then *ERROR at line 6:ORA-06550: line 6, column 2:PLS-00370: OTHERS handler must be last among the exception handlers of a blockORA-06550: line 0, column 0:PL/SQL: Compilation unit analysis 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. We have a trigger on data base.in the trigger body we have created a body using dbms_output.put_line(********) We have a trigger on data base.in the trigger body we have created a body using dbms_output.put_line(********) ;this should be firedwhen ever trigger executed;
TRUE ... displays the messge from dbms_output.put_line 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 % 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. 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 differenttable or views Latest Answer : %ROWTYPE is used when you need to work with complete record.TYPE RECORD is used to create your own data type with specificed number of values to hold.Suppose If a table has 20 columns and you need to work with only seven columns . If I use %ROWTYPE, ... % 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. What is a cursor ? Why Cursor is required ? Cursor is a named private SQL area from where information can be accessed. Cursors are required to process rows individually for queries returning multiple rows.
Latest Answer : Oracle uses work areas called private SQL area to Execute Sql statements and store information. A cursor is a mechanism by which we can assign name to that private sql area , there by access information stored in it.In Pl/Sql ... cursor retrive data from a table. it can be done in two level 1 %type it retrive data from a particular row 2 %rowtype it retrive data from a full table Cursor is a named private SQL area also called as context area from where information can be accessed. Cursors are required to process rows individually for queries returning multiple rows. there are three types of cursors 1. Static Cursor * Implicit Cursor * Explicit Cursor 2. Dynamic Cursor 3. Reference Cursor IMPLICIT ----------(1) Called as SQL. (2) Never user CURSOR keyword explicitly (3) Memory allocation and program controll will done automatically (4) Returns or updates or deletes only one record. (5) Attributes : SQL%FOUND, SQL%NOTFOUND EXPLICIT ----------(1) called as cursors (2) Uses CURSOR keyword explicitly (3) Memory allocation and program control thru the cursor written. (4) Returns or updates or deletes multiple records. (5) Attributes : SQL%FOUND, SQL%NOTFOUND, %ISOPEN, %ROWCOUNT Explain the two type of Cursors ? There are two types of cursors, Implicit Cursor and Explicit Cursor.PL/SQL uses Implicit Cursors for queries.User defined cursors are called Explicit Cursors. They can be declared and Latest Answer : Cursors are of two types1. Implicit Cursors: - Whenever we execute sql statements oracle server assigns a work area called private sql area to store precessed infomation. The most recently used work are can be accessed using SQL%. In implicit cursors ...
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. There are two ways of processing a cursor output. These mainly depend on the type of cursor used. Cursors can be 1) Static : Declared in declarations section with a definate command 2) Dynamic : Usually passed a string, which is formulated in program based on various conditions. If the cursor is dynamic, it needs to be processed thro open cursor, fetch into, loop and end loop. This is because such cursors need to be opened into a ref cursor with "open cursor" command. If the cursor is static, it can be processed thro a cursored for loop or by the method mentioned above. Cursored for loop takes the pain to open and close the cursor automatically. 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. %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 Latest Answer : %FOUND :- Returns True if successful fecth has been executed. Returns false if no rows returned ...
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 implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values from active set into fields in the record and closeswhen all the records have been processed. Latest Answer : Cursor for loop implicitly declares a loop index as %rowtype. It uses result of query to determine dynamically no of times the loop is to be repeated. It performs open, fectch , close operations implicitly. ... What will happen after commit statement ? Cursor C1 is Select empno, ename from emp; Begin open C1;
loop
Fetch C1 into eno.ename; Exit When C1 %notfound;----commit; end loop; end; The cursor having query as SELECT .... FOR UPDATE gets closed after COMMIT/ROLLBACK. The cursor having query as SELECT.... does not get closed even after COMMIT/ROLLBACK.
The cursor having query will get closed, because once the for update clause is fired it locks all the rows which is been modified and once it encounters a commit/rollback it automatically comes out of that session, and will be processing a fresh loop altogether.
Explain the usage of WHERE CURRENT OF clause in cursors ? WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row fetched from a cursor. Database Triggers
Latest Answer : When referencing the current row from an explicit cursor, use the WHERE CURRENT OF clause. This allows you to apply updates and deletes to the row currently being addressed, without the need to explicitly reference the ROWID. You must include the FOR ... What are two parts of package ? 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 Latest Answer : A package usually has a specification and a body, stored separately in the database.The specification is the interface to your applications. It declares the types, variables, constants, exceptions, cursors, and subprograms available for use. The package ... SQL General Interview Questions ... • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • •
What are the different types of joins? Explain normalization with examples. What cursor type do you use to retrieve multiple recordsets? Diffrence between a "where" clause and a "having" clause What is the difference between "procedure" and "function"? How will you copy the structure of a table without copying the data? How to find out the database name from SQL*PLUS command prompt? Tadeoffs with having indexes Talk about "Exception Handling" in PL/SQL? What is the diference between "NULL in C" and "NULL in Oracle?" What is Pro*C? What is OCI? Give some examples of Analytical functions. What is the difference between "translate" and "replace"? What is DYNAMIC SQL method 4? How to remove duplicate records from a table? What is the use of ANALYZing the tables? How to run SQL script from a Unix Shell? What is a "transaction"? Why are they necessary? Explain Normalizationa dn Denormalization with examples. When do you get contraint violtaion? What are the types of constraints? How to convert RAW datatype into TEXT? Difference - Primary Key and Aggregate Key How functional dependency is related to database table design? What is a "trigger"? Why can a "group by" or "order by" clause be expensive to process? What are "HINTS"? What is "index covering" of a query? What is a VIEW? How to get script for a view? What are the Large object types suported by Oracle? What is SQL*Loader? Difference between "VARCHAR" and "VARCHAR2" datatypes. What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table. Difference between "ORACLE" and "MICROSOFT ACCESS" databases. How to create a database link ?
PL/SQL interview questions... • • • • • • • • • • • • • • • • • •
Normalize many to many relationships Difference - Equijoin and union What is TEMP table space in Oracle, what is rollback segment How do we find row chaining? Pattern matching operators Features in oracle 9i and 10g Why truncating table is faster than delete copy commit syntax Convert Zulu time zone to US Eastern time zone Difference - union and union all Difference - Group by, Order by clause Which Ranking functions are available? Difference - Decode, NVL, NVL2 Tradeoffs of using partitioned tables How can we call stored procedure in SQL query What are the restrictions on calling PL/SQL from SQL Why EXISTS is preferable to distinct Give 2 examples of avoiding unnecessary parsing.
Explain the usage of WHERE CURRENT OF clause in cursors ? WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row fetched from a cursor. Database Triggers 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 FROM table_name WHERE CURRENT OF cursor_name; 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 ... ; job_rec fall_jobs_cur %ROWTYPE;BEGIN OPEN fall_jobs_cur; LOOP FETCH fall_jobs_cur INTO job_rec; IF fall_jobs_cur%NOTFOUND THEN EXIT; ELSIF job_rec.do_it_yourself_flag = 'YOUCANDOIT' THEN UPDATE winterize SET responsible = 'STEVEN' WHERE CURRENT OF fall_jobs_cur; COMMIT; EXIT; END IF; END LOOP; CLOSE fall_jobs_cur;END;
Write the order of precedence for validation of a column in a table ? I. II.
done using Database triggers. ii. done using Integarity Constraints. I & ii. Exception
Latest Answer : create table a ( b number, c number check (c >100) );create or replace trigger t1 before insert on a begindbms_output.put_line('this is before insert trigger'); end;create or replace trigger t2after insert on a begindbms_output.put_line('this ... Based on what conditions can we decide whether to use a table or a view or a materialized view ? Latest Answer : 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 ... What is a database trigger ? Name some usages of database trigger ?
Database trigger is stored PL/SQL program unit associated with a specific database table. Usages are Audit data modifications, Log events transparently, Enforce complex business rules Derive column values automatically, Implement complex security authorizations. Maintain replicate tables. A database trigger is a named pl/sql block associated with a table and fires automatically when an event occurs or something happens. Data auditing , Implementing complex business rules, security are main uses of database triggers. How many types of database triggers can be specified on a table ? What are they ? Insert
Update
Before Row After Row
Delete
o.k.
o.k.
o.k.
Before Statement After Statement
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. --There are five types of database triggers 1. 2. 3. 4. 5.
Row Level Trigger Statement Level Trigger Instead of Trigger Schema Trigger Database Trigger
Out of these five types of triggers Only two are used for the table purpose, i.e. two row level trigger and statement level triggers are used for insert, update or/and delete operation on table
A trigger may be a 1. DML Trigger on tables 2. Instead of triggers on views 3. System triggers on database or schemaBased on the way it executes statements triggers are of two types
1. Statement leve trigger 2. Row level triggerA trigger fires ...
Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger ? Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger ? Why ? It is not possible. As triggers are defined for each table, if you use COMMIT of in a trigger, it affects logical transaction processing.
ROLLBACK
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 Latest Answer : OLD and NEW are two virtual tables available during database trigger execution.UPDATE statement has access to both old and new values.INSERT statement has access only to new values. Old values are NULL for insert statement.DELETE ... 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.
What happens if a procedure that updates a column of table X is called in a database trigger of the What happens if a procedure that updates a column of table X is called in a database trigger of the same table ? Mutation of table occurs. 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.
Write the order of precedence for validation of a column in a table ?
I. II.
done using Database triggers. ii. done using Integarity Constraints.
III. IV.
I & ii. Exception
create table a ( b number, c number check (c >100) ); create or replace trigger t1 before insert on a begin dbms_output.put_line('this is before insert trigger'); end; create or replace trigger t2 after insert on a begin dbms_output.put_line('this is after insert trigger'); end; insert into a values (1,99); / this is before insert trigger insert into a values (1,99) * ERROR at line 1: ORA-02290: check constraint (XXINV.SYS_C00106711) violated insert into a values (1,199); / this is before insert trigger this is after insert trigger 1 row created. So, if it is before insert trigger then the trigger will run first before the constriants in the table. if it is after insert trigger , contraints are checked first and then trigger will run.
What are the return values of functions SQLCODE and SQLERRM ?
SQLCODE returns the latest code of the error that has occurred. SQLERRM returns the relevant error message of the SQLCODE. Latest Answer : • SQLCODE: Returns the numeric value for the error code• SQLERRM: Returns the message associated with the error numberSQLCODE Value Description ... Answer Question
Subscribe
What is Data Concarency and Consistency? Data Concarency => Means that many users can access data at the same time. Data Consistency => Means that each user sees a consistent view of the data, including visible changes made by the user's own transactions and transactions of other users. 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
What is the output of the following pl/sql block ?declare v_empno emp.empno%type;begin select empno What is the output of the following pl/sql block ?declare v_empno emp.empno%type;begin select empno into v_empno from emp where empno = 10;exception when others then dbms_output.put_line ( 'no data found'); when no_data_found then dbms_output.put_line ( 'ther is no data found ');end; when others then *ERROR at line 6:ORA-06550: line 6, column 2:PLS-00370: OTHERS handler must be last among the exception handlers of a blockORA-06550: line 0, column 0:PL/SQL: Compilation unit analysis
always when others exception should be the last exception handling in sequence. You have compiled some PL/SQL packages in your schema, and found aome errors in one procedure.how do you find which procedure produced the error? how do you find which section of the code produced the error and look at? USER_ERRORS
It give list of all procedures/ package/ functions/ types wherever error occurs Along with line no and what is the error. What is PL/SQL table ? Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary key.
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. What is the order of execution if there is a statement level and row level trigger on a same table? Latest Answer : The correct order is as below. Trigger firing sequence: 1) Before statement level triggers, if present 2) For each row a) Before row level triggers, if present b) After row level triggers, if present 3) Actual Statement 4) After statement level ... Read Answers (5) | Asked by : joseph Answer Question
Subscribe
In PL/SQL if we write select statement with INTO clause it may return two exceptions NO_DATA_FOUND or In PL/SQL if we write select statement with INTO clause it may return two exceptions NO_DATA_FOUND or TOO_MANY_ROW . To do you avoid these execeptions. How do you write SQL statement in alternative way? Read Answers (6) | Asked by : ddkdhar Answer Question
Subscribe
Write sample code that can create a hierachical set of data without using a start with and connect by Write sample code that can create a hierachical set of data without using a start with and connect by clause in PL/SQL Read Answers (1) | Asked by : soorajsk_84 Answer Question
Subscribe
Convert SQL to Oracle Procedure using cursor SELECT APE.DAT_INSERT_DATE as "Payment Entry Date", Case when APE.TXT_INTERMEDIARY_CD is null or APE.TXT_PAYER_CUSTOMER_ID APE.TXT_INTERMEDIARY_CD then (Select TXT_CUSTOMER_NAME from GENMST_CUSTOMER Latest Answer : create or replace procedure sql_to_procedure as declare cursor c1 is SELECT APE.DAT_INSERT_DATE as "Payment Entry Date",APE.TXT_INTERMEDIARY_CD AS "Intermediary ID",APE.TXT_PAYER_CUSTOMER_ID as "CustomerID/Payer ID",TXT_CUSTOMER_NAME ... Read Answers (1) | Asked by : preeti Answer Question
Subscribe
oracle is compiler or interpretter,can any one tell me the answer?
6
I have a procedure in a procedure. The inner procedure contains out parameter. How I can call the inner procedure in the out procedure and send the inner procedure parameter value(out parameter value) into out procedure?
1
what is the difference between the query and corelated query
IBM
4
What is INSTEAD OF trigger ?
TCS
4
Difference between views and materialized views?
BirlaSoft
4
What is clustered and non-clustered indexes?
Microsoft
3
How the execution will be done in exceptions? What is Highwatermark?
2 Thermotech 1
What are the types of triggers ?
TCS
2
Whatis yhe use of cursor ? how cursor allocate context area for executing the sql statement?
HCL
2
If an unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE?
2
How toimport .dmp file in lower version of oracle from higher version ? TCS
1
What is Raise_application_error ?
1
What cursor type do you use to retrieve multiple recordsets?
Microsoft
a procedure one in two out parameters i am waiting it in a sql query can i get the output
9 1
Types of locks in database ?
TCS
3
write the Sql query for creating database backup?
TCS
3
What is the difference between join and union.
9
What are the cursor attributes used in PL/SQL ?
3
Give which cursor is better for better performance means type of cursors?
Debug PL SQL How can we generate debugging output from PL/SQL? use the oracle supplied package DBMS_OUTPUT with procedures PUT, PUT_LINE, NEW_LINE etc... What is the need of primary key as opposed to using not null and unique ? we can create a column with' not null+unique' with out using primary key 1) Primary key creates clustered index by default which actually reorders the row in a table based on index while unique key creates non-clustered index. 2) Replication of table possible only if it contains primary key. How to find error line of a package at run time How can the error line can be identified for a package at run time ? Latest Answer: Show error ... Read Answers (1) | Asked by : sanjoy.dubey Answer Question Paging In Oracle
Subscribe
Hi All,I have requirement of sending the records based on the input received from web.I have a ref_cursor returning 30 rows..Here I am supposed to do paging on the set of records present in the above ref View Question | Asked by : vijay.patil2005 Answer Question
Subscribe
What are optimizer hints? Optimizer hints are used to alter execution plan of SQL statement. For ex, certain index can be sometimes more selective for certain queries. Based on the information you can choose a more efficient execution plan by using hint and telling the optimizer to choose a more optimal path. Hints used for Optimization are : All_rows First_rows Answer Question
Subscribe
Referenced and Dependent objects How oracle manages dependency between referenced and dependent objects ? View Question | Asked by : KD09714 Answer Question
Subscribe
PL SQL Logs List at least three common ways to write logs in PL SQL? Latest Answer: i.feel,using a ref cursor, we can return more than one value to a fucntion ... Read Answers (1) | Asked by : liaohanming Answer Question
Subscribe
Problem with Utl_file.fopen Hi,There is problem with ult_file.fopen. When I run from the server side, there is no issue with utl_file and it is working fine.If I run the same procedure from Client machine, I am facing problem. It the parameter set in configuration file init.oraand UTL_FILE_DIR belongs to the directory structure in oracle server machine. And the directory structure should be on same machine as oracle server. Thus fopen can run in oracle server machine not client. Thus fopen call on client machine will give invalid_operation i.e. file could not be opened. Global Temporary Table
What is Global temporary table? and what are the benefits of it? GLOBAL TEMPORARY TABLE statement defines a temporary table for the current session. The declared temporary table description does not appear in the system catalog. It is not persistent and cannot be shared with other sessions. Each session that defines a declared global temporary table of the same name has its own unique description of the temporary table. When the session terminates, the rows of the table are deleted, and the description of the temporary table is dropped. What is an Exception ? What are types of Exception ? Exception is the error handling part of PL/SQL block. The types are Predefined and user defined. Some of Predefined exceptions are. Latest Answer : Exception is nothing but error in the PL/SQL program. If any error occured in the PL/SQL program that terminates from the program. To handle that exceptions we are using exception handling part in the PL/SQLThere are three types of exceptions1. predefined2. ... Exception is the error handling part of PL/SQL block. The types are Predefined and user defined. Some of Predefined exceptions are. CURSOR_ALREADY_OPEN DUP_VAL_ON_INDEX NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR INVALID_NUMBER LOGON_DENIED NOT_LOGGED_ON PROGRAM-ERROR STORAGE_ERROR TIMEOUT_ON_RESOURCE VALUE_ERROR ZERO_DIVIDE OTHERS. Exception is nothing but error in the PL/SQL program. If any error occured in the PL/SQL program that terminates from the program. To handle that exceptions we are using exception
handling part in the PL/SQL There are three types of exceptions 1. predefined 2. non-predefined 3. user defined Predefined exceptions are defined by the system we have some predefined exception names to handle some exceptions non-predefined exceptions are also raised by the system only but we dont have any predefined names we have to trap the exceptions with error code defined by the system User defined exceptions are defined by the user. He has to declare the exception, he has to raise the exception.
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? 1) A function will return a value, adding to that , it is possible to use a function in SQL statements, whereas procedures cannot be used. 2)No, functions cannot retrun more than one value, instead one can get this done in other way round by using OUT parameters for a function. 3)To perform validations and transactions on database tables. 4)Memory usage is more. 5)The variable defined inside Package Specification are treated as Global variables, which can be referred externally.
1)what is the starting "oracle error number"?2)what is meant by forward declaration in functions? 1)what is the starting "oracle error number"? 2)what is meant by forward declaration in functions? 1. STARTING ORACLE ERROR NO IS ORA 00001 2. Forward Declaration means.. If you are defining a package body having two procedures , If u want to use second procedure in the defination of first procedure.. You have to declare the second package with its arguments(if have) before using in the defination of first procedure.. its labled as forward declaration PL/SQL does not allow forward references. You must declare an identifier before using it. Therefore, a subprogram must be declared before calling it. You can use forward declarations to do the following: • Define subprograms in logical or alphabetical order
• Define mutually recursive subprograms • Group subprograms in a package Mutually recursive programs are programs that call each other directly or indirectly.
ibabu Answer Question
Subscribe
How can i import .dmp file in lower version of oracle from higher version ? Latest Answer : No. You cannot export a higher version to the lower version. ... Export the higher version data using lower version Export utility and import it to the lower version DB.
1.What is bulk collect?2.What is instead trigger3.What is the difference between Oracle table & PL/SQL 1.What is bulk collect?2.What is instead trigger3.What is the difference between Oracle table & PL/SQL table?4.What R built in Packages in Oracle?5.what is the difference between row migration & row changing? 1.What is bulk collect? Bulk collect is part of PLSQL collection where data is stored/ poped up into a variable. example: declare type sal_rec is table of number; v_sal sal_rec; begin select sal bulk collect into v_sal from emp; for r in 1.. v_sal.count loop dbms_output.put_line(v_sal(r)); end loop; end;
2.What is instead trigger instead triggers are used for views. 3.What is the difference between Oracle table & PL/SQL table? Table is logical entity which holds the data in dat file permanently . where as scope of plsql table is limited to the particular block / procedure . refer above example sal_rec table will hold data only till programme is reaching to end;
4.What R built in Packages in Oracle? There R more then 1000 oracle builtin packges like: Dbms_output, dbms_utility
dbms_pipe .............
5.what is the difference between row migration & row changing? Migration: The data is stored in blocks whic use Pctfree 40% and pctused 60% ( normally). The 40% space is used for update and delete statements . when a condition may arise that update/delete statement takes more then pctfree then it takes the space from anther block. this is called migration. RowChaining: while inserting the data if data of one row takes more then one block then this row is stored in two blocks and rows are chained.
sir,pls send me some more oftanily asked oracle interview questions iam an one year exprience person...i Sir,pls send me some more oftanily asked oracle interview questions iam an one year exprience person...i need one year oracle interview questions..... Read Answers (2) | Asked by : basavarajkolur Answer Question
Subscribe
What is the use of nocopy parameter in oracle procedure Hi, What is nocopy parameter in oracle procedure. what is the use of it. In which situation,we can use the nocopy parameter.Thanks,Saravanan.P
Latest Answer : Ussually IN paramter is pass by value and OUT/IN OUT are pass by refererence....If one wants to send the IN paramter too as pass by reference he could add NOCOPY parameter....advantage is always less memory usagedisadvantage is when there is a change ... Read Answers (5) | Asked by : ily_saravanan Answer Question
Subscribe
PL/SQL Block output begin For i in 1..5 loop insert into A values(i); savepoint 1; end loop; rollback to savepoint 1; commitend;--initially there are no data in table A. So my question is after execution of this After the loop exits 1 to 5 is inserted into the table and a savepoint is also created with the name savepoint1. Now after rollback no data will be deleted and the table A will have values 1 to 5. Read Answers (4) | Asked by : Kanhucharan Answer Question
Subscribe
Example for calling procedure Give an example for calling procedure with user and system exception /* simple example for calling procedure from a another procedure with system and user define exception */ set serveroutput on create or replace procedure proc1 is -- calling procedure from emp_id. v_time timestamp; -- time stamp for calling procedure. begin select systimestamp -- selecting time stamp from dual table. into v_time from dual; dbms_output.put_line(v_time); update emp -- update employees. set salary = 25000 where employee_id = 100; end proc1; / create or replace procedure emp_id -- mail procedure. (emp in emp.employee_id%type, sal out emp.salary%type) is excep exception; excep1 exception; v_time timestamp; -- time stamp for mail procedure.
begin select systimestamp -- selecting time stamp from dual table. into v_time from dual; dbms_output.put_line(v_time); select salary -- fetch the salary for analyze. into sal from emp where employee_id = emp; /* check conditions */ if sal = 24000 then proc1; elsif sal >= 25000 then raise excep; else raise excep1; -- raise exception. end if; exception when no_data_found -- system exception. then dbms_output.put_line('no record found'); when excep -- user define exception. then dbms_output.put_line('already have the salary'); when excep1 -- user define exception. then dbms_output.put_line('not in employee_id in proc1'); end emp_id; / show errors; / variable sa number execute emp_id (100, :sa) show errors; Answer Question
Subscribe
PL/SQL tables How will implement the PL/SQL tables? PL/SQl tables were introduced in Oracle 7.PL/SQL tables are similar to arrays in C.By using PL/SQL Tables, it is possible to create a collection of items, all of the same type, indexed by an integer. eg:TYPE name IS TABLE OF varchar2 INDEX BY BINARY_INTEGER;
- Pl/sql is in memory representation of a table. - It is just a data type. ( Collection type) - It may store any number of rows from table. Here is a simple example
CREATE OR REPLACE PROCEDURE TEST_PROC AS TYPE EMP_TYPE IS TABLE OF EMP%ROWTYPE; EMP_VAR EMP_TYPE; BEGIN SELECT * BULK COLLECT INTO EMP_VAR FROM EMP; FOR I IN EMP_VAR.FIRST..EMP_VAR.LAST LOOP DBMS_OUTPUT.PUT_LINE(' EMPLOYEE ' ||EMP_VAR(I).ENAME || ' SALARY IS '|| EMP_VAR(I).SAL); END LOOP; END; Oracle triggers can we issue rollback, commit in the trigger body. if we issue what is the result Commit and roll back statements are not possible from triggers. Although we can create triggers with COMMIT and ROLLBACK, it will result in an error when the trigger has fired. Ideally this is desirable since the original transaction may be rolled back and so the effects of trigger also should be rolled back. However we can use commit if it is declared as an autonomous transaction. Generally that will be used for writing to log tables. Read Answers (5) | Asked by : maheshveeragoni Answer Question
Subscribe
Difference between 'TABLE OF' and 'REF CURSOR' What exactly the difference between 'TABLE OF' and 'REF CURSOR' in PL/SQL?For what purposes these both might be used? A ref cursor is a dynamic cursor in which the contents of cursor can be changed dynamically at run time depending upon our requirement. A ref cursor is basically a data type. A variable declared based on such data type is called cursor variable. We can assosiate differenct statement to a cursor variable dynamically. The main advantage of ref cursor is 1. We can return result set to a client which we can't do using normal cursors. 2. It can be passed as parameter to sub programs. Table of is use to define a collection type. Collections are generally used for bulk processing. In cursors the data is processed sequentially. Using collections we can process all the data in one go. Answer Question
Subscribe
Oracle refcursor and procedure
how to pass result set using refcursor from one package procedure to another package procedure? and code also CREATE TABLE employees ( empid NUMBER(5), empname VARCHAR2(30)); INSERT INTO employees (empid, empname) VALUES (1, 'Dan Morgan'); INSERT INTO employees (empid, empname) VALUES (2, 'Jack Cline'); INSERT INTO employees (empid, empname) VALUES (3, 'Caleb Small'); COMMIT; CREATE OR REPLACE PROCEDURE pass_ref_cur(p_cursor SYS_REFCURSOR) IS TYPE array_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER; rec_array array_t; BEGIN FETCH p_cursor BULK COLLECT INTO rec_array; FOR i IN rec_array.FIRST .. rec_array.LAST LOOP dbms_output.put_line(rec_array(i)); END LOOP; END pass_ref_cur; / set serveroutput on DECLARE rec_array SYS_REFCURSOR; BEGIN OPEN rec_array FOR 'SELECT empname FROM employees'; pass_ref_cur(rec_array); CLOSE rec_array; END; /
Which two statements are true?A. A function must return a value.B. A procedure must return a value.C. A. Which two statements are true? A. A function must return a value. B. A procedure must return a value. C. A function executes a PL/SQL statement. D. A function is invoked as part of an expression. E. A procedure must have a return Data
A function must return a value - It's True . " A function has to return a value " ------------------------------------------------------------------B. A procedure must return a value - It's fase. " A Procedure may or may not return a value " ----------------------------------------------------------------------------------C. A function executes a PL/SQL statement -It's True. We can write Data Manipulation Statements such as insert, update, delete inside the Function. ---------------------------------------------------------------------------------------------------D. A function is invoked as part of an expression. -It's True. We can invoke a function as a part of expression in sql statements. ------------------------------------------------------------------------------------------------E. A procedure must have a return Data --It's false. No need ...
Oracle extract records from temporary table Assume that I am using a temporary table in a procedure and I am inserting records and updating another set of records through Merge statement. If I use cursor in that temporary table, How can I extract Create Global temporary tables and say on commit preserve rows. The global temporary tables have data available till the session is active. So you if you insert it at one procedure and want to access it somewhere else you can do that very easily till the session is active
What is nested table in Oracle and and difference between table and nested table A Table is a basic unit of storage in oracle. A nested table is a collection type. The main advantage of collections is instead of processing data sequentially, we may process all the date in one step. - It is a collection of rows stored as a column in a table. - It is a table withing a table. - There is no restriction on number of rows in a nested table - There is no restriction on number of columns in a nested table. - We can not index nested table. - The nested table is stored as a seperate table and main table maintains a pointer to the nested table as reference. - Nested table stored data in no particular order - But when you retrieve data into pl/sql variable it assigns serial number starts with 1 - Intially they are dense you may sparse later. - Nested tables are unbounded. There is no upper limit.
How do you call procedure have a DDL or commit/rollback statement from a trigger? Yes using pragma autonomous_transaction as per example below for commit. we have two table employee and employee_bak of same structure (empid, emp_name, location, manager_id) --autonomous procedure will insert value in employee_bak, procedure is getting --called from trigger on insert in employee. create or replace procedure replicate_employee (p_emp_id employee.emp_id%type, p_emp_name employee.emp_name%type, p_location employee.location%type, p_manager_id employee.manager_id%type) as pragma autonomous_transaction; begin insert into employee_bak values(p_emp_id, p_emp_name, p_location, p_manager_id); commit; end replicate_employee; --trigger after insert on employee create or replace trigger trg_backup_employee after insert on employee for each row declare begin replicate_employee(:new.emp_id, :new.emp_name, :new.location, :new.manager_id); end; --Note : if pragma autonomous_transaction is not used, trigger will give error at run –time
What are mutating tables? When a table is in state of transition it is said to be mutating. eg :: If a row has been deleted then the table is said to be mutating and no operations can be done on the table except select. Mutate means chage. Mutating table is a table that is being modified by update, delete or insert statement Answer Question
Subscribe
Char(20) = 'name' varchar2(20)='name' When comparing these two values, are
Char(20) = 'name' varchar2(20)='name' When comparing these two values, are the spaces padded in char are considered or not? Are both values equal? In Char type spaces will be padded after 'name' uptp max length 20. in Varchar spaces will not be padded.
Is it possible to use commit or rollback in exception section. Yes you can use commit or rollback in exception block; select * from test123; A ---------51 Declare s varchar2(2); Begin update test123 set a = a+10; select a into s from test123 where a=20; exception when others then rollback; dbms_output.put_line('test'|| s); End; SQL> / test PL/SQL procedure successfully completed. SQL> select * from test123; A ---------51
How do you encrypt the function to prevent accessing from users without specific permission. ? Using wrap utility we can encrypt source code of a function to byte code (Not a readable format). Becareful there is no decrypt utility to convert source code back to ascii format. if you aim is just to prevent function accessing from users do not give privelege on that function to other users. I think you can use wrap utility encrypt the function / procedure program units for example create a function store it as xx.sql file
c:oracle> wrap iname=xx.sql
This process will result xx.plb file which is encrypted
What are purity rules for functions? why they use ? what effects if not follow these rules? The purity level defines what structure the function reads or modifies. the types of purity level: 1)wnds--write no database stage I.e the function does not modify any database or tables. 2)rnds--reads no database state. i.e function does not read any database tables. 3)wnps--write no package state i.efunction does not modify any packaged variables. 4)rnps-read no package state i.e function does not read any package variables. To be callable from SQL statements, a stored function (and any subprograms called by that function) must obey certain "purity" rules, which are meant to control side effects: • • •
When called from a SELECT statement or a parallelized INSERT, UPDATE, or DELETE statement, the function cannot modify any database tables. When called from an INSERT, UPDATE, or DELETE statement, the function cannot query or modify any database tables modified by that statement. When called from a SELECT, INSERT, UPDATE, or DELETE statement, the function cannot execute SQL transaction control statements (such as COMMIT), session control statements (such as SET ROLE), or system control statements (such as ALTER SYSTEM). Also, it cannot execute DDL statements (such as CREATE) because they are followed by an automatic commit.
If any SQL statement inside the function body violates a rule, you get an error at run time (when the statement is parsed). To check for violations of the rules, you can use the pragma (compiler directive) RESTRICT_REFERENCES. The pragma asserts that a function does not read or write database tables or package variables. For example, the following pragma asserts that packaged function credit_ok writes no database state (WNDS) and reads no package state (RNPS): CREATE PACKAGE loans AS FUNCTION credit_ok RETURN BOOLEAN; PRAGMA RESTRICT_REFERENCES (credit_ok, WNDS, RNPS); END loans;
Write sample code that can create a hierachical set of data without using a start with and connect by Write sample code that can create a hierachical set of data without using a start with and connect by clause in PL/SQL select empno, ename, level from emp where connect by mgr=empno start with job='PRESIDENT'; What is the difference between right join and right outer join..
Both are same. Right outer join returns all the reocrds that satisfy the join condtion + rest of the records from right (or second) table. Why DUAL table is not visible? DUAL is a part data dictionary and owned by SYS. You should not make modifications to this table. It contains only one row and one column of VARCHAR2 datatype. Used to refer an object which does not have any pysical reference in database table. Ex:- Select sysdate from dual. What is the need for using function purity in pl/sql To be callable from SQL statements, a stored function must obey the following "purity" rules, which are meant to control side effects: 1. When called from a SELECT statement or a parallelized INSERT, UPDATE, or DELETE statement, the function cannot modify any database tables. 2. When called from an INSERT, UPDATE, or DELETE statement, the function cannot query or modify any database tables modified by that statement. 3. When called from a SELECT, INSERT, UPDATE, or DELETE statement, the function cannot execute SQL transaction control statements (such as COMMIT), session control statements (such as SET ROLE), or system control statements (such as ALTER SYSTEM). Also, it cannot execute DDL statements (such as CREATE) because they are followed by an automatic commit. Which type of binding does PL/SQL use? PL/SQL uses early binding which makes the execution of block because as fast as possible as the database objects are already verified by the compiler. Before a PL/SQL program can be executed, it must be compiled. The PL/SQL compiler resolves references to Oracle objects by looking up their definitions in the data dictionary. Then, the compiler assigns storage addresses to program variables that will hold Oracle data so that Oracle can look up the addresses at run time. This process is called binding. How a database language implements binding affects runtime efficiency and flexibility. Binding at compile time, called static or early binding, increases efficiency because the definitions of database objects are looked up then, not at run time. On the other hand, binding at run time, called dynamic or late binding, increases flexibility because the definitions of database objects can remain unknown until then. What is the difference between using IS and AS while creating a procedure, function package and package body? There is absolutely no difference between using IS and AS while creating a procedure, a function or a package. What is the disadvantage of out parameter in functions
Functions with "out" parameters cannot be used in SQL statements, however I disagree because functions without parameters can also be called in select statements as long as they have a return() (Eg: SYSDATE) What do you mean by OCI, Data guard and Advance queue responsibilities for a Oracle developers? OCI stands for Oracle Call Interface, it is a interface api used to access oracle database from C programs. Data Guard stands for it is multiple DB servers environment configured for Physical as well as Logical Standby Databases. And Oracle Advance Queuing provides interfacing/messing mechanism between oracle and non- oracle systems. Compare EXISTS and IN Usage with advantages and disadvantages. IN or EXISTS which gives better performance depends upon the situation.
Select * from T1 where x in (select y from T2 ) is typically processed as: select * from t1, ( select distinct y from t2 ) t2 where t1.x = t2.y; The subquery is evaluated, distinct'ed, indexed (or hashed or sorted) and then joined to the original table -- typically.
While using IN , optimizer runs subquery first and then joins it with main dataset. Table in the subqery is small and table in the main query is large then IN usaully makes sense.
select * from t1 where exists ( select null from t2 where y = x ) That is processed more like: for x in ( select * from t1 ) loop if ( exists ( select null from t2 where y = x.x ) then OUTPUT THE RECORD end if end loop It always results in a full scan of T1
Using EXISTS, optimizer runs main query first and then applies dataset to the subquery. If the main table size is small and subquery table size is large then EXISTS usually makes sense.
How to reduce the the burden/main memory on database if i am using refcursor to hold large data to increase performance. What will be the impact of replacing an API call with a stored PL/SQL call? How PL SQL is different from T-SQL SQL (Structures Query Language) PL/SQL (Procedure Language / SQL) is the Oracle's version with lots of additional proprietary functions. T-SQL : Transact-SQL is Microsoft's proprietary version of SQL. When using a count(distinct) is it better to use a self-join or temp table to find redundant data, and provide an example? What is the difference between database trigger and application trigger? Database triggers are backend triggeres and perform as any event occurs on databse level (ex. Inset,update,Delete e.t.c) wheras application triggers are froentend triggers and perform as any event taken on application level (Ex. Button Pressed, New Form Instance e.t.c)
what are the file utilit comands used in PL/SQL procedures? utlfile is used to transfer data from database tables to flat file With the Oracle-supplied UTL_FILE package, you can read from and write to operating system files. It Provides security for directories on the server through the init.ora file. UTL_FILE Procedures and Functions: • Function FOPEN • Function IS_OPEN • Procedure GET_LINE • Procedure PUT, PUT_LINE, PUTF • Procedure NEW_LINE • Procedure FFLUSH • Procedure FCLOSE, FCLOSE_ALL Explain about CURSOR and REF CURSUR with real time scenario where this can be used. CURSOR A cursor is a variable that runs through the tuples of some relation. This relation can be a stored table, or it can be the answer to some query.
A cursor can be used in realtime when u need to fetch some records and do some kind of an operation on each of these records .. which cannot be done with a single DML... REFERENCE CURSOR A cursor variable is a data structure that points to a cursor object, which in turn points to the cursor's result set. You can use cursor variables to more easily retrieve rows in a result set from client and server programs. You can also use cursor variables to hide minor variations in queries. The syntax for a REF_CURSOR type is: TYPE ref_cursor_name IS REF CURSOR
[RETURN record_type];
If you do not include a RETURN clause, then you are declaring a weak REF CURSOR. Cursor variables declared from weak REF CURSORs can be associated with any query at runtime. A REF CURSOR declaration with a RETURN clause defines a "strong" REF CURSOR. A cursor variable based on a strong REF CURSOR can be associated with queries whose result sets match the number and datatype of the record structure after the RETURN at runtime. To use cursor variables, you must first create a REF_CURSOR type, then declare a cursor variable based on that type. Reference cursors on the other hand are used in realtime for dynamic purposes ... like when its required that you need to do an operation not on a single table but multiple tables and u cannot use cursor for each table to do the operation ... u can used dynamic or reference cursor to do this operation. What is the difference between private packages and public package . what is the difference in declaration of these 2 packages. i dont think there is something called as public package / private package. But yes the methods defined in a package can either be public or private. Below is a simple expln. · Variables and constants that are not defined within any function or procedure in the package are called package data. · Package data declared inside the package specification is called public package data. · Package data declared inside the package body is called private package data. · Private package data can be accessed only by elements defined in the package itself. · Public package data can be accessed by the package itself and by any program that can execute that package. · Package data structures, public and private, act like globals and persist within a single Oracle session or connection.
What is CODEX function? How to create a constraint for a tablecolumn which is already created Alter Command: Alter table tablename add constraint constraintname primary key / unique (column name) What is a cluster and what is the real time use and business reasons to use Clustering Why we use instead of trigger. what is the basic structure of the instead of trigger. Explain specific Conceptually, INSTEAD OF triggers are very simple. You write code that the Oracle server will execute when a program performs a DML operation on the view. Unlike a conventional BEFORE or AFTER trigger, an INSTEAD OF trigger takes the place of, rather than supplements, Oracle's usual DML behavior. (And in case you're wondering, you cannot use BEFORE/AFTER triggers on any type of view, even if you have defined an INSTEAD OF trigger on the view.) CREATE OR REPLACE TRIGGER images_v_insert INSTEAD OF INSERT ON images_v FOR EACH ROW BEGIN /* This will fail with DUP_VAL_ON_INDEX if the images table || already contains a record with the new image_id. */ INSERT INTO images VALUES (:NEW.image_id, :NEW.file_name, :NEW.file_type, :NEW.bytes); IF :NEW.keywords IS NOT NULL THEN DECLARE /* Note: apparent bug prevents use of :NEW.keywords.LAST. || The workaround is to store :NEW.keywords as a local || variable (in this case keywords_holder.) */ keywords_holder Keyword_tab_t := :NEW.keywords; BEGIN FOR the_keyword IN 1..keywords_holder.LAST LOOP INSERT INTO keywords VALUES (:NEW.image_id, keywords_holder(the_keyword)); END LOOP; END; END IF; END; Once we've created this INSTEAD OF trigger, we can insert a record into this object view (and hence into both underlying tables) quite easily using: INSERT INTO images_v VALUES (Image_t(41265, 'pigpic.jpg', 'JPG', 824, Keyword_tab_t('PIG', 'BOVINE', 'FARM ANIMAL')));
This statement causes the INSTEAD OF trigger to fire, and as long as the primary key value (image_id = 41265) does not already exist, the trigger will insert the data into the appropriate tables. Similarly, we can write additional triggers that handle updates and deletes. These triggers use the predictable clauses INSTEAD OF UPDATE and INSTEAD OF DELETE. How can we avoid duplicate rows. without using distinct command Using Self join like : select dup.column from tab a,tab b where a.dup.column=b.dup.column and a.rowidb.rowid DELETE FROM emp WHERE ROWID NOT IN (SELECT MIN(ROWID) FROM emp GROUP BY id); select a.DEPTNO from emp a, emp b where a.deptno=b.deptno and a.rowid not in (select max(rowid) from emp) group by a.deptno; What is Pragma Init Exception ? what is difference between user defined exception and init pragma exception. what is the use of it. Pragma Init Exception is the Non predefined exception. It will direct the complier to add the user defined error message to the oracle error number. It means that there are some predefined error codes which are not having the error message explicitly the programmer has to give error message for the predefined error code so the pragma Init Exception will direct the complier to associate the user defined error message to predefined error codes. User-defined exceptions must be explicitly raised through the use of the RAISE statement e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
How to disable a trigger for a particular table ? alter table disable trigger What are the disadvantages of Packages and triggers?? Disadvantages of Triggers • • • •
It is easy to view table relationships , constraints, indexes, stored procedure in database but triggers are difficult to view. Triggers execute invisible to client-application. They are not visible or can be traced in debugging code. It is hard to follow their logic as it they can be fired before or after the database insert/update happens. It is easy to forget about triggers and if there is no documentation it will be difficult to figure out for new developers for their existence.
•
Triggers run every time when the database fields are updated and it is overhead on system. It makes system run slower.
Disadvantage of packages: • • • • • • • •
Unnecessary module loading. Unable to load large packages into memory. Unable to compile large packages. Lack of synonym support. No version control. You cannot reference remote packaged variables directly or indirectly.. Inside package you cannot reference host variable.. We are not able to grant a procedure in package..
How do you set table for read only access ? if i am updating one record in a table at that time no other user can't able insert ,update the record in same table How is it possible Latest Answer: you can select the table for updationfor eg: select * from emp for update;no you can do the update/insert anything you want... any other user or session would be able to do any insert/update to the same table only after you release the table by commit ... Read Answers (4) | Asked by : nitin_kumat Answer Question
Subscribe
What is the use of nocopy parameter in oracle procedure Prior to Oracle 8i there were three types of parameter-passing options to procedures and functions: • • •
IN: parameters are passed by reference OUT: parameters are implemented as copy-out (passed by value) IN OUT: parameters are implemented as copy-in/copy-out (passed by value)
The technique of OUT and IN OUT parameters was designed to protect original values of them in case exceptions were raised, so that changes could be rolled back. Because a copy of the parameter set was made, rollback could be done. However, this method imposed significant CPU and memory overhead when the parameters were large data collections—for example, PL/SQL Table or VARRAY types. With the new NOCOPY option, OUT and IN OUT parameters are passed by reference, which avoids copy overhead. However, parameter set copy is not created and, in case of an exception rollback, cannot be performed and the original values of parameters cannot be restored.
Here is an example of using the NOCOPY parameter option: TYPE Note IS RECORD( Title VARCHAR2(15), Created_By VARCHAR2(20), Created_When DATE, Memo VARCHAR2(2000));TYPE Notebook IS VARRAY(2000) OF Note;CREATE OR REPLACE PROCEDURE Update_Notes(Customer_Notes IN OUT NOCOPY Notebook) IS BEGIN ...END; How to avoid the mutating error with sample program Hi, can any body give me the sample program for avoiding the mutating error. we can avoid the mutating through the statement level trigger instead of using the statement level trigger, i need one sample A mutating error comes when u r trying to do some DML operation on a table that owns the trigger.... there are a lot of options to avoid mutation .. eg, Making it autonomous transaction or making it a statement level trigger ... or using temporary table... the following example gives how to use temporary pl/sql table to avoid mutation error : create table CUG ( id_cug number(12) not null primary key, id_B number(12) not null, type number(1), foreign key (id_B) references CUG (id_cug) on delete cascade); Next we create a temporary table to avoid the "Mutating Table Problem". drop table CUGTMP; create global temporary table CUGTMP ( id_B number(12), type number(1)) on commit delete rows; The following trigger checks new rows (Inserts) in CUG create or replace trigger bi_r before insert on CUG for each row declare l_type CUG.type%type; begin if (:new.type in (3,4)) then select type into l_type from CUG where id_cug = :new.id_B; end if; if (l_type != 2) then raise_application_error(-20002, 'C and D CUGs must have a leading B'); end if; end; / The following Trigger saves the new values for id_B in the temporary table.
create or replace trigger au_r after update of id_B on CUG for each row begin insert into CUGTMP (id_B,type) values (:new.id_B,:new.type); end; / The following Trigger finally checks, that C and D CUGs belong to a B CUG. create or replace trigger au_s after update of id_B on CUG declare l_id_B number(12); l_typeCD number(1); l_typeB number(1); cursor cur_cugtmp is select id_B,type from CUGTMP; begin open cur_cugtmp; loop fetch cur_cugtmp into l_id_B,l_typeCD; exit when cur_cugtmp%notfound; select type into l_typeB from CUG where id_cug = l_id_B; if (l_typeB != 2) then raise_application_error(-20002, 'C and D CUGs must have a leading B'); end if; end loop; close cur_cugtmp; end; / Test insert and update insert into CUG (id_cug,id_B,type) values (0,0,0); insert into CUG (id_cug,id_B,type) values (1,0,2); insert into CUG (id_cug,id_B,type) values (2,0,2); insert into CUG (id_cug,id_B,type) values (3,1,3); insert into CUG (id_cug,id_B,type) values (4,2,3); insert into CUG (id_cug,id_B,type) values (5,1,4); insert into CUG (id_cug,id_B,type) values (6,2,4); commit;
SQL> select * from CUG; ID_CUG ID_B TYPE ---------- ---------- ---------0 0 0 1 0 2 2 0 2 3 1 3 4 2 3 5 1 4 6 2 4 Now, we want that that the CUGs 3,4,5,6 changes the leadership to CUG 2 SQL> update CUG set id_B = 2 where id_cug in (3,4,5,6); 4 rows updated. SQL> select * from cug; ID_CUG ID_B TYPE ---------- ---------- ---------0 0 0 1 0 2 2 0 2 3 2 3 4 2 3 5 2 4 6 2 4 Next we delete the "Leader" with ID_CUG = 2. All childs must be deleted automatically with the DELETE CASCADE. SQL> select * from cug; ID_CUG ID_B TYPE ---------- ---------- ---------0 0 0 1 0 2 Everything looks fine - cool isn't it ?
What is difference between PL/SQL tables and arrays? 1. PL/SQL tables are temporary array like objects used in a PL/SQL Block. The size of pl/sql table is unconstrained. For varrays we need to specify upper bound. 2. Pl/sql tables can not be stored in database where as varrays can be stored in database. 3. We can use negative index for pl/sql tables. In varrays negative index is not allowed. 4. In pl/sql tables data need not be stored in consecutive rows. Varrays are dense and retain their order while storing in database.
5. You cannot perform DML operations on PL/SQL table. DML operations can be performed on Varrays. 1. Varray is set of values of same data type whereas tables can store values of diff data types..
What is the use of NOCOPY Compiler Hint while writing PL/SQL procedures/subprograms??? The PL/SQL runtime engine has two different methods for passing parameter values between stored procedures and functions, by value and by reference. When a parameter is passed by value the PL/SQL runtime engine copies the actual value of the parameter into the formal parameter. Any changes made to the parameter inside the procedure has no effect on the values of the variables that were passed to the procedure from outside. When a parameter is passed by reference the runtime engine sets up the procedure call so that both the actual and the formal parameters point (reference) the same memory location that holds the value of the parameter. By default OUT and IN OUT parameters are passed by value and IN parameters are passed by reference. When an OUT or IN OUT parameter is modified inside the procedure the procedure actually only modifies a copy of the parameter value. Only when the procedure has finished without exception is the result value copied back to the formal parameter. Now, if you pass a large collection as an OUT or an IN OUT parameter then it will be passed by value, in other words the entire collection will be copied to the formal parameter when entering the procedure and back again when exiting the procedure. If the collection is large this can lead to unnecessary CPU and memory consumption. The NOCOPY hint alleviates this problem because you can use it to instruct the runtime engine to try to pass OUT or IN OUT parameters by reference instead of by value. In the absence of the NOCOPY hint the entire orders collection would have been copied into the theorders variable upon exit from the procedure. Instead the collection is now passed by reference. Keep in mind, however, that there is a downside to using NOCOPY. When you pass parameters to a procedure by reference then any modifications you perform on the parameters inside the procedure is done on the same memory location as the actual parameter, so the modifications are visible. In other words, there is no way to “undo” or “rollback” these modifications, even when an exception is raised midway. So if an exception is raised inside the procedure the value of the parameter is “undefined” and cannot be trusted. Consider our get_customer_orders example. If the p_orders parameter was half-filled with orders when an exception was raised, then upon exit our theorders variable will also be halffilled because it points to the same memory location as the p_orders parameter. This downside is most problematic for IN OUT parameters because if an exception occurs midway then not only is the output garbage, but you’ve also made the input garbage. To sum up, a NOCOPY hint can offer a small performance boost, but you must be careful and know how it affects program behavior, in particular exception handling.
What are the advantages and disadvantages of DBMS-SQL What is PRAGMA RESTRICT_REFERENCES: By using pragma_restrict_references we can give the different status to functions,Like WNDB(WRITE NO DATA BASE),RNDB(read no data base),Write no package state,read no packge state.
In PL/SQL if we write select statement with INTO clause it may return two exceptions NO_DATA_FOUND or In PL/SQL if we write select statement with INTO clause it may return two exceptions NO_DATA_FOUND or TOO_MANY_ROW . To do you avoid these execeptions. How do you write SQL statement in alternative way? If you don't want an exception to be raised on a SELECT statement, you can avoid executing the statement by having a count just before the SELECT as shown below TOO_MANY_ROWS When you try to match single value with multiple. To avoid it use “IN” clause instead of “=” in select statement. SELECT count(rowid) into v_count from tables where conditions. if(v_count = 1) then SELECT column into v_column from tables where conditions; else --Select statement not executed because it will throw exception v_column=dummy_value; end if; However it is a much better practice to handle these errors using exceptions Without closing the cursor, If you want to open it what will happen. If error, get what is the error? It throws error message ORA-06511: PL/SQL: cursor already open In function and procedure the parameter pass is "call by value" or "call by reference"? IN params are by default pass by references. IN OUT & OUT params are by default pass by value. One can pass IN OUT/OUT by references using NOCOPY option. Is it possible create table in procedure or function? If Not Why?
Its possible to create a table using procedures. There are two ways, #1
Use PRAGMA AUTONOMOUS_TRANSACTION; Code: Create or replace procedure Create_tab As PRAGMA AUTONOMOUS_TRANSACTION; Begin EXECUTE IMMEDIATE ‘Create TABLE ProcT(col1 number(2), col2 varchar2(10))’; End; #2 Use Dbms_sql Package Code: Create or Replace procedure Dynamic_Tab (TabName in varchar2) as V_cursor INTEGER; Ddl_Execute INTEGER; begin V_cursor:=Dbms_sql.Open_cursor; Dbms_sql.Parse(V_cursor,'Create Table '||TabName||' (col1 number(2),col2 varchar2 (10))', Dbms_sql.native); Ddl_Execute:=dbms_sql.Execute(V_cursor); Dbms_output.put_line(TabName||' Created.'); If Dbms_sql.Is_open(V_cursor) then
Dbms_sql.Close_cursor(V_Cursor); end if; Exception when Others then Dbms_output.put_line(sqlerrm); End Dynamic_Tab; Select from A table through cursor and update B table. If it updates successfully then insert into another table. Handled every type of exception in the code? Explain, Is it possible to have same name for package and the procedure in that package. Yes, its possible to have same name for package and the procedure in that package. What is dense_rank function and it's usage ? In Oracle/PLSQL, the dense_rank function returns the rank of a row in a group of rows. It is very similar to the rank function. However, the rank function can cause non-consecutive rankings if the tested values are the same. Whereas, the dense_rank function will always result in consecutive rankings. Dense_Rank gives ranking for groups and Rank gives rank Used as an Aggregate Function As an Aggregate function, the dense_rank returns the dense rank of a row within a group of rows. The syntax for the dense_rank function when used as an Aggregate function is: dense_rank( expression1, ... expression_n ) WITHIN GROUP ( ORDER BY expression1, ... expression_n ) Used as an Analytic Function As an Analytic function, the dense_rank returns the rank of each row of a query with respective to the other rows. The syntax for the dense_rank function when used as an Analytic function is: dense_rank() OVER ( [ query_partition_clause] ORDER BY clause ) What is diff between strong and weak ref cursors A strong REF CURSOR type definition specifies a return type, but a weak definition does not.
Strong Ref cursor type is less Error prone, because oracle already knows what type you are going to return DECLARE TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE; -- strong TYPE GenericCurTyp IS REF CURSOR; -- weak How to insert a music file into the database LOB datatypes can be used to store blocks of unstructured data like graphic images, video, audio, etc
HiWhile creating a table, what is the difference between VARCHAR2(80) and VARCHAR2(80 BYTE)? it is now possible to specify the length in 3 different ways: 1. VARCHAR2(20) : uses the default length semantics defined by the NLS_LENGTH_SEMANTICS parameter which defaults to BYTE. 2. VARCHAR2(20 BYTE) : allows only the specified number of bytes to be stored in the column, regardless of how many characters this represents. 3. VARCHAR2(20 CHAR) : allows the specified number of characters to be stored in the column regardless of the number of bytes this equates to. What are the Limitations of Packages,views,procedures?What is the maximum number of subprograms inside There is no limitation on the number of Subprograms in the package, but there is a limitation on the compiled file size in the database. What is the order of execution if there is a statement level and row level trigger on a same table? Before Statement level Before Row level After Row level After Statement level Can we have same trigger with different names for a table?eg: create trigger trig1after insert on tab1; create trigger trig2after insert on tab1;If yes,which trigger executes first. its always possible...since oracle allows 12 triggers/table. The triggers will be fired on the basis of TimeStamp of their creation in Data Dictionary. The trigger with latest timestamp will be fired at last.
What will happen to an anonymus block,if there is no statement inside the block?eg:declarebeginend; Error will occur at compile time. Wheather a Cursor is a Pointer or Reference? cursor is basically a pointer as it's like a address of virtual memory which is being used storage related to sql query & is made free after the values from this memory is being used. What happens when commit is given in executable section and an error occurs ?please tell me what happens if exception block is committed at the last? Whenever the exception is raised ..all the transaction made before will be commited. If the exception is not raised then all the transaction will be rolled back. What is mutatinig trigger? How do you avoid mutating trigger? Mutating Trigger is very simple, see you have row level trigger on table with before/after timing, now in you trigger defination if you have query(DML) on the same table on which trigger is Based , then there is Mutating of Trigger Error. Since oracle can`t process same table @ same time for two diff task. You can avoid mutating trigger by using autonomous transaction. How can i see the time of execution of a sql statement? How to change owner of a table? Owner of a table is the schema name which holds the table. To change the owner just recreate the table in the new schema and drop the previous table
What is materialized view? Latest Answer: in addition to te previous posts, unlike a View,which refreshes automatically if the underlying base table data is changed, the data in a Materialized view needs o be refreshed explicitly with the help of a dbms_job.Thanks. ... Read Answers (4) | Asked by : Mrigen Answer Question
Subscribe
What is Atomic transaction? An atomic transaction is a database transaction or a hardware transaction which either completely occurs, or completely fails to occur. A prosaic example is pregnancy - you can't be "halfway pregnant"; you either are or you aren't
How to get the 25th row of a table. select * from emp where rownum=25; Mention the differences between aggregate functions and analytical functions clearly with examples? Aggregate Function: Group functions returns one result per each group of the result set Analytical Function: Where as analytical functions returns multi rows per each group i.e. using analytical functions we may display group results along with individual rows What ever an analytic function does can be done by native SQL, with join and sub-queries. But the same routine What is the difference between instead of triggers, database trigger and schema trigger? INSTEAD OF Trigger control operation on view , not table. They can be used to make nonupdateable views updateable and to override the behvior of view that are updateable. Database triggers are executed in response to particular events on tables. Trigger for a table /view is a database trigger. e.g before , insert * update, delete, insert * row level, statement level Schema triggers are fired when schema objects (tables) are modified. It can be like before create, later, drop. e.g before logoff, after logon, before create, drop, alter on schema ( these trigger are also called DDL trigger) Application trigger: before shutdown, after startup, on error( any error occur in database, after starting the orcalce instance, before closing the instance) What is the difference between database server and data dictionary Database Server: Database server is a server on which the instance of oracle as server runs. The database server is a key component in a client/server environment. It holds the database management system (DBMS) and the databases. Upon requests from the client machines, it searches the database for selected records and passes them back over the network. DB dictionary: The data dictionary comprises a set of tables and views that map the structure of the database.
Oracle stores information here about the logical and physical structure of the database. It is managed by oracle server. The data dictionary contains information such as the following: • • • •
User information, such as user privileges Integrity constraints defined for tables in the database Names and datatypes of all columns in database tables Information on space allocated and used for schema objects
Hi, How do we display the column values of a table using cursors without knowing the column names inside the loop? DECLARE CURSOR cr_data IS SELECT ROWID, a.* FROM fnd_user a where rownum < 10; l_table_name VARCHAR2(2000) := 'FND_USER'; -- IMP--This table name should be same as your from table in the above cursor l_value VARCHAR2 (2000); l_str VARCHAR2 (2000); CURSOR column_names (p_table_name VARCHAR2) IS SELECT * FROM all_tab_columns WHERE table_name = p_table_name; -- You can use order by clause here if you want. BEGIN FOR cr_rec IN cr_data LOOP
-- We should pass the same Table Name FOR cr_columc_rec IN column_names (l_table_name) LOOP l_str := 'Select ' || cr_columc_rec.column_name || ' from '||l_table_name||' where rowid = '||chr(39) || cr_rec.ROWID||chr(39); DBMS_OUTPUT.put_line ('Query is ' || l_str); EXECUTE IMMEDIATE l_str INTO l_value; DBMS_OUTPUT.put_line ( 'Column is ' || cr_columc_rec.column_name || ' and Value is ' || l_value ); END LOOP; END LOOP; END; Suppose I have 2 triggers on table T, tr1- a before insert trigger & tr2- a before update trigger. tr1 has update (T) statement inside body of tr1and tr2 has insert (T) statement inside body of tr2. Now, I'm trying to insert a row into T.What will hppn?? You will get a mutating table error. because you cannot do any DML statements inside the trigger which is used by the same table you are updating or inserting. What is the diff between %Rowtype and %type?
%Rowtype means associating a single variable to a entire row.(It is one way of Declaring a composite plsql datatype "RECORD") %type means associating a single variable to a particular column in table. both %Rowtype and %type declarations are known as Anchored Declarations in plsql . What is difference between Cursor and Ref Cursor. Please give example. Cursor is static one and ref cursor is dynamic with return type. Cursor is a structure which points to a memory locations while Ref-cursor is a datastructure which point to a object which inturn points to Memory locations..the advantage of having Ref-cursor is that we can pass dynamically the Ref-cursor as a parameter to a procedures.. Can we create a table using with Procedure or Function?wat is the Mutating trigger error? Ya, we can create table with procedure by using 'EXECUTE IMMEDIATE' command. Mutating error:- occurs when row level trigger accesses same table on which it is based while executing or the table currently being modified by the DML statements. 1.What is bulk collect?2.What is instead trigger3.What is the difference between Oracle table & PL/SQL table?4.What R built in Packages in Oracle?5.what is the difference between row migration & row changing? 1.What is bulk collect? Bulk collect is part of PLSQL collection where data is stored/ poped up into a variable. example: declare type sal_rec is table of number; v_sal sal_rec; begin select sal bulk collect into v_sal from emp; for r in 1.. v_sal.count loop dbms_output.put_line(v_sal(r)); end loop;
end;
2.What is instead trigger instead triggers are used for views. 3.What is the difference between Oracle table & PL/SQL table? Table is logical entity which holds the data in dat file permanently . where as scope of plsql table is limited to the particular block / procedure . refer above example sal_rec table will hold data only till programme is reaching to end;
4.What R built in Packages in Oracle? There R more then 1000 oracle builtin packges like: Dbms_output, dbms_utility
dbms_pipe .............
5.what is the difference between row migration & row changing? Migration: The data is stored in blocks whic use Pctfree 40% and pctused 60% ( normally). The 40% space is used for update and delete statements . when a condition may arise that update/delete statement takes more then pctfree then it takes the space from anther block. this is called migration. RowChaining: while inserting the data if data of one row takes more then one block then this row is stored in two blocks and rows are chained. How can I create a new table by using other two table's values. CREATE TABLE table_name AS ( SELECT column_name,column_name FROM tablename1 ) I want to tune the below query for performance issue can u please help me the query is SELECT DISTINCTA.BUSINESS_UNIT,A.CUST_ID,A.ASOF_DTFROM I want to tune the below query for performance issue can u please help me the query is SELECT DISTINCTA.BUSINESS_UNIT,A.CUST_ID,A.ASOF_DTFROM PS_ITEM_ACTIVITY A WHERE A.BUSINESS_UNIT = '1100G'AND A.ITEM LIKE 'OA%' AND A.PO_LINE = 0AND A.ENTRY_REASON 'CLEAR'AND A.ASOF_DT > '01-JAN-1900'AND A.USER1 = ' 'UNIONSELECT
DISTINCTA.BUSINESS_UNIT,A.CUST_ID,A.ASOF_DTFROM PS_PENDING_ITEM A WHERE A.BUSINESS_UNIT = '1100G'AND A.ITEM LIKE 'OA%' Read Answers (5) | Asked by : snehal Answer Question
Subscribe
Suppose thr are 10 DMLs(insert,update,delete ) in the main section of the PL/SQL block .The exception Put some dbms_output statement after each DML statement. 1)any one can tell me,suppose we have 1000 of records,ok.then we want to update only 500 records,how can we solve this problem? 2)how many types of "explicit cursors" we have? update set = where rownum Declare Cursor c1 is select * from emp FORUPDATE; Z c1%rowtype; Begin Open C1; Fetch c1 into Z; Commit; Fetch c1 in to Z; end; NO ERRORS. ERROR can arise for space between “in to Z” What are the Restrictions on Cursor Variables? Cursor variables are subject to the following restrictions; Oracle may remove some of these in future releases.
•
Cursor variables cannot be declared in a package since they do not have a persistent state. CREATE PACKAGE emp_stuff AS TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE; emp_cv EmpCurTyp; -- not allowed END emp_stuff;
• • • • • • • •
You cannot use RPCs (Remote Procedure Calls) to pass cursor variables from one server to another. If you pass a cursor variable as a bind or host variable to PL/SQL, you will not be able to fetch from it from within the server unless you also open it in that same server call. The query you associate with a cursor variable in an OPEN-FOR statement cannot use the FOR UPDATE clause. You cannot test for cursor variable equality, inequality, or nullity using comparison operators. You cannot assign NULLs to a cursor variable. Database columns cannot store cursor variable values. You will not be able to use REF CURSOR types to specify column types in statements to CREATE TABLEs or CREATE VIEWs. The elements in a nested table, index-by table, or variable array (VARRAY) cannot store the values of cursor variables. You will not be able to use REF CURSOR types to specify the element type of a collection. Cursor variables cannot be used with dynamic SQL (through use of the DBMS_SQL package).
Can we declare a column having number data type and its scale is larger than pricesion ex: column_name NUMBER(10,100), column_name NUMBAER(10,-84) YES How to disable multiple triggers of a table at at a time? ALTER TABLE DISABLE ALL TRIGGER How to avoid using cursors? What to use instead of cursor and in what cases to do so? Latest Answer: You can use bulk binding to avoid cursors. It improves performance by minimizing context switches sql and pl/sql. When you are hadling large volume of data then better to use bulk binding. ... Read Answers (8) | Asked by : moviefan456 Answer Question
Subscribe
How we can create a table in PL/SQL block. insert records into it??? is it possible by some procedure CREATE OR REPLACE PROCEDURE ddl_create_proc (p_table_name IN VARCHAR2) AS l_stmt VARCHAR2(200); BEGIN DBMS_OUTPUT.put_line('STARTING '); l_stmt := 'create table '|| p_table_name || ' as (select * from emp )'; execute IMMEDIATE l_stmt; DBMS_OUTPUT.put_line('end '); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.put_line('exception '||SQLERRM || 'message'||sqlcode); END; In a Distributed Database System Can we execute two queries simultaneously ? Justify ? As Distributed database system based on 2 phase commit, one query is independent of 2 nd query so of course we can run. If the two queries are firing on the table it is not possible. If the queries are firing on different different tables then it is possible. 1)what is the starting "oracle error number"?2)what is meant by forward declaration in functions? STARTING ORACLE ERROR NO IS ORA-00000: normal, successful completion Forward Declarations: A forward declaration means that modules (procedures and functions) are declared in advance of their actual body definition. This declaration makes that module available to be called by other modules even before the program’s body is defined. A forward declaration consists simply of the module header, which is just the name of the module followed by the parameter list (and a RETURN clause in case the module is a function), no more no less. You cannot make forward declarations of a variable or cursor. This technique works only with modules (procedures and functions). Example of forward Declaration:
CREATE OR REPLACE PACKAGE BODY forward_pack IS PROCEDURE calc_rating(. . .);
-- forward declaration
PROCEDURE award_bonus(. . .) IS
-- subprograms defined
BEGIN
-- in alphabetical order
calc_rating(. . .); ... END; PROCEDURE calc_rating(. . .) IS BEGIN ... END; END forward_pack;
Explian rowid,rownum?what are the psoducolumns we have? Rowid is a unique identifier, hexadecimal string representing the unique address of a row in its table. When a row is inserted into the table it generates a row id and will be removed when the row is deleted. Rownum: For each row returned by a query, the ROWNUM pseudo column returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. You can select from pseudocolumns, but you cannot insert, update, or delete their values. This section describes these pseudocolumns: - CURRVAL and NEXTVAL - LEVEL - ROWID
- ROWNUM What is difference b/w stored procedures and application procedures,stored function and application 1) Stored subprograms: These are coded and compiled from within the Oracle database via SQL Plus etc. 2) Application subprograms: These are coded and compiled from within the Oracle development tools such as Oracle Developer. State the difference between implict and explict cursor's IMPLICIT CURSORS are used primarily when returning a single row of data. With Implicit cursors, the declaration, open, fetch and close functions are done automatically. SELECT column_name INTO :block.field_name FROM table_name; EXPLICIT CURSORS are used, when you are getting more than a single row of data that needs to be processed further. Explicit cursor requires the cursor to be declared, opened, fetched and then closed.
State the advantage and disadvantage of Cursor's The main disadvantage of cursors is that it process records sequentially. It increases number of context switches between sql and pl/sql. It hampers the performance. We may overcome this problem by using collections. How to trace PL/SQL Package? How to trace PL/SQL procedures? How to trace SQL statement? What is DBMS_TRACE? When you want to see the execute plan of a SQL statement, you need to use TRACE function of Oracle. The dbms_trace package provides an API to allow the actions of PL/SQL programs to be traced, where the scope and volume of the tracing is user configurable. This package is loaded by default, but the schema tables to hold the collected data is created by running the $ORACLE_HOME/rdbms/admin/tracetab.sql as the SYS user, shown in the trace_setup.sql script.
How to trace the errors in pl/sql block code..
USER_ERRORS or SHOW ERRORS Else use DBMS_OUTPUT.PUT_LINE What can be the Maximum size of a plsql block? There is no limit on the number of bytes. however, there is a limit on the size of the parse tree generated for your pl/sql code. How to display the contents of a current record fetched in a ref cursor SQL> create or replace function get_emps(dno in number) return sys_refcursor 2 is 3
return_value sys_refcursor;
4 begin 5 6 7
open return_value for select * from emp where deptno = dno; return return_value;
8 end; 9 / Function created. SQL> var rc refcursor SQL> exec :rc := get_emps(30) PL/SQL procedure successfully completed. SQL> print rc
1 What are the advantages and disadvantages of using PL/SQL or JAVA as the primary programming tool for database automation.#2 Will JAVA replace PL/SQL? Internally the Oracle database supports two procedural languages, namely PL/SQL and Java. This leads to questions like "Which of the two is the best?" and "Will Oracle ever desupport PL/SQL in favour of Java?".
Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever desupport PL/SQL. In fact, all indications are that PL/SQL still has a bright future ahead of it. Many enhancements are still being made to PL/SQL. For example, Oracle 9iDB supports native compilation of Pl/SQL code to binaries. PL/SQL and Java appeal to different people in different job roles. The following table briefly describes the difference between these two language environments: PL/SQL: · Data centric and tightly integrated into the database · Proprietary to Oracle and difficult to port to other database systems · Data manipulation is slightly faster in PL/SQL than in Java · Easier to use than Java (depending on your background) Java: · Open standard, not proprietary to Oracle · Incurs some data conversion overhead between the Database and Java type systems · Java is more difficult to use (depending on your background)
How to handle exception in Bulk collector? During bulk collect you can save the exception and then you can process the exception. Look at the below given example: DECLARE
TYPE NumList IS TABLE OF NUMBER;
num_tab NumList := NumList(10,0,11,12,30,0,20,199,2,0,9,1); errors NUMBER; BEGIN FORALL i IN num_tab.FIRST..num_tab.LAST SAVE EXCEPTIONS DELETE * FROM emp WHERE sal > 500000/num_tab(i); EXCEPTION WHEN OTHERS THEN out
-- this is not in the doco, thanks to JL for pointing this
errors := SQL%BULK_EXCEPTIONS.COUNT; dbms_output.put_line('Number of errors is ' || errors); FOR i IN 1..errors LOOP
-- Iteration is
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX;
-- Error code is
SQL%BULK_EXCEPTIONS(i).ERROR_CODE; END LOOP; END; How to view the contents of tables created by the following procedure after the Loop? CREATE OR REPLACE PROCEDURE A0_BULK_COLLECT_TEST IS TYPE EMPLOYEE_MRNO IS TABLE OF A_REGISTRATION_HEADER.ARH_MR_NUM%TYPE; TYPE EMPLOYEE_NAME IS TABLE OF VARCHAR2(255); MRNUMBERS EMPLOYEE_MRNO; NAMES EMPLOYEE_NAME; CURSOR crBulkCollect IS SELECT ARH_MR_NUM, ARH_FIRST_NAME||' '||ARH_MIDDLE_NAME||' '||ARH_LAST_NAME FROM A_REGISTRATION_HEADER WHERE ARH_CTGRY_CD='EMP'; BEGIN OPEN crBulkCollect; FETCH crBulkCollect BULK COLLECT INTO MRNUMBERS, NAMES; CLOSE crBulkCollect; END;
FOR ALL j IN 1..MRNUMBERS.COUNT dbms_output.put_line(MRNUMBERS(j)); dbms_output.put_line(NAMES(j)); What is HIGH WATERMARK?I got to know that it is reset when the TRUNCATE command is executed on a table. All Oracle segments have an upper boundary containing the data within the segment. This upper boundary is called the "High Water Mark" or HWM, which means table, cannot contain data beyond the HWM. When TRUNCATE is used on the table, all the rows of that table is deleted and the HWM is decreased to the minimum size. But when DELETE is issued on the table, the rows are deleted
and nothing is done on the HWM. Thats is, the HWM is never decreased even after the no of rows for the table is less or none. That is this keeps some space always with its own. Other reated issue on this is.... When your query perform full table scan on the table on which the DELETE is done, the query will scan the disk space till the HWM (even if there is no row ) which will result in bad response time.... But if TRUNCATE is used, the HWM will be reset and the query will take less time... What is pragma? can any one give me the example of autonomous Transaction ?can we change the order of procedure parameter while calling procedure? Pragama is compile directive . Example of Autonomous transactions Suppose you are updating value from table and you don't have update trigger on that table but still you want to maintain a log entry for this update in seprate table. You can write a procedure and call that procedure to do this . But you can not use COMMIT in this called procedure because it will save the entire transaction. To avoid this you can declare this procedure as autonomous transaction procedure so that the execution of this procedure will be treated as totally diff. transaction and you can issue commit in called procedure without affecting the main transaction. Can we use commit in trigger and cursors? Yes we write commit on trriger but only in autonomous transaction only Yes We can use commit statement in triggers with 10G. Here is example : CREATE OR REPLACE TRIGGER t_trigger AFTER INSERT ON t1 FOR EACH ROW DECLARE PRAGMA AUTONOMOUS_TRANSACTION; i PLS_INTEGER; BEGIN SELECT COUNT(*) INTO i FROM t1; INSERT INTO t2 VALUES (i); COMMIT; END; /
Difference between truncate and delete DELETE 1. 2. 3. 4. 5. 6.
Delete creates a rollback segment and can be rollback. It is DML statement. Delete command deletes records one by one Delete allows conditional remove of records Trigger fires on delete statement Does not reset the High Watermark of the table.
TRUNCATE 1. 2. 3. 4. 5. 6.
Truncate is a DDL statement. Cannot be rollback. Truncate removes all the records at a time. Truncate does not allow conditional remove of records Trigger do not fires on truncate statement. It also resets the HIGH WATERMARK which will improve subsequent query performance.
What is Mutation of a trigger? why and when does it oocur? When a trigger tries to access its own table, from which its fired, then the trigger is said to be mutating and table is mutating table. Why do we need to create a force view?what is its purpose?give some examples? Force View does forces the creation of a View even when the View will be invalid. NoForce Is the default. When a view is created for base table which does not exist then in that situation we use FORCE. CREATE FORCE VIEW view_force AS SELECT * FROM xyz; Where xyz does not exist. The force view scripts are reusable in data warehousing environments where migration of data from one db to other wills occurs, so they use the same script in diff databases even if the base table may be created afterwards. What is the data type of Null? Oracle treats NULL as character value of length of 0. So, the default data type of NULL is a character data type and to prove it, we create a view on a null column with an alias a, and then describe it to see the datatype and length of the string. Here is the code..... create view myview
as select null a from dual; describe myview; The describe command shows that the column a has a data type of a varchar2(0). So the Answer is : Character Type
What is the purpose of FORCE while creating a VIEW The purpose of FORCE keyword is to create a view if the underlying base table doesnot exists. ex : create or replace FORCE view as That View will be created with the message View created with compilation errors Once you create the table that invalid view will become as valid one. How can I speed up the execution of query when number of rows in the tables increased . Indexed the columns (Primary key) 2. Use the indexed / Primary key columns in the where clause 3. check the explain paln for the query and avoid for the nested loops / full table scan (depending on the size of data retrieved and / or master table with few rows) 4. YOU CAN SPEED UP THE QUERY BY USING THE ROWID IN THE SELECT STATEMENT.
What is autonomous Transaction? Where are they used? Autonomous transaction is the transaction which acts independantly from the calling part and could commit the process done. Autonomous_transcation is used to create a new session. It is more useful when you want to have log like: You want when ever update statement is fired on emp table. You want a entry should be made in logfile that emptable is attempted to update no matter updation was successful or not
CREATE TABLE EMPLOG(TERMINAL_NAME VARCHAR2(50), UPDATE_DATE DATE); CREATE OR REPLACE TRIGGER UPDATE_EMP_TRIG BEFORE UPDATE ON EMP DECLARE
RMSG VARCHAR2(50) ; PRAGAMA AUTONOMOUS_TRANSACTION; BEGIN SELECT ' EMP TABLE IS UPDATED FROM TERMINAL : '||USERENV('TERMINAL') INTO RMSG FROM DUAL; INSERT INTO EMPLOG VALUES(RMSG, SYSDATE); COMMIT; END; / now if user issues UPDATE EMP SET SAL = SAL + 400 ; ROLLBACK; This query will not effect emp table but "emplog" will have a entry What is the difference between In, Out, InOut Parameters. Can we pass value or reference or both to the In Out Parameter. IN : It is a CONSTANT in the sub-program and u can not modify its value in subits value is modified in the sub-program then it will give a error.
program. if
By default, OUT and IN OUT parameters are passed by value. The values of any IN OUT parameters are copied before the subprogram is executed. During subprogram execution, temporary variables hold the output parameter values. If the subprogram exits normally, these values are copied to the actual parameters. If the subprogram exits with an unhandled exception, the original parameters are unchanged. IN : It is a CONSTANT in the sub-program and u can not modify its value in subits value is modified in the sub-program then it will give a error.
program. if
OUT: the out parameter will always have a NULL value during the begining of the sub-program, we can modify its value in the sub-program and then this modified value can be sent to the calling program. Suppose from calling evironment u are sending a variable which has some value to the sub-program, but if that corresponding variable is mrked as OUT in the subprogram, then in the sub-program that value will be replaced with NULL, and then the operation in the sub-program will be done. NOTE: this behaviour can be changed using the NOCOPY option, but remmeber the restriction imposed on NOPCOY. IN-OUT: well this is the variable, where u can read the variable and write the variable.
And one more thing to note is that, for OUT and IN-OUT the variables will be passed by value. if NOCOPY option is not used, but the restriction with the NOCOPY is that its a hint to the compiler, and not necessary that the compiler will be using it, so be careful while usin the NOCOPY option.
I want to insert the following information in userAction table:Which user execute which query on which date? the user Action table contains the following attributes: USER DATE QUERY please write to me how to resolve this problem? Step 1: Store the query in a variable before executing it. Step 2: Simply insert the above query variable, sysdate and user into the User Action table. Note : User name (person logged in into the application) can be obtained from the session. 1) Why it is recommended to use INOUT instead of OUT parameter type in a procedure?2) What happen if OUT parameter will be useful for returning the value from subprogram, value can be assigned only once and this variable cannot be assigned to another variable.IN OUT parameter will be used to pass the value to subprogram and as well as it can be used to return the value to caller of subprogram. It acts as explicitly declared variable. Therefore it can be assigned value and its value can be assigned to another variable. So IN OUT will be useful than OUT parameter. If nothing is assigned to OUT parameter NULL is returned. How can one view all the procedures, functions, triggers and packages created by the user select object_name, object_type from user_objects where object_type in ('PACKAGE','PROCEDURE','FUNCTION','TRIGGER') What is the difference between User-level, Statement-level and System-level Rollback? Can you please give me example of each? 1. System - level or transaction level Rollback the current transaction entirely on errors. This was the unique behavior of old drivers becauase PG has no savepoint functionality until 8.0. 2. Statement Rollback the current (ODBC) statement on errors (in case of 8.0 or later version servers). The driver calls a SAVEPOINT command just before starting each (ODBC) statement and automatically ROLLBACK to the savepoint on errors or RELEASE it on success. If you expect Oracle-like automatic per statement rollback, please use this level. 3. User Level You can(have to) call some SAVEPOINT commands and rollback to a savepoint on errors by yourself. Please note you have to rollback the current transcation or ROLLBACK to a savepoint on errors (by yourself) to continue the application.
What is the DATATYPE of PRIMARY KEY?is it Binary integer..i'm not sure..1.Varchar2 2.Char 3.Binary integer 4.Number Binary Integer What is a purity level? How it is should be taken into consideration when your writing any database objects i.e., trigger,function, procedure etc., Purity level defines what type of datastructure function reads and modify. Threre are 4 types of purity level 1)WNDS(Write No Database State) 2) RNDS(Read No Database State) 3)WNPS(Write No Package State) 2) RNPS(Read No Package State) For package function , PRAGMA RESTRIC_REFRENCES is required. Ex.
PRAGMA RESTRICT_REFRENCES(functionname,WNPS,RNPS)
What is PL/Sql tables?Is cursor variable store in PL/SQL table? pl/sql table is temparary table which is used to store records temrparaily in PL/SQL Block, whenever block completes execution, table is also finished. Cursor variable doesn't store with pl/sql Table . IT is a pointer to cursor & it is not item, It is dynamic. What is difference between varray and nested table.can u explain in brief and clear my these concepts.also 1. Nested tables are unbounded where as varray has maximun limit. 2. Nested tables are dense intially but can be sparse latter. So you can delete individual elements from nested tables. Varrays are always dense .It is not possible to delete individual elements in varrays. 3. Varrays stores data in-line. Nested tables are stored separately, main table maintains a pointer to nested table. 4. When stored in database varrays retain their order where as nested tables do not. What steps should a programmer should follow for better tuning of the PL/SQL blocks? Difference between procedure and function? What is the use of ref cursor return type? Tuning can be taken care by using the Correct Index on the table.We should not use Not equal to, Distinct on the Indexed columns. 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", "", "!=", "!>", "! create or replace procedure fast_proc is 2 type TObjectTable is table of ALL_OBJECTS%ROWTYPE; 3 ObjectTable$ TObjectTable;
4 5 6 7 8 9 10 11 12 /
begin select * BULK COLLECT INTO ObjectTable$ from ALL_OBJECTS; forall x in ObjectTable$.First..ObjectTable$.Last insert into t1 values ObjectTable$(x) ; end;
. Latest Answer: Hi Meenakshi,It seems that I can get some more detail about TUNING. If I need to tune my query, what are the steps that I need to take....I know nothing about tuning....If you find time, pls give me some idea...Regards,
[email protected] ...