Vous êtes sur la page 1sur 33

Creating a User

Once connected as SYSTEM, to generate a new account, the command used is: CREATE USER

Syntax:
CREATE USER <user name> IDENTIFIED BY <any password>;

Oracle gives various privileges to the users. Mainly two types of privileges are:

System privileges - System wide access - resource, connect, dba, etc.

User Privileges - Grants to specific table data.

To add privileges to the new account, the command is: Grant.


GRANT is a very powerful statement with many possible options, but the core functionality is
to manage the privileges of both users and roles throughout the database.
Providing Roles
One can GRANT or REVOKE privileges on various database objects in Oracle.
Assigning privileges to the user: connect, resource, dba
Syntax: GRANT CONNECT, RESOURCE, DBA TO <user>;
To ensure that the new user has disk space allocated in the system to actually create or modify
tables and data, GRANT TABLESPACE is used.
Syntax: GRANT UNLIMITED TABLESPACE TO <user>;
Default Tablespace <name of the table> (given by default), Temporary Tablespace
Granting Privileges on Table
Granting users various privileges to tables. These privileges can be any combination of SELECT,
INSERT, UPDATE, DELETE, REFERENCES, ALTER, INDEX, or ALL.
Syntax:
GRANT SELECT, INSERT, UPDATE, DELETE ON suppliers TO <user>;

Database Administrator can simply retrieve information about user privileges related to the
system, tables and roles through DBA_SYS_PRIVS, DBA_TAB_PRIVS, and DBA_ROLE_PRIVS
respectively. SELECT * FROM DBA_TAB_PRIVS;
REVOKE
REVOKE statement is used to remove privileges from a specific user or role, or from all users, to
perform actions on database objects.
Revokes privileges already granted to other users.

For example to revoke select, update, insert privileges granted to user1, give the following
statement:

revoke select, update, insert on emp from user1;


Views

• Views are known as logical tables.


• They may represent the data of one of more tables.
• It derives its data from the tables on which it is based. These tables are called base tables.
• Views can be based on actual tables or another view also.
• They are very powerful and handy since they can be treated like any other table but do not
occupy the space of a table.
• It is a predefined query on one or more tables.
• Retrieving information from a view is done in the same manner as retrieving from a table.
• With some views, DML operations (delete, insert, update) can be performed on the base
tables.
• Views don't store data, they only access rows in the base tables.
• It only allows a user to retrieve data.
• By writing complex queries as a view, the complexity can be hidden from an end user.
Creating Views
If we have EMP and DEPT table. To see the empno, ename, sal, deptno, department name and
location we have to give a join query:
select e.empno,e.ename,e.sal,e.deptno,d.dname,d.loc
From emp e, dept d where e.deptno=d.deptno;

So everytime if one wants to see emp details and department names where they are working we
have to give a long join query. Instead of giving this join query again and again, we can create a
view on these table by using the command: CREATE VIEW
Syntax:
create view emp_det as select e.empno, e.ename,e.sal,e.deptno,d.dname,d.loc
from emp e, dept d where e.deptno=d.deptno;

Now to see the employee details and department names instead of giving a join query, one can
just type:
select * from emp_det;
Replacing/Altering Views
• To alter the definition of a view, one must replace the view using one of the following
methods:
• A view can be dropped and then re-created, all grants of corresponding view privileges are
revoked from roles and users.
• A view can be replaced by redefining it with a CREATE VIEW statement that contains the OR
REPLACE option.
• This option replaces the current definition of a view, but preserves the present security
authorizations.
For example, if ACCOUNTS_STAFF view has been created and you realize that you must redefine
the ACCOUNTS_STAFF view to correct the department number specified in the WHERE clause of
the defining query, because it should have been 30, you can replace the current version of the
ACCOUNTS_STAFF view with the following statement:
CREATE OR REPLACE VIEW Accounts_staff AS
SELECT Empno, Ename, Deptno FROM Emp
WHERE Deptno = 30;
To delete a view, use the DROP VIEW command.
Syntax: DROP VIEW view_name
create table Employee
(
ID VARCHAR(4 BYTE) NOT NULL,
First_Name VARCHAR(10 BYTE),
Last_Name VARCHAR(10 BYTE),
Start_Date DATE,
End_Date DATE,
Salary Number(8,2),
City VARCHAR(10 BYTE),
Description VARCHAR(15 BYTE)
)

