What is PL/SQL and what is it used for?
PL/SQL
is Oracle's Procedural Language
extension to SQL. PL/SQL's language syntax,
structure and data types are similar to that of ADA. The PL/SQL language
includes object oriented programming techniques such as encapsulation, function
overloading, information hiding (all but inheritance). PL/SQL is commonly used
to write data-centric programs to manipulate data in an Oracle database.
Should one use PL/SQL or Java to code procedures and triggers?
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 can one see if somebody modified any code?
Code
for stored procedures, functions and packages is stored in the Oracle Data
Dictionary. One can detect code changes by looking at the LAST_DDL_TIME column
in the USER_OBJECTS dictionary view. Example:
SELECT OBJECT_NAME,
TO_CHAR(CREATED, 'DD-Mon-RR HH24:MI') CREATE_TIME,
TO_CHAR(LAST_DDL_TIME, 'DD-Mon-RR HH24:MI') MOD_TIME,
STATUS
FROM USER_OBJECTS
WHERE LAST_DDL_TIME > '&CHECK_FROM_DATE';
How can one search PL/SQL code for a string/ key value?
The
following query is handy if you want to know where a certain table, field or
expression is referenced in your PL/SQL source code.
SELECT TYPE, NAME, LINE
FROM USER_SOURCE
WHERE UPPER(TEXT) LIKE '%&KEYWORD%';
How can one keep a history of PL/SQL code changes?
One
can build a history of PL/SQL code changes by setting up an AFTER CREATE schema
(or database) level trigger (available from Oracle 8.1.7). This way one can
easily revert to previous code should someone make any catastrophic changes.
Look at this example:
CREATE TABLE SOURCE_HIST -- Create history table
AS SELECT SYSDATE CHANGE_DATE, USER_SOURCE.*
FROM USER_SOURCE WHERE 1=2;
CREATE OR REPLACE TRIGGER change_hist -- Store code in hist table
AFTER CREATE ON SCOTT.SCHEMA -- Change SCOTT to your schema name
DECLARE
BEGIN
if DICTIONARY_OBJ_TYPE in ('PROCEDURE', 'FUNCTION',
'PACKAGE', 'PACKAGE BODY', 'TYPE') then
-- Store old code in SOURCE_HIST table
INSERT INTO SOURCE_HIST
SELECT sysdate, user_source.* FROM USER_SOURCE
WHERE TYPE = DICTIONARY_OBJ_TYPE
AND NAME = DICTIONARY_OBJ_NAME;
end if;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20000, SQLERRM);
END;
/
show errors
How can I protect my PL/SQL source code?
PL/SQL
V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs
to protect the source code.
This is
done via a standalone utility that transforms the PL/SQL source code into
portable binary object code (somewhat larger than the original). This way you
can distribute software without having to worry about exposing your proprietary
algorithms and methods. SQL*Plus and SQL*DBA will still understand and know how
to execute such scripts. Just be careful, there is no "decode" command
available.
The syntax
is:
wrap iname=myscript.sql oname=xxxx.plb
Can one print to the screen from PL/SQL?
One
can use the DBMS_OUTPUT package to write information to an output buffer. This
buffer can be displayed on the screen from SQL*Plus if you issue the SET SERVEROUTPUT ON;
command. For example:
set serveroutput on
begin
dbms_output.put_line('Look Ma, I can print from PL/SQL!!!');
end;
/
DBMS_OUTPUT
is useful for debugging PL/SQL programs. However, if you print too much, the
output buffer will overflow. In that case, set the buffer size to a larger
value, eg.: set serveroutput on size 200000
If you
forget to set serveroutput on type SET SERVEROUTPUT ON once you
remember, and then EXEC NULL;. If you haven't cleared the DBMS_OUTPUT
buffer with the disable or enable procedure, SQL*Plus will display the entire
contents of the buffer when it executes this dummy PL/SQL block.
Note that
DBMS_OUTPUT doesn't print blank or NULL lines. To overcome this problem, SET
SERVEROUTPUT ON FORMAT WRAP; Look at this example with this option first
disabled and then enabled:
SQL> SET SERVEROUTPUT ON
SQL> begin
2 dbms_output.put_line('The next line is blank');
3 dbms_output.put_line('');
4 dbms_output.put_line('The above line should be blank');
5 end;
6 /
The next line is blank
The above line should be blank
SQL> SET SERVEROUTPUT ON FORMAT WRAP
SQL> begin
2 dbms_output.put_line('The next line is blank');
3 dbms_output.put_line('');
4 dbms_output.put_line('The above line should be blank');
5 end;
6 /
The next line is blank
The above line should be blank
Can one read/write files from PL/SQL?
Included
in Oracle 7.3 is an UTL_FILE package that can read and write operating system
files. The directory you intend writing to has to be in your INIT.ORA file (see
UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file
was to use DBMS_OUTPUT with the SQL*Plus SPOOL command.
Copy this
example to get started:
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN('/tmp', 'myfile', 'w');
UTL_FILE.PUTF(fileHandler, 'Look ma, I''m writing to a file!!!\n');
UTL_FILE.FCLOSE(fileHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, 'ERROR: Invalid path for file or path not in INIT.ORA.');
END;
/
Can one call DDL statements from PL/SQL?
One
can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using
the "EXECUTE IMMEDATE" statement. Users running Oracle versions below
8i can look at the DBMS_SQL package (see FAQ about Dynamic SQL).
begin
EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)';
end;
NOTE:
The DDL statement in quotes should not be terminated with a semicolon.
Can one use dynamic SQL statements from PL/SQL?
Starting
from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to
execute dynamic SQL and PL/SQL statements (statements created at run-time).
Look at these examples. Note that statements are NOT terminated by semicolons:
EXECUTE IMMEDIATE 'CREATE TABLE x (a NUMBER)';
-- Using bind variables...
sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)';
EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;
-- Returning a cursor...
sql_stmt := 'SELECT * FROM emp WHERE empno = :id';
EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;
One
can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements.
Look at these examples:
CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
More
complex DBMS_SQL example using bind variables:
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
v_cursor integer;
v_dname char(20);
v_rows integer;
BEGIN
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x', DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
v_rows := DBMS_SQL.EXECUTE(v_cursor);
loop
if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then
exit;
end if;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname);
end loop;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
when others then
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '||sqlerrm);
END;
/
What is the difference between %TYPE and %ROWTYPE?
The
%TYPE and %ROWTYPE constructs provide data independence, reduces maintenance
costs, and allows programs to adapt as the database changes to meet new
business needs.
%ROWTYPE
is used to declare a record with the same types as found in the
specified database table, view or cursor. Example:
DECLARE
v_EmpRecord emp%ROWTYPE;
%TYPE is
used to declare a field with the same type as that of a specified
table's column. Example:
DECLARE
v_EmpNo emp.empno%TYPE;
What is the result of comparing NULL with NULL?
NULL
is neither equal to NULL, nor it is not equal to NULL. Any comparison to NULL
is evaluated to NULL. Look at this code example to convince yourself.
declare
a number := NULL;
b number := NULL;
begin
if a=b then
dbms_output.put_line('True, NULL = NULL');
elsif a<>b then
dbms_output.put_line('False, NULL <> NULL');
else
dbms_output.put_line('Undefined NULL is neither = nor <> to NULL');
end if;
end;
How does one get the value of a sequence into a PL/SQL variable?
As
you might know, one cannot use sequences directly from PL/SQL. Oracle (for some
silly reason) prohibits this:
i := sq_sequence.NEXTVAL;
However,
one can use embedded SQL statements to obtain sequence values:
select sq_sequence.NEXTVAL into :i from dual;
Can one execute an operating system command from PL/SQL?
There
is no direct way to execute operating system commands from PL/SQL in Oracle7.
However, one can write an external program (using one of the precompiler
languages, OCI or Perl with Oracle access modules) to act as a listener on a
database pipe (SYS.DBMS_PIPE). Your PL/SQL program then put requests to run
commands in the pipe, the listener picks it up and run the requests. Results
are passed back on a different database pipe. For an Pro*C example, see chapter
8 of the Oracle Application Developers Guide.
In Oracle8
one can call external 3GL code in a dynamically linked library (DLL or shared
object). One just write a library in C/ C++ to do whatever is required. Defining
this C/C++ function to PL/SQL makes it executable.
How does one loop through tables in PL/SQL?
Look
at the following nested loop code example.
DECLARE
CURSOR dept_cur IS
SELECT deptno
FROM dept
ORDER BY deptno;
-- Employee cursor all employees for a dept number
CURSOR emp_cur (v_dept_no DEPT.DEPTNO%TYPE) IS
SELECT ename
FROM emp
WHERE deptno = v_dept_no;
BEGIN
FOR dept_rec IN dept_cur LOOP
dbms_output.put_line('Employees in Department '||TO_CHAR(dept_rec.deptno));
FOR emp_rec in emp_cur(dept_rec.deptno) LOOP
dbms_output.put_line('...Employee is '||emp_rec.ename);
END LOOP;
END LOOP;
END;
/
How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy?
Contrary
to popular believe, one should COMMIT less frequently within a PL/SQL
loop to prevent ORA-1555 (Snapshot too old) errors. The higher the frequency of
commit, the sooner the extents in the rollback segments will be cleared for new
transactions, causing ORA-1555 errors.
To fix
this problem one can easily rewrite code like this:
FOR records IN my_cursor LOOP
...do some stuff...
COMMIT;
END LOOP;
COMMIT;
...
to ...
FOR records IN my_cursor LOOP
...do some stuff...
i := i+1;
IF mod(i, 10000) = 0 THEN -- Commit every 10000 records
COMMIT;
END IF;
END LOOP;
COMMIT;
If
you still get ORA-1555 errors, contact your DBA to increase the rollback
segments.
NOTE: Although fetching
across COMMITs work with Oracle, is not supported by the ANSI standard.
I can SELECT from SQL*Plus but not from PL/SQL. What is wrong?
PL/SQL
respect object privileges given directly to the user, but does not observe
privileges given through roles. The consequence is that a SQL statement can
work in SQL*Plus, but will give an error in PL/SQL. Choose one of the following
solutions:
- Grant direct access on the tables to your user. Do not use roles!
· GRANT select ON scott.emp TO my_user;
- Define your procedures with invoker rights (Oracle 8i and higher);
- Move all the tables to one user/schema.
What is a mutating and constraining table?
"Mutating"
means "changing". A mutating table is a table that is currently being
modified by an update, delete, or insert statement. When a trigger tries to
reference a table that is in state of flux (being changed), it is considered
"mutating" and raises an error since Oracle should not return data
that has not yet reached its final state.
Another
way this error can occur is if the trigger has statements to change the
primary, foreign or unique key columns of the table off which it fires. If you
must have triggers on tables that have referential constraints, the workaround
is to enforce the referential integrity through triggers as well.
There are
several restrictions in Oracle regarding triggers:
- A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD still can be accessed by the trigger) .
- A statement-level trigger cannot query or modify a mutating table if the trigger is fired as the result of a CASCADE delete.
- Etc.
Can one pass an object/table as an argument to a remote procedure?
The
only way to reference an object type between databases is via a database link.
Note that it is not enough to just use "similar" type definitions.
Look at this example:
-- Database A: receives a PL/SQL table from database B
CREATE OR REPLACE PROCEDURE pcalled(TabX DBMS_SQL.VARCHAR2S) IS
BEGIN
-- do something with TabX from database B
null;
END;
/
-- Database B: sends a PL/SQL table to database A
CREATE OR REPLACE PROCEDURE pcalling IS
TabX DBMS_SQL.VARCHAR2S@DBLINK2;
BEGIN
pcalled@DBLINK2(TabX);
END;
/
Is it better to put code in triggers or procedures? What is the difference?
In
earlier releases of Oracle it was better to put as much code as possible in
procedures rather than triggers. At that stage procedures executed faster than
triggers as triggers had to be re-compiled every time before executed (unless
cached). In more recent releases both triggers and procedures are compiled when
created (stored p-code) and one can add as much code as one likes in either
procedures or triggers.
Is there a PL/SQL Engine in SQL*Plus?
No.
Unlike Oracle Forms, SQL*Plus does not have an embedded PL/SQL engine. Thus,
all your PL/SQL code is sent directly to the database engine for execution.
This makes it much more efficient as SQL statements are not stripped off and
sent to the database individually.
Is there a limit on the size of a PL/SQL block?
Yes,
the max size is not an explicit byte limit, but related to the parse tree that
is created when you compile the code. You can run the following select
statement to query the size of an existing package or procedure:
SQL> select * from dba_object_size where name = 'procedure_name';
Which of the following statements is true
about implicit cursors?
- Implicit cursors are used for SQL statements that are not named.
- Developers should use implicit cursors with great care.
- Implicit cursors are used in cursor for loops to handle data processing.
- Implicit cursors are no longer a feature in Oracle.
Which of the following is not a feature of
a cursor FOR loop?
- Record type declaration.
- Opening and parsing of SQL statements.
- Fetches records from cursor.
- Requires exit condition to be defined.
A developer would like to use referential
datatype declaration on a variable. The variable name is EMPLOYEE_LASTNAME, and
the corresponding table and column is EMPLOYEE, and LNAME, respectively. How
would the developer define this variable using referential datatypes?
- Use employee.lname%type.
- Use employee.lname%rowtype.
- Look up datatype for EMPLOYEE column on LASTNAME table and use that.
- Declare it to be type LONG.
Which three of the following are implicit
cursor attributes?
- %found
- %too_many_rows
- %notfound
- %rowcount
- %rowtype
If left out, which of the following would
cause an infinite loop to occur in a simple loop?
- LOOP
- END LOOP
- IF-THEN
- EXIT
Which line in the following statement will
produce an error?
- cursor action_cursor is
- select name, rate, action
- into action_record
- from action_table;
- There are no errors in this statement.
The command used to open a CURSOR FOR loop
is
- open
- fetch
- parse
- None, cursor for loops handle cursor opening implicitly.
What happens when rows are found using a
FETCH statement
- It causes the cursor to close
- It causes the cursor to open
- It loads the current row values into variables
- It creates the variables to hold the current row values
Read the following code:
CREATE OR REPLACE PROCEDURE find_cpt
(v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)
IS
BEGIN
IF v_cost_per_ticket > 8.5 THEN
SELECT cost_per_ticket
INTO v_cost_per_ticket
FROM gross_receipt
WHERE movie_id = v_movie_id;
END IF;
END;
Which
mode should be used for V_COST_PER_TICKET?
- IN
- OUT
- RETURN
- IN OUT
Read the following code:
CREATE OR REPLACE TRIGGER update_show_gross
{trigger information}
BEGIN
{additional code}
END;
The
trigger code should only execute when the column, COST_PER_TICKET, is greater
than $3. Which trigger information will you add?
- WHEN (new.cost_per_ticket > 3.75)
- WHEN (:new.cost_per_ticket > 3.75
- WHERE (new.cost_per_ticket > 3.75)
- WHERE (:new.cost_per_ticket > 3.75)
What is the maximum number of handlers
processed before the PL/SQL block is exited when an exception occurs?
- Only one
- All that apply
- All referenced
- None
For which trigger timing can you reference
the NEW and OLD qualifiers?
- Statement and Row
- Statement only
- Row only
- Oracle Forms trigger
Read the following code:
CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
RETURN number IS
v_yearly_budget NUMBER;
BEGIN
SELECT yearly_budget
INTO v_yearly_budget
FROM studio
WHERE id = v_studio_id;
RETURN v_yearly_budget;
END;
Which
set of statements will successfully invoke this function within SQL*Plus?
- VARIABLE g_yearly_budget NUMBER
EXECUTE g_yearly_budget := GET_BUDGET(11); - VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11); - VARIABLE :g_yearly_budget
NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11); - VARIABLE g_yearly_budget NUMBER
:g_yearly_budget := GET_BUDGET(11);
CREATE OR REPLACE PROCEDURE update_theater
(v_name IN VARCHAR v_theater_id IN NUMBER) IS
BEGIN
UPDATE theater
SET name = v_name
WHERE id = v_theater_id;
END update_theater;
When
invoking this procedure, you encounter the error:
ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.
How
should you modify the function to handle this error?
- An user defined exception must be declared and associated with the error code and handled in the EXCEPTION section.
- Handle the error in EXCEPTION section by referencing the error code directly.
- Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception.
- Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.
Read the following code:
CREATE OR REPLACE PROCEDURE calculate_budget IS
v_budget studio.yearly_budget%TYPE;
BEGIN
v_budget := get_budget(11);
IF v_budget < 30000
THEN
set_budget(11,30000000);
END IF;
END;
You are about to add an argument to
CALCULATE_BUDGET. What effect will this have?
- The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.
- The SET_BUDGET function will be marked invalid and must be recompiled before the next execution.
- Only the CALCULATE_BUDGET procedure needs to be recompiled.
- All three procedures are marked invalid and must be recompiled.
Which procedure can be used to create a
customized error message?
- RAISE_ERROR
- SQLERRM
- RAISE_APPLICATION_ERROR
- RAISE_SERVER_ERROR
The CHECK_THEATER trigger of the THEATER
table has been disabled. Which command can you issue to enable this trigger?
- ALTER TRIGGER check_theater ENABLE;
- ENABLE TRIGGER check_theater;
- ALTER TABLE check_theater ENABLE check_theater;
- ENABLE check_theater;
Examine this database trigger
CREATE OR REPLACE TRIGGER prevent_gross_modification
{additional trigger information}
BEGIN
IF TO_CHAR(sysdate, DY) = MON
THEN
RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);
END IF;
END;
This
trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire
only once for the entire DELETE statement. What additional information must you
add?
- BEFORE DELETE ON gross_receipt
- AFTER DELETE ON gross_receipt
- BEFORE (gross_receipt DELETE)
- FOR EACH ROW DELETED FROM gross_receipt
Examine this function:
CREATE OR REPLACE FUNCTION set_budget
(v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS
BEGIN
UPDATE studio
SET yearly_budget = v_new_budget
WHERE id = v_studio_id;
IF SQL%FOUND THEN
RETURN TRUEl;
ELSE
RETURN FALSE;
END IF;
COMMIT;
END;
Which
code must be added to successfully compile this function?
- Add RETURN right before the IS keyword.
- Add RETURN number right before the IS keyword.
- Add RETURN boolean right after the IS keyword.
- Add RETURN boolean right before the IS keyword.
Under which circumstance must you
recompile the package body after recompiling the package specification?
- Altering the argument list of one of the package constructs
- Any change made to one of the package constructs
- Any SQL statement change made to one of the package constructs
- Removing a local variable from the DECLARE section of one of the package constructs
Procedure and Functions are explicitly
executed. This is different from a database trigger. When is a database trigger
executed?
- When the transaction is committed
- During the data manipulation statement
- When an Oracle supplied package references the trigger
- During a data manipulation statement and when the transaction is committed
Which Oracle supplied package can you use
to output values and messages from database triggers, stored procedures and
functions within SQL*Plus?
- DBMS_DISPLAY
- DBMS_OUTPUT
- DBMS_LIST
- DBMS_DESCRIBE
What occurs if a procedure or function
terminates with failure without being handled?
- Any DML statements issued by the construct are still pending and can be committed or rolled back.
- Any DML statements issued by the construct are committed
- Unless a GOTO statement is used to continue processing within the BEGIN section, the construct terminates.
- The construct rolls back any DML statements issued and returns the unhandled exception to the calling environment.
Examine this code
BEGIN
theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;
END;
For
this code to be successful, what must be true?
- Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist only in the body of the THEATER_PCK package.
- Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the THEATER_PCK package.
- Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the THEATER_PCK package.
- Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist in the specification of the THEATER_PCK package.
A stored function must return a value
based on conditions that are determined at runtime. Therefore, the SELECT
statement cannot be hard-coded and must be created dynamically when the
function is executed. Which Oracle supplied package will enable this feature?
- DBMS_DDL
- DBMS_DML
- DBMS_SYN
- DBMS_SQL
ans
- 1
2. 2
3. 1
4 .(1,3,4)
5. 2
6. 3
7. 4
8. 2
9. 2
10. (3,4)
11. 1
12. 4
13. 1
14 .1
15. 3
16. 3
17. 1
18. (1,4)
19. 4
20. 3
21. 4
22. 2
23. 4
24. 3
25. 4
- What’s the command to see the current user name? Sql> show user;
- What’s the command to change the SQL prompt name?
SQL>
set sqlprompt “database-1 > ”
database-1 >
database-1 >
database-1 >
database-1 >
- How do you switch to DOS prompt from SQL prompt? SQL> host
- How do I eliminate duplicate rows in an Oracle database?
SQL>
delete from table_name where rowid not in (select max(rowid) from table group
by duplicate_values_field_name);
or
SQL>
delete duplicate_values_field_name dv from table_name ta where rowid <
(select min(rowid) from table_name tb where ta.dv=tb.dv);
- How do I display row number with records? Use the row-num pseudocolumn with query, like
SQL>
select rownum, ename from emp;
- How do you display the records within a given range?
select
rownum, empno, ename from emp where rowid in
(select rowid from emp where rownum < =&rangeend
minus
select rowid from emp where rownum<&rangebegin);
(select rowid from emp where rownum < =&rangeend
minus
select rowid from emp where rownum<&rangebegin);
- The NVL function only allows the same data type. But here’s the task: if the commission field is null, then the text “Not Applicable” should be displayed, instead of blank space. How do you write the query?
SQL>
select nvl(to_char(comm.),’Not Applicable’) from emp;
- Explain explicit cursor attributes. There are four cursor attributes used in Oracle: cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name%ISOPEN
- Explain implicit cursor attributes. Same as explicit cursor but prefixed by the word SQL: SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN
- How do you view version information in Oracle?
SQL>
select banner from $version;
No comments:
Post a Comment