Академический Документы
Профессиональный Документы
Культура Документы
What is SQL?
When a user wants to get some information from a database file, he can issue a query. A query is a user request to retrieve data or information with a certain condition. SQL is a query language that allows user to specify the conditions.
General Structure
SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ; col1], col2] FROM tablename WHERE condition
DISTINCT will eliminate duplication in the output while ALL will keep all duplicated rows. condition can be : (1) an inequality, or (2) a string comparison using logical operators AND, OR, NOT.
Grouping
SELECT ...... FROM ...... WHERE condition ; GROUP BY groupexpr [HAVING requirement] requirement] Group functions: COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )
groupexpr specifies the related rows to be grouped as one entry. Usually it is a column. WHERE condition specifies the condition of individual rows before the rows are group. HAVING requirement specifies the condition involving the whole group.
Natural Join
A Natural Join is a join operation that joins two tables by their common column. This operation is similar to the setting relation of two tables.
SELECT a.comcol, a.col1, b.col2, expr1, expr2 ; a.col1, b.col2, expr1, FROM table1 a, table2 b ; WHERE a.comcol = b.comcol a.comcol b.comcol
Outer Join
An Outer Join is a join operation that includes rows that have a match, plus rows that do not have a match in the other table.
PL/SQL Blocks
PL/SQL code is built of Blocks, with a unique structure. There are two types of blocks in PL/SQL:
1. Anonymous Blocks: have no name (like scripts)
2. Named Blocks:
Procedures Functions
EXCEPTION (optional)
/* Here you define the actions that take place if an exception is thrown during the run of this block */
END; /
(mandatory)
A correct completion of a block will generate the following message: PL/SQL procedure successfully completed
Always put a new line with only a / at the end of a block! (This tells Oracle to run the block)
Creating a Cursor
We create a Cursor when we want to go over a result of a query (like ResultSet in JDBC) Syntax Example: DECLARE cursor c is select * from sailors; sailorData sailors%ROWTYPE; BEGIN open c; fetch c into sailorData;
sailorData is a variable that can hold a ROW from the sailors table
Description Evaluates to TRUE if the cursor is open. Evaluates to TRUE if the most recent fetch does not return a row. Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND Evaluates to the total number of rows returned so far.
%ROWCOUNT
Number
Printing Output
You need to use a function in the DBMS_OUTPUT package in order to print to the output If you want to see the output on the screen, you must type the following (before starting):
set serveroutput on format wrapped size 1000000
Trapping Exceptions
Here we define the actions that should happen when an exception is thrown. Example Exceptions:
NO_DATA_FOUND TOO_MANY_ROWS ZERO_DIVIDE
DECLARE num_row number_table%ROWTYPE; BEGIN select * into num_row from number_table; dbms_output.put_line(1/num_row.num); EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line('No data!'); WHEN TOO_MANY_ROWS THEN dbms_output.put_line('Too many!'); WHEN OTHERS THEN dbms_output.put_line(Error); end;
User-Defined Exception
DECLARE e_number1 EXCEPTION; cnt NUMBER; BEGIN select count(*) into cnt from number_table; IF cnt = 1 THEN RAISE e_number1; ELSE dbms_output.put_line(cnt); END IF; EXCEPTION WHEN e_number1 THEN dbms_output.put_line('Count = 1'); end;
Creating a Function
Almost exactly like creating a procedure, but you supply a return type
CREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] RETURN datatype IS|AS PL/SQL Block;
Triggers
Triggers are special procedures which we want activated when someone has performed some action on the DB. For example, we might define a trigger that is executed when someone attempts to insert a row into a table, and the trigger checks that the inserted data is valid.
Trigger types
1) Row level trigger - An event is triggered for each row upated, inserted or deleted. 2) Statement level trigger - An event is triggered for each sql statement executed.
Trigger Syntax
CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) BEGIN
--- sql statements
END;
1) BEFORE UPDATE, Statement Level: This trigger will insert a record into the table 'product_check' before a sql update statement is executed, at the statement level. CREATE or REPLACE TRIGGER Before_Update_Stat_product BEFORE UPDATE ON product Begin INSERT INTO product_check Values('Before update, statement level',sysdate); END; /
2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table 'product_check' before each row is updated. CREATE or REPLACE TRIGGER Before_Upddate_Row_product BEFORE UPDATE ON product FOR EACH ROW BEGIN INSERT INTO product_check Values('Before update row level',sysdate); END; /
Obtain info of http request Generates HTTP Headers And Browser cookies
invoke a PL/SQL stored subprogram through an HTTP listener MOD_PLSQL was formerly called the Oracle PL/SQL Cartridge and OWA (Oracle Web Agent). mod_plsql maps Web client requests to PL/SQL stored subprograms over HTTP The mod_plsql plug-in enables you to use PL/SQL stored subprograms to process HTTP requests and generate responses
CREATE OR REPLACE PROCEDURE IS CURSOR emp_cursor IS SELECT last_name, first_name FROM hr.employees ORDER BY last_name; BEGIN HTP.PRINT('<html>'); HTP.PRINT('<head>'); HTP.PRINT('<meta http-equiv="Content-Type" content="text/html">'); HTP.PRINT('<title>List of Employees</title>'); HTP.PRINT('</head>'); HTP.PRINT('<body TEXT="#000000" BGCOLOR="#FFFFFF">'); HTP.PRINT('<h1>List of Employees</h1>'); HTP.PRINT('<table width="40%" border="1">'); HTP.PRINT('<tr>'); HTP.PRINT('<th align="left">Last Name</th>'); HTP.PRINT('<th align="left">First Name</th>'); HTP.PRINT('</tr>'); FOR emp_record IN emp_cursor LOOP HTP.PRINT('<tr>'); HTP.PRINT('<td>' || emp_record.last_name || '</td>'); HTP.PRINT('<td>' || emp_record.first_name || '</td>'); END LOOP; HTP.PRINT('</table>'); HTP.PRINT('</body>'); HTP.PRINT('</html>'); END;
print_employees
http://host:port/plsql/print_employees http://example.com:8080/plsql/print_employ ees The Web browser returns an HTML page with a table that includes the first and last name of every employee in the hr.employees table.
Questions / Discussions?