ID FIRST_NAME LAST_NAME START_DAT END_DATE SALARY CITY DESCRIPTION


---- ---------- ---------- --------- --------- ---------- ---------- ---------------
01 Jason Martin 25-JUL-96 25-JUL-06 1234.56 Toronto Programmer
02 Alison Mathews 21-MAR-76 21-FEB-86 6661.78 Vancouver Tester
03 James Smith 12-DEC-78 15-MAR-90 6544.78 Vancouver Tester
04 Celia Rice 24-OCT-82 21-APR-99 2344.78 Vancouver Manager
05 Robert Black 15-JAN-84 08-AUG-98 2334.78 Vancouver Tester
06 Linda Green 30-JUL-87 04-JAN-96 4322.78 New York Tester
07 David Larry 31-DEC-90 12-FEB-98 7897.78 New York Manager
08 James Cat 17-SEP-96 15-APR-02 1232.78 Vancouver Tester
Creating Index
• An index for a database table is similar in concept to a book index.
• When a row is added to the table, additional time is required to update the index for the new
row.
• Oracle database automatically creates an index for the primary key of a table and for columns
included in a unique constraint.
Syntax:
CREATE [UNIQUE] INDEX index_name ON
table_name(column_name[, column_name...]);

Example:
CREATE INDEX emp_idx ON employee(last_name);
To view the indexes:
SELECT index_name, table_name, column_name
FROM USER_IND_COLUMNS WHERE table_name = 'EMP';
To drop the index:
drop index emp_idx;
Copying a Table

The contents of a table can be copied from one table to the other using the following command:
Syntax:
INSERT INTO <new table name> SELECT * from <old table name>;

Note: The new table should be created already in order to copy the contents from some other
table.
PL/SQL
• PL stands for Procedural Language. PL/SQL is referred to as a block structured language.
• All PL/SQL programs are made up of blocks, which can be nested within each other.
• Each block performs a logical action in the program.
• The subprograms can be either – Functions, procedures and can be grouped into packages.
• PL/SQL also allows access to databases via – Cursors, Triggers, stored procedures and
functions.
• A PL/SQL block is a syntactical unit that might contain program code, variable declarations,
error handlers, procedures, functions, and even other PL/SQL blocks.

Syntax for a PL/SQL Block: DECLARE


variable_declarations
BEGIN
program_code
EXCEPTION
exception_handlers
END;
The declaration section and the exception handler portion of a PL/SQL block are optional.
PL/SQL
• The BEGIN and END keywords delimit the procedural portion of the block.
• The EXCEPTION keyword signifies the end of the main body of code and begins the section
containing exception handling code.
• The semicolon at the end of the block and at the end of each statement, is the PL/SQL
statement terminator that signifies the end of the block.
• PL/SQL blocks can also be nested.
• The slash at the end tells that you are done typing PL/SQL code.
• The code is then transmitted to the Oracle database for execution.
• Oracle has included the DBMS_OUTPUT package with PL/SQL to provide some limited output
capabilities by using the command dbms_output.put_line
• The only SQL statements allowed in a PL/SQL program are SELECT, INSERT, UPDATE, DELETE
and several other.
• The SELECT statement has a special format.
• CREATE, DROP, or ALTER are not allowed.
• PL/SQL is not case sensitive.
• C style comments (/* ... */) or ( -- ….) .
PL/SQL
There are two types of PL/SQL blocks.
1. Anonymous Block - Blocks without names.
2. Named Block (Subprograms) - The procedures & Functions

Anonymous Block:
Block Structure
DECLARE
<Define PL/SQL objects to be used within this block>
BEGIN
<Executable Statements>
EXCEPTION
< Used to trap Predefined error conditions>
END;
Variables and Types
• Information is transmitted between a PL/SQL program and the database through variables.
• Every variable has a specific type associated with it that can be one of the types used by SQL
for database columns.
• PL/SQL also allows BOOLEAN variables.
• The most commonly used generic type is NUMBER.
• Variables of type NUMBER can hold either an integer or a real number.
• The most commonly used character string type is VARCHAR(n), where n is the maximum
length of the string in bytes.
• Any variable declarations must immediately follow DECLARE and come before BEGIN.

