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.
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 /