SlideShare uma empresa Scribd logo
1 de 11
Baixar para ler offline
Oracle/PLSQL: Create a database
CREATE TEMPORARY TABLESPACE TEMP_NEW TEMPFILE
'/DATA/database/ifsprod/temp_01.dbf' SIZE 500m autoextend on next 10m
maxsize unlimited;
CREATE DATABASE mynewdb
USER SYS IDENTIFIED BY sys_password
USER SYSTEM IDENTIFIED BY system_password
EXTENT MANAGEMENT LOCAL
DEFAULT TEMPORARY TABLESPACE temp
UNDO TABLESPACE undotbs1
DEFAULT TABLESPACE users;
Oracle/PLSQL: Create a Schema
Step 1 - Create a new user in Oracle
CREATE USER smithj
IDENTIFIED BY pwd4smithj
DEFAULT TABLESPACE tbs_perm_01
TEMPORARY TABLESPACE tbs_temp_01
QUOTA 20M on tbs_perm_01;
create tablespace
tbs_temp_01
datafile
tbs_temp_01.dbf'
size
50m
autoextend on
next 10m
maxsize 100m;
Step 2 - Assign SYSTEM privileges to new user in Oracle
GRANT create session TO smithj;
GRANT create table TO smithj;
GRANT create view TO smithj;
GRANT create any trigger TO smithj;
GRANT create any procedure TO smithj;
GRANT create sequence TO smithj;
GRANT create synonym TO smithj;
Object can be function or store procedure :
GRANT EXECUTE ON object TO smithj;
REVOKE EXECUTE ON object FROM user;
grant dba to sample_schema ;
grant connect to sample_schema
These new privileges are now granted to the user called smithj.
Step 3 - Create objects in the schema
Step 4 - Grant Object Privileges
After you have created your objects in the schema, you will need to grant privileges so that
other schemas/users can access your database objects (ie: tables).
Step 5 - Create Synonyms for Objects
As a last step, you may want to create synonyms so that other schemas can access the new
database objects (ie: tables) without having to prefix the object names with the schema name.
For example, if you were another user named smithj and wanted to select from the suppliers
table in new_schema, you would have to run the following SELECT statement (before any
synonyms are created):
SELECT *
FROM new_schema.suppliers;
If you then created a synonym for the suppliers table as follows:
CREATE PUBLIC SYNONYM suppliers
FOR new_schema.suppliers;
You could run the SELECT statement as follows:
SELECT *
FROM suppliers;
No longer needing to prefix the table name with the schema name.
Oracle/PLSQL: CREATE USER statement
The syntax for the CREATE USER statement in Oracle/PLSQL is:
CREATE USER user_name
IDENTIFIED { BY password
| EXTERNALLY [ AS 'certificate_DN' ]
| GLOBALLY [ AS '[ directory_DN ]' ]
}
[ DEFAULT TABLESPACE tablespace
| TEMPORARY TABLESPACE
{ tablespace | tablespace_group }
| QUOTA integer [ K | M | G | T | P | E ]
| UNLIMITED }
ON tablespace
[ QUOTA integer [ K | M | G | T | P | E ]
| UNLIMITED }
ON tablespace
]
| PROFILE profile_name
| PASSWORD EXPIRE
| ACCOUNT { LOCK | UNLOCK }
[ DEFAULT TABLESPACE tablespace
| TEMPORARY TABLESPACE
{ tablespace | tablespace_group }
| QUOTA integer [ K | M | G | T | P | E ]
| UNLIMITED }
ON tablespace
[ QUOTA integer [ K | M | G | T | P | E ]
| UNLIMITED }
ON tablespace
]
| PROFILE profile
| PASSWORD EXPIRE
| ACCOUNT { LOCK | UNLOCK } ]
] ;
Parameters or Arguments
Example
If you wanted to execute a simple CREATE USER statement that creates a new user and
assigns a password, you could do the following:
For example:
CREATE USER smithj
IDENTIFIED BY pwd4smithj
DEFAULT TABLESPACE tbs_perm_01
TEMPORARY TABLESPACE tbs_temp_01
QUOTA 20M on tbs_perm_01;
CREATE USER smithj
IDENTIFIED BY pwd4smithj
DEFAULT TABLESPACE tbs_perm_01
TEMPORARY TABLESPACE tbs_temp_01
QUOTA 20M on tbs_perm_01
Oracle/PLSQL: DROP USER statement
DROP USER user_name [ CASCADE ];
DROP USER smithj;
DROP USER smithj CASCADE;
Oracle/PLSQL: Roles
CREATE ROLE role_name
[ NOT IDENTIFIED |
IDENTIFIED {BY password | USING [schema.] package | EXTERNALLY |
GLOBALLY } ;
This first example creates a role called test_role.
CREATE ROLE test_role
IDENTIFIED BY test123;
Grant TABLE Privileges to Role
GRANT privileges ON object TO role_name
GRANT select, insert, update, delete ON suppliers TO test_role;
GRANT all ON suppliers TO test_role;s
Revoke Table Privileges from Role
REVOKE privileges ON object FROM role_name;
REVOKE delete ON suppliers FROM test_role;
REVOKE all ON suppliers FROM test_role;
Grant Function/Procedure Privileges to Role
GRANT EXECUTE ON object TO role_name;
EXECUTE means the following:
Privilege Description
EXECUTE
Ability to compile the function/procedure.
Ability to execute the function/procedure directly.
Revoke Function/Procedure Privileges from Role
REVOKE execute ON object FROM role_name;
Grant Role to User
GRANT role_name TO user_name;
REVOKE role_name FROM user_name;
Enable/Disable Role (Set Role Statement)
SET ROLE
( role_name [ IDENTIFIED BY password ] | ALL [EXCEPT role1, role2, ... ] |
NONE );
For example:
SET ROLE test_role IDENTIFIED BY test123;
Set role as DEFAULT Role
ALTER USER user_name
DEFAULT ROLE
( role_name | ALL [EXCEPT role1, role2, ... ] | NONE );
Example
Let's look at an example of how to set a role as a DEFAULT ROLE in Oracle.
For example:
ALTER USER smithj
DEFAULT ROLE
test_role;
Drop Role
DROP ROLE role_name;
Oracle/PLSQL: Procedures
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Example
CREATE OR REPLACE Procedure UpdateCourse
( name_in IN varchar2 )
IS
cnumber number;
cursor c1 is
SELECT course_number
FROM courses_tbl
WHERE course_name = name_in;
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
INSERT INTO student_courses
( course_name,
course_number )
VALUES
( name_in,
cnumber );
commit;
close c1;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||'
-ERROR- '||SQLERRM);
END;
--------------------------------------------------------------------
CREATE OR REPLACE PROCEDURE getDBUSERByUserId(
p_userid IN DBUSER.USER_ID%TYPE,
o_username OUT DBUSER.USERNAME%TYPE,
o_createdby OUT DBUSER.CREATED_BY%TYPE,
o_date OUT DBUSER.CREATED_DATE%TYPE)
IS
BEGIN
SELECT USERNAME , CREATED_BY, CREATED_DATE
INTO o_username, o_createdby, o_date
FROM DBUSER WHERE USER_ID = p_userid;
END;
++++++++++++++++++++++++++++
DECLARE
o_username DBUSER.USERNAME%TYPE;
o_createdby DBUSER.CREATED_BY%TYPE;
o_date DBUSER.CREATED_DATE%TYPE;
BEGIN
getDBUSERByUserId(1001,o_username,o_createdby,o_date);
DBMS_OUTPUT.PUT_LINE('username : ' || o_username);
DBMS_OUTPUT.PUT_LINE('createdby : ' || o_createdby);
DBMS_OUTPUT.PUT_LINE('createddate : ' || o_date);
END;
--------------------------------------------------------------------
1> CREATE OR REPLACE PROCEDURE employer_details
2> IS
3> CURSOR emp_cur IS
4> SELECT first_name, last_name, salary FROM emp_tbl;
5> emp_rec emp_cur%rowtype;
6> BEGIN
7> FOR emp_rec in sales_cur
8> LOOP
9> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
10> || ' ' ||emp_cur.salary);
11> END LOOP;
12>END;
13> /
--------------------------------------------------------------------
CREATE PROCEDURE GET_ONESET_CUSTOMERINFO
(
P_CREDITLINEAMOUNT IN INTEGER,
CURSOR_ IN OUT TYPES.REF_CURSOR
)
AS
BEGIN
OPEN CURSOR_ FOR
SELECT * FROM CROSSSELLCUSTOMERS
WHERE CREDITLINEAMOUNT >= P_CREDITLINEAMOUNT;
END;
Oracle/PLSQL: Functions
CREATE [OR REPLACE] FUNCTION function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [function_name];
CREATE OR REPLACE FUNCTION show_employee_salary(dnum NUMBER) RETURN
NUMBER
IS
CURSOR emp_cursor IS
SELECT employee_id, salary FROM employees WHERE
department_id = dnum;
total_salary NUMBER(11, 2) := 0;
BEGIN
FOR emp_record IN emp_cursor LOOP
total_salary := total_salary + emp_record.salary;
DBMS_OUTPUT.PUT_LINE('Employees ID : ' ||
emp_record.employee_id || ' ;Salary : ' || emp_record.salary);
END LOOP;
/* SHOW SUM OF SALARY */
DBMS_OUTPUT.PUT_LINE('Total salary : ' ||
TO_CHAR(total_salary));
RETURN total_salary;
END show_employee_salary;
RUN IT :
SET SERVEROUTPUT ON
VARIABLE total_salary NUMBER;
EXECUTE :total_salary := show_employee_salary(20);
CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;
cursor c1 is
SELECT course_number
FROM courses_tbl
WHERE course_name = name_in;
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||'
-ERROR- '||SQLERRM);
END;
--------------------------------------------------------------------
CREATE OR REPLACE Function TotalIncome
( name_in IN varchar2 )
RETURN varchar2
IS
total_val number(6);
cursor c1 is
SELECT monthly_income
FROM employees
WHERE name = name_in;
BEGIN
total_val := 0;
FOR employee_rec in c1
LOOP
total_val := total_val + employee_rec.monthly_income;
END LOOP;
RETURN total_val;
END;
Loop cursor : for and loop
CREATE OR REPLACE Function IncomeLevel
( name_in IN varchar2 )
RETURN varchar2
IS
monthly_value number(6);
ILevel varchar2(20);
cursor c1 is
SELECT monthly_income
FROM employees
WHERE name = name_in;
BEGIN
open c1;
fetch c1 into monthly_value;
close c1;
IF monthly_value <= 4000 THEN
ILevel := 'Low Income';
ELSIF monthly_value > 4000 and monthly_value <= 7000 THEN
ILevel := 'Avg Income';
ELSIF monthly_value > 7000 and monthly_value <= 15000 THEN
ILevel := 'Moderate Income';
ELSE
ILevel := 'High Income';
END IF;
RETURN ILevel;
END;
Oracle/PLSQL: Triggers
Salary < 10000
I U D
Employee + + -
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Example :
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE
ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
CREATE TRIGGER PersonCheckAge
AFTER INSERT OR UPDATE OF age
ON Person
FOR EACH ROW
BEGIN
IF (:new.age < 0) THEN
RAISE_APPLICATION_ERROR(-20000, 'no negative age allowed');
END IF;
END;
/
SQL> create or replace trigger emp_biu
2 before insert or update on employee
3 referencing new as new old as old
4 for each row
5 begin
6 if nvl(:new.salary,0) >= 10000 THEN
7 raise_application_error (-20999,'Salary with
8 commissions should be less than 10000');
9 end if;
10 end;
11 /

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Oracle - Program with PL/SQL - Lession 07
Oracle - Program with PL/SQL - Lession 07Oracle - Program with PL/SQL - Lession 07
Oracle - Program with PL/SQL - Lession 07
 
Les01
Les01Les01
Les01
 
Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
 
Les02
Les02Les02
Les02
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Les12
Les12Les12
Les12
 
Les10
Les10Les10
Les10
 
Oracle PL/SQL Bulk binds
Oracle PL/SQL Bulk bindsOracle PL/SQL Bulk binds
Oracle PL/SQL Bulk binds
 
Les03
Les03Les03
Les03
 
Les02 Restricting And Sorting Data
Les02 Restricting And Sorting DataLes02 Restricting And Sorting Data
Les02 Restricting And Sorting Data
 
11 things about 11gr2
11 things about 11gr211 things about 11gr2
11 things about 11gr2
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
Les06 Subqueries
Les06 SubqueriesLes06 Subqueries
Les06 Subqueries
 
Les12 creating views
Les12 creating viewsLes12 creating views
Les12 creating views
 
Trig
TrigTrig
Trig
 
Les05 Aggregating Data Using Group Function
Les05 Aggregating Data Using Group FunctionLes05 Aggregating Data Using Group Function
Les05 Aggregating Data Using Group Function
 
Les01 Writing Basic Sql Statements
Les01 Writing Basic Sql StatementsLes01 Writing Basic Sql Statements
Les01 Writing Basic Sql Statements
 
Quick reference for cql
Quick reference for cqlQuick reference for cql
Quick reference for cql
 
Les04 Displaying Data From Multiple Table
Les04 Displaying Data From Multiple TableLes04 Displaying Data From Multiple Table
Les04 Displaying Data From Multiple Table
 

Destaque

Aerial Photography Manchester By Bernard O Sullivan
Aerial Photography Manchester By Bernard O SullivanAerial Photography Manchester By Bernard O Sullivan
Aerial Photography Manchester By Bernard O Sullivan
Mike Spence
 
Maak kennis met Blömer accountants en adviseurs
Maak kennis met Blömer accountants en adviseursMaak kennis met Blömer accountants en adviseurs
Maak kennis met Blömer accountants en adviseurs
Sharon de Ruwe-Bos
 
Case studies wsi wisdom book 2011- uk and europe
Case studies   wsi wisdom book 2011- uk and europeCase studies   wsi wisdom book 2011- uk and europe
Case studies wsi wisdom book 2011- uk and europe
Mike Spence
 
Lineage ii the chaotic chronicle prima official e guide
Lineage ii the chaotic chronicle prima official e guideLineage ii the chaotic chronicle prima official e guide
Lineage ii the chaotic chronicle prima official e guide
Fernando Bera
 

Destaque (14)

Swing chain correct the cause of your most common swing errors
Swing chain   correct the cause of your most common swing errorsSwing chain   correct the cause of your most common swing errors
Swing chain correct the cause of your most common swing errors
 
Pizza palace
Pizza palacePizza palace
Pizza palace
 
Inside Out Photo Commercial Photographers Example Portfolio
Inside Out Photo Commercial Photographers Example PortfolioInside Out Photo Commercial Photographers Example Portfolio
Inside Out Photo Commercial Photographers Example Portfolio
 
Verb to be
Verb to beVerb to be
Verb to be
 
Mauro powerrrr
Mauro powerrrrMauro powerrrr
Mauro powerrrr
 
Aerial Photography Manchester By Bernard O Sullivan
Aerial Photography Manchester By Bernard O SullivanAerial Photography Manchester By Bernard O Sullivan
Aerial Photography Manchester By Bernard O Sullivan
 
Maak kennis met Blömer accountants en adviseurs
Maak kennis met Blömer accountants en adviseursMaak kennis met Blömer accountants en adviseurs
Maak kennis met Blömer accountants en adviseurs
 
Programa completo
Programa completoPrograma completo
Programa completo
 
Capital budgeting decission
Capital budgeting decissionCapital budgeting decission
Capital budgeting decission
 
Ingles
InglesIngles
Ingles
 
Case studies wsi wisdom book 2011- uk and europe
Case studies   wsi wisdom book 2011- uk and europeCase studies   wsi wisdom book 2011- uk and europe
Case studies wsi wisdom book 2011- uk and europe
 
Putting: The longest yard
Putting: The longest yardPutting: The longest yard
Putting: The longest yard
 
Lineage ii the chaotic chronicle prima official e guide
Lineage ii the chaotic chronicle prima official e guideLineage ii the chaotic chronicle prima official e guide
Lineage ii the chaotic chronicle prima official e guide
 
Waste gas filipe
Waste gas   filipeWaste gas   filipe
Waste gas filipe
 

Semelhante a Oracle

Les08-Oracle
Les08-OracleLes08-Oracle
Les08-Oracle
suman1248
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
Reka
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
Yanli Liu
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
Nawaz Sk
 

Semelhante a Oracle (20)

Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should Know
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01
 
Function in PL/SQL
Function in PL/SQLFunction in PL/SQL
Function in PL/SQL
 
Les08-Oracle
Les08-OracleLes08-Oracle
Les08-Oracle
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Oracle sql tuning
Oracle sql tuningOracle sql tuning
Oracle sql tuning
 
plsql les06
 plsql les06 plsql les06
plsql les06
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
 
Oracle - Program with PL/SQL - Lession 10
Oracle - Program with PL/SQL - Lession 10Oracle - Program with PL/SQL - Lession 10
Oracle - Program with PL/SQL - Lession 10
 
PHP tips by a MYSQL DBA
PHP tips by a MYSQL DBAPHP tips by a MYSQL DBA
PHP tips by a MYSQL DBA
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
 

Oracle

  • 1. Oracle/PLSQL: Create a database CREATE TEMPORARY TABLESPACE TEMP_NEW TEMPFILE '/DATA/database/ifsprod/temp_01.dbf' SIZE 500m autoextend on next 10m maxsize unlimited; CREATE DATABASE mynewdb USER SYS IDENTIFIED BY sys_password USER SYSTEM IDENTIFIED BY system_password EXTENT MANAGEMENT LOCAL DEFAULT TEMPORARY TABLESPACE temp UNDO TABLESPACE undotbs1 DEFAULT TABLESPACE users; Oracle/PLSQL: Create a Schema Step 1 - Create a new user in Oracle CREATE USER smithj IDENTIFIED BY pwd4smithj DEFAULT TABLESPACE tbs_perm_01 TEMPORARY TABLESPACE tbs_temp_01 QUOTA 20M on tbs_perm_01; create tablespace tbs_temp_01 datafile tbs_temp_01.dbf' size 50m autoextend on next 10m maxsize 100m; Step 2 - Assign SYSTEM privileges to new user in Oracle GRANT create session TO smithj; GRANT create table TO smithj; GRANT create view TO smithj; GRANT create any trigger TO smithj; GRANT create any procedure TO smithj; GRANT create sequence TO smithj; GRANT create synonym TO smithj; Object can be function or store procedure : GRANT EXECUTE ON object TO smithj; REVOKE EXECUTE ON object FROM user; grant dba to sample_schema ; grant connect to sample_schema
  • 2. These new privileges are now granted to the user called smithj. Step 3 - Create objects in the schema Step 4 - Grant Object Privileges After you have created your objects in the schema, you will need to grant privileges so that other schemas/users can access your database objects (ie: tables). Step 5 - Create Synonyms for Objects As a last step, you may want to create synonyms so that other schemas can access the new database objects (ie: tables) without having to prefix the object names with the schema name. For example, if you were another user named smithj and wanted to select from the suppliers table in new_schema, you would have to run the following SELECT statement (before any synonyms are created): SELECT * FROM new_schema.suppliers; If you then created a synonym for the suppliers table as follows: CREATE PUBLIC SYNONYM suppliers FOR new_schema.suppliers; You could run the SELECT statement as follows: SELECT * FROM suppliers; No longer needing to prefix the table name with the schema name. Oracle/PLSQL: CREATE USER statement The syntax for the CREATE USER statement in Oracle/PLSQL is: CREATE USER user_name IDENTIFIED { BY password | EXTERNALLY [ AS 'certificate_DN' ] | GLOBALLY [ AS '[ directory_DN ]' ] } [ DEFAULT TABLESPACE tablespace | TEMPORARY TABLESPACE { tablespace | tablespace_group } | QUOTA integer [ K | M | G | T | P | E ] | UNLIMITED }
  • 3. ON tablespace [ QUOTA integer [ K | M | G | T | P | E ] | UNLIMITED } ON tablespace ] | PROFILE profile_name | PASSWORD EXPIRE | ACCOUNT { LOCK | UNLOCK } [ DEFAULT TABLESPACE tablespace | TEMPORARY TABLESPACE { tablespace | tablespace_group } | QUOTA integer [ K | M | G | T | P | E ] | UNLIMITED } ON tablespace [ QUOTA integer [ K | M | G | T | P | E ] | UNLIMITED } ON tablespace ] | PROFILE profile | PASSWORD EXPIRE | ACCOUNT { LOCK | UNLOCK } ] ] ; Parameters or Arguments Example If you wanted to execute a simple CREATE USER statement that creates a new user and assigns a password, you could do the following: For example: CREATE USER smithj IDENTIFIED BY pwd4smithj DEFAULT TABLESPACE tbs_perm_01 TEMPORARY TABLESPACE tbs_temp_01 QUOTA 20M on tbs_perm_01; CREATE USER smithj IDENTIFIED BY pwd4smithj DEFAULT TABLESPACE tbs_perm_01 TEMPORARY TABLESPACE tbs_temp_01 QUOTA 20M on tbs_perm_01 Oracle/PLSQL: DROP USER statement DROP USER user_name [ CASCADE ]; DROP USER smithj; DROP USER smithj CASCADE; Oracle/PLSQL: Roles
  • 4. CREATE ROLE role_name [ NOT IDENTIFIED | IDENTIFIED {BY password | USING [schema.] package | EXTERNALLY | GLOBALLY } ; This first example creates a role called test_role. CREATE ROLE test_role IDENTIFIED BY test123; Grant TABLE Privileges to Role GRANT privileges ON object TO role_name GRANT select, insert, update, delete ON suppliers TO test_role; GRANT all ON suppliers TO test_role;s Revoke Table Privileges from Role REVOKE privileges ON object FROM role_name; REVOKE delete ON suppliers FROM test_role; REVOKE all ON suppliers FROM test_role; Grant Function/Procedure Privileges to Role GRANT EXECUTE ON object TO role_name; EXECUTE means the following: Privilege Description EXECUTE Ability to compile the function/procedure. Ability to execute the function/procedure directly. Revoke Function/Procedure Privileges from Role REVOKE execute ON object FROM role_name; Grant Role to User GRANT role_name TO user_name; REVOKE role_name FROM user_name; Enable/Disable Role (Set Role Statement) SET ROLE ( role_name [ IDENTIFIED BY password ] | ALL [EXCEPT role1, role2, ... ] | NONE ); For example: SET ROLE test_role IDENTIFIED BY test123; Set role as DEFAULT Role ALTER USER user_name DEFAULT ROLE ( role_name | ALL [EXCEPT role1, role2, ... ] | NONE ); Example Let's look at an example of how to set a role as a DEFAULT ROLE in Oracle.
  • 5. For example: ALTER USER smithj DEFAULT ROLE test_role; Drop Role DROP ROLE role_name;
  • 6. Oracle/PLSQL: Procedures CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ] IS [declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [procedure_name]; Example CREATE OR REPLACE Procedure UpdateCourse ( name_in IN varchar2 ) IS cnumber number; cursor c1 is SELECT course_number FROM courses_tbl WHERE course_name = name_in; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; INSERT INTO student_courses ( course_name, course_number ) VALUES ( name_in, cnumber ); commit; close c1; EXCEPTION WHEN OTHERS THEN raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM); END; --------------------------------------------------------------------
  • 7. CREATE OR REPLACE PROCEDURE getDBUSERByUserId( p_userid IN DBUSER.USER_ID%TYPE, o_username OUT DBUSER.USERNAME%TYPE, o_createdby OUT DBUSER.CREATED_BY%TYPE, o_date OUT DBUSER.CREATED_DATE%TYPE) IS BEGIN SELECT USERNAME , CREATED_BY, CREATED_DATE INTO o_username, o_createdby, o_date FROM DBUSER WHERE USER_ID = p_userid; END; ++++++++++++++++++++++++++++ DECLARE o_username DBUSER.USERNAME%TYPE; o_createdby DBUSER.CREATED_BY%TYPE; o_date DBUSER.CREATED_DATE%TYPE; BEGIN getDBUSERByUserId(1001,o_username,o_createdby,o_date); DBMS_OUTPUT.PUT_LINE('username : ' || o_username); DBMS_OUTPUT.PUT_LINE('createdby : ' || o_createdby); DBMS_OUTPUT.PUT_LINE('createddate : ' || o_date); END; -------------------------------------------------------------------- 1> CREATE OR REPLACE PROCEDURE employer_details 2> IS 3> CURSOR emp_cur IS 4> SELECT first_name, last_name, salary FROM emp_tbl; 5> emp_rec emp_cur%rowtype; 6> BEGIN 7> FOR emp_rec in sales_cur 8> LOOP 9> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name 10> || ' ' ||emp_cur.salary); 11> END LOOP; 12>END; 13> / -------------------------------------------------------------------- CREATE PROCEDURE GET_ONESET_CUSTOMERINFO ( P_CREDITLINEAMOUNT IN INTEGER, CURSOR_ IN OUT TYPES.REF_CURSOR ) AS BEGIN OPEN CURSOR_ FOR SELECT * FROM CROSSSELLCUSTOMERS WHERE CREDITLINEAMOUNT >= P_CREDITLINEAMOUNT; END;
  • 8. Oracle/PLSQL: Functions CREATE [OR REPLACE] FUNCTION function_name [ (parameter [,parameter]) ] RETURN return_datatype IS | AS [declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [function_name]; CREATE OR REPLACE FUNCTION show_employee_salary(dnum NUMBER) RETURN NUMBER IS CURSOR emp_cursor IS SELECT employee_id, salary FROM employees WHERE department_id = dnum; total_salary NUMBER(11, 2) := 0; BEGIN FOR emp_record IN emp_cursor LOOP total_salary := total_salary + emp_record.salary; DBMS_OUTPUT.PUT_LINE('Employees ID : ' || emp_record.employee_id || ' ;Salary : ' || emp_record.salary); END LOOP; /* SHOW SUM OF SALARY */ DBMS_OUTPUT.PUT_LINE('Total salary : ' || TO_CHAR(total_salary)); RETURN total_salary; END show_employee_salary; RUN IT : SET SERVEROUTPUT ON VARIABLE total_salary NUMBER; EXECUTE :total_salary := show_employee_salary(20);
  • 9. CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; cursor c1 is SELECT course_number FROM courses_tbl WHERE course_name = name_in; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1; RETURN cnumber; EXCEPTION WHEN OTHERS THEN raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM); END; -------------------------------------------------------------------- CREATE OR REPLACE Function TotalIncome ( name_in IN varchar2 ) RETURN varchar2 IS total_val number(6); cursor c1 is SELECT monthly_income FROM employees WHERE name = name_in; BEGIN total_val := 0; FOR employee_rec in c1 LOOP total_val := total_val + employee_rec.monthly_income; END LOOP; RETURN total_val; END; Loop cursor : for and loop
  • 10. CREATE OR REPLACE Function IncomeLevel ( name_in IN varchar2 ) RETURN varchar2 IS monthly_value number(6); ILevel varchar2(20); cursor c1 is SELECT monthly_income FROM employees WHERE name = name_in; BEGIN open c1; fetch c1 into monthly_value; close c1; IF monthly_value <= 4000 THEN ILevel := 'Low Income'; ELSIF monthly_value > 4000 and monthly_value <= 7000 THEN ILevel := 'Avg Income'; ELSIF monthly_value > 7000 and monthly_value <= 15000 THEN ILevel := 'Moderate Income'; ELSE ILevel := 'High Income'; END IF; RETURN ILevel; END; Oracle/PLSQL: Triggers Salary < 10000 I U D Employee + + - CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF }
  • 11. {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) DECLARE Declaration-statements BEGIN Executable-statements EXCEPTION Exception-handling-statements END; Example : CREATE OR REPLACE TRIGGER display_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON customers FOR EACH ROW WHEN (NEW.ID > 0) DECLARE sal_diff number; BEGIN sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary: ' || :OLD.salary); dbms_output.put_line('New salary: ' || :NEW.salary); dbms_output.put_line('Salary difference: ' || sal_diff); END; / CREATE TRIGGER PersonCheckAge AFTER INSERT OR UPDATE OF age ON Person FOR EACH ROW BEGIN IF (:new.age < 0) THEN RAISE_APPLICATION_ERROR(-20000, 'no negative age allowed'); END IF; END; / SQL> create or replace trigger emp_biu 2 before insert or update on employee 3 referencing new as new old as old 4 for each row 5 begin 6 if nvl(:new.salary,0) >= 10000 THEN 7 raise_application_error (-20999,'Salary with 8 commissions should be less than 10000'); 9 end if; 10 end; 11 /