For example:
DECLARE
price NUMBER;
myobject VARCHAR(20);
Variables and Types
• Variable types in PL/SQL can be tricky as a variable is used to manipulate data stored in an
existing relation.
• It is essential that the variable has the same type as the relation column.
• If there is any type mismatch, variable assignments and comparisons may not work the way it
is expected. So, to be safe, instead of hard coding the type of a variable, one should use the
%TYPE operator.
For example: DECLARE
myobject Order.name%TYPE;
gives variable myobject whatever type was declared for the name column in relation Order.
A variable may also have a type that is a record with several fields by using %ROWTYPE.
The result is a record type in which the fields have the same names and types as the attributes of
the relation.
For instance: DECLARE
objectuple Order%ROWTYPE;
makes variable objectuple be a record with fields name and manufacturer assuming that the
relation has the schema Order(name, manufacturer).
PL/SQL
• The initial value of any variable, regardless of its type, is NULL.
• Values to the variables can be assigned using the ":=" operator.
• The assignment can occur either immediately after the type of the variable is declared or
anywhere in the executable portion of the program.

Example:
DECLARE
a NUMBER := 3;
BEGIN
a := a + 1;
END;
Anonymous Blocks
DECLARE
x NUMBER;
BEGIN
x := 72600;
dbms_output.put_line('The variable X = ');
dbms_output.put_line(x);
END;
/ Declare
NUM1 number:=20;
NUM2 number:=50;
SUM number:=0;
Begin
SUM := NUM1+NUM2;
dbms_output.put_line (SUM||',');
end;
/
Anonymous Block
CREATE TABLE
T1( e number,
f number );
INSERT INTO T1 VALUES(1, 3);
INSERT INTO T1 VALUES(2, 4);
Select * from T1;

/* Above is plain SQL; below is the PL/SQL program. */


DECLARE
a NUMBER;
b NUMBER;
BEGIN
SELECT e, f INTO a, b FROM T1 WHERE e>1;
INSERT INTO T1 VALUES( b, a);
END;
/
Anonymous Block
DECLARE
v_sal emp.sal%TYPE;
BEGIN
INSERT INTO emp VALUES (6, 'Tomcat', 1000);
UPDATE emp SET sal = sal + 5000 WHERE empno = 6;
SELECT sal INTO v_sal FROM employee WHERE empno = 6;
DBMS_OUTPUT.PUT_LINE('Salary increased to ' || v_sal);
END;
/
Conditions in PL / SQL
PL/SQL allows you to branch and create loops and also put condition using IF statement.

Syntax:
IF <condition> THEN <statement_list> ELSE <statement_list> END IF;

ELSE part is optional. Nested If’s will have the following syntax:

IF <condition_1> THEN ...


ELSIF <condition_2> THEN ...
ELSIF <condition_n> THEN ...
ELSE ...
END IF;
If – Then – Else
DECLARE DECLARE
a NUMBER; grade CHAR(1);
b NUMBER; BEGIN
BEGIN grade := 'B';
SELECT e, f INTO a, b FROM T1 WHERE e>1;
IF b=1 THEN IF grade = 'A' THEN
INSERT INTO T1 VALUES( b, a); DBMS_OUTPUT.PUT_LINE('Excellent');
ELSE ELSIF grade = 'B' THEN
INSERT INTO T1 VALUES(b+10,a+10); DBMS_OUTPUT.PUT_LINE('Very Good');
END IF; ELSIF grade = 'C' THEN
END; DBMS_OUTPUT.PUT_LINE('Good');
ELSIF grade = 'D' THEN
DBMS_OUTPUT. PUT_LINE('Fair');
ELSIF grade = 'F' THEN
DBMS_OUTPUT.PUT_LINE('Poor');
ELSE
DBMS_OUTPUT.PUT_LINE('No such grade');
END IF;
END;
/
Loops
Loops are created with the following syntax:
LOOP
<loop_body> /* A list of statements. */
END LOOP;
At least one of the statements in <loop_body> should be an EXIT statement of the form
EXIT WHEN <condition>; The loop breaks if <condition> is true.

WHILE loop can be formed with: WHILE <condition> LOOP


<loop_body>
END LOOP;
FOR loop can be formed with: FOR <var> IN <start>..<finish> LOOP
<loop_body>
END LOOP;
Here, <var> can be any variable; it is local to the for-loop and need not be declared. Also, <start>
and <finish> are constants.
Loop – Exit When

DECLARE
x NUMBER := 0; DECLARE
BEGIN i NUMBER := 1;
LOOP BEGIN
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' || x); LOOP
x := x + 1; INSERT INTO T1 VALUES(i,i);
IF x > 3 THEN i := i+1;
EXIT; EXIT WHEN i>100;
END IF; END LOOP;
END LOOP; END;
-- After EXIT, control resumes here
DBMS_OUTPUT.PUT_LINE(' After loop: x = ' ||x);
END;
/
Loop - Continue
DECLARE
x NUMBER := 0;
BEGIN
LOOP -- After CONTINUE statement, control resumes here
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' ||x);
x := x + 1;
IF x < 3 THEN
CONTINUE;
END IF;
DBMS_OUTPUT.PUT_LINE
('Inside loop, after CONTINUE: x = ' || x);
EXIT WHEN x = 5;
END LOOP;

DBMS_OUTPUT.PUT_LINE (' After loop: x = ' || x);


END;
/
While - Loop

DECLARE
done BOOLEAN := FALSE;
BEGIN
WHILE done LOOP
DBMS_OUTPUT.PUT_LINE ('This line does not print.');
done := TRUE;
END LOOP;

WHILE NOT done LOOP


DBMS_OUTPUT.PUT_LINE ('Hello, world!');
done := TRUE;
END LOOP;
END;
/
For - Loop
BEGIN
DBMS_OUTPUT.PUT_LINE ('lower_bound < upper_bound');

FOR i IN 1..3 LOOP


DBMS_OUTPUT.PUT_LINE (i);
END LOOP;

DBMS_OUTPUT.PUT_LINE ('lower_bound = upper_bound');

FOR i IN 2..2 LOOP


DBMS_OUTPUT.PUT_LINE (i);
END LOOP;

DBMS_OUTPUT.PUT_LINE ('lower_bound > upper_bound');

FOR i IN 3..1 LOOP


DBMS_OUTPUT.PUT_LINE (i);
END LOOP;
END;
/
For – Loop - GOTO
DECLARE
p VARCHAR2(30);
n PLS_INTEGER := 37;
BEGIN
FOR j in 2..ROUND(SQRT(n)) LOOP
IF n MOD j = 0 THEN
p := ' is not a prime number';
GOTO print_now;
END IF;
END LOOP;

p := ' is a prime number';

<<print_now>>
DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);
END;
/
Named Block
PL / SQL has two types of subprograms
• Procedures
• Functions
Named Block Structure for PL / SQL Subprogram:
(Named Block)
HEADER
IS <Declaration Section>
BEGIN
<Executable Statements>
EXCEPTION
< Used to trap Predefined error conditions>
END;
Procedures
• PL/SQL procedure is a named block that does a specific task.
• It allows you to encapsulate complex business logic and reuse it in both database layer and
application layer.
Syntax:
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
Procedures

CREATE OR REPLACE PROCEDURE adjust_salary(


in_employee_id IN EMPLOYEES.EMPLOYEE_ID%TYPE,
in_percent IN NUMBER
) IS
BEGIN
-- update employee's salary
UPDATE employees
SET salary = salary + salary * in_percent / 100
WHERE employee_id = in_employee_id;
END;
/
Functions
A function is a named PL/SQL Block which is similar to a procedure.
The major difference between a procedure and a function is, a function must always return a
value, but a procedure may or may not return a value.
Syntax:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
Functions
CREATE OR REPLACE FUNCTION employer_details_func
RETURN VARCHAR(20);
IS
emp_name VARCHAR(20);
BEGIN
SELECT first_name INTO emp_name
FROM emp_tbl WHERE empID = '100';
RETURN emp_name;
END;
/
IN and Out Parameters

When you create a function or procedure, you have to define IN/OUT/INOUT


parameters parameters.
IN : IN parameter referring to the procedure or function and allow to overwritten
the value of parameter.
OUT : OUT parameter referring to the procedure or function and allow to
overwritten the value of parameter.
IN OUT : Both IN OUT parameter referring to the procedure or function to pass
both IN OUT parameter, modify/update by the function or procedure and also get
returned.
DECLARE Procedures
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= &n;
b:= &n;
findMin(a, b, c);
dbms_output.put_line(' Minimum of '||a||' and ' ||b ||'is : ' || c);
END;

Vous aimerez peut-être aussi