0% found this document useful (0 votes)
39 views33 pages

PLSQL Queries Examples

This document provides examples of PL/SQL queries and programming. It demonstrates basic PL/SQL blocks, using SQL within PL/SQL, exceptions, records, procedures, variables and more. Key examples include hello world anonymous blocks, a procedure to print a message, using records to retrieve and display employee data, and handling exceptions when invalid data is entered.

Uploaded by

prasanna ghare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
39 views33 pages

PLSQL Queries Examples

This document provides examples of PL/SQL queries and programming. It demonstrates basic PL/SQL blocks, using SQL within PL/SQL, exceptions, records, procedures, variables and more. Key examples include hello world anonymous blocks, a procedure to print a message, using records to retrieve and display employee data, and handling exceptions when invalid data is entered.

Uploaded by

prasanna ghare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 33

ORACLE PLSQL QUERIES AND EXAMPLES

PLSQL BASICS
posted Apr 29, 2012, 4:29 PM by srinivas aithagani   [ updated Apr 29, 2012, 6:07 PM ]

SQL> SET SERVEROUTPUT ON


SQL> --SIMPLE PLSQL PROGRAM
SQL> BEGIN
  2  NULL;
  3  END;
  4  /

PL/SQL procedure successfully completed.

SQL> BEGIN
  2  DBMS_OUTPUT.PUT_LINE('HELLO WORLD');
  3  END;
  4  /
HELLO WORLD                                                                                  

PL/SQL procedure successfully completed.

SQL> ABOVE IS ANANYMOUS BLOCK

SQL> --THE SAME PROGRAM IS WRITING WITH PROCEDURE'


SQL> CREATE OR REPLACE PROCEDURE PROC_1
  2  AS
  3   BEGIN
  4   DBMS_OUTPUT.PUT_LINE('HELLO WORLD');
  5   END;
  6  /

Procedure created.

SQL> --EXECUTING ABOVE PROCEDURE


SQL> EXEC PROC_1;
HELLO WORLD                                                                                  

PL/SQL procedure successfully completed.

SQL> --OR WE CAN EXECUTE THE PROCEDURE BY USING AN ANANYMOUS BLOCK


SQL> BEGIN
  2  PROC_1;
  3  END;
  4  /
HELLO WORLD                                                                                  

PL/SQL procedure successfully completed.

SQL> --USING SQL IN PLSQL


SQL> DECLARE
  2  V_ENAME EMP.ENAME%TYPE;
  3  V_SAL EMP.SAL%TYPE;
  4  V_DEPTNO EMP.DEPTNO%TYPE;
  5  V_COMM EMP.COMM%TYPE;
  6  BEGIN
  7  SELECT ENAME,SAL,DEPTNO,COMM INTO V_ENAME,V_SAL,V_DEPTNO,V_COMM
  8  FROM EMP WHERE EMPNO=7839;
  9  DBMS_OUTPUT.PUT_LINE(V_ENAME||' '||V_SAL||' '||V_DEPTNO||' '||V_COMM);
 10  END;
 11  /
KING 5000 10                                                                                

PL/SQL procedure successfully completed.

SQL> --WRITING THE SAME PROGRAM BY USING EMPNO


SQL> ED
Wrote file afiedt.buf

  1  DECLARE
  2  V_EMPNO EMP.EMPNO%TYPE:=&ENTEREMPNO;
  3  V_ENAME EMP.ENAME%TYPE;
  4  V_SAL EMP.SAL%TYPE;
  5  V_DEPTNO EMP.DEPTNO%TYPE;
  6  V_COMM EMP.COMM%TYPE;
  7  BEGIN
  8  SELECT ENAME,SAL,DEPTNO,COMM INTO V_ENAME,V_SAL,V_DEPTNO,V_COMM
  9  FROM EMP WHERE EMPNO=V_EMPNO;
 10  DBMS_OUTPUT.PUT_LINE(V_ENAME||' '||V_SAL||' '||V_DEPTNO||' '||V_COMM);
 11* END;
SQL> /
Enter value for enterempno: 7839
KING 5000 10                                                                                

PL/SQL procedure successfully completed.

SQL> /
Enter value for enterempno: 7566
JONES 2975 20                                                                                

PL/SQL procedure successfully completed.

SQL> --NOW AM ENTERING INVALID EMPNO


SQL> /
Enter value for enterempno: 1234
DECLARE
*
ERROR at line 1:
ORA-01403: no data found 
ORA-06512: at line 8 

SQL> --USING EXCEPTION HANDLING


SQL> ED
Wrote file afiedt.buf
  1  DECLARE
  2  V_EMPNO EMP.EMPNO%TYPE:=&ENTEREMPNO;
  3  V_ENAME EMP.ENAME%TYPE;
  4  V_SAL EMP.SAL%TYPE;
  5  V_DEPTNO EMP.DEPTNO%TYPE;
  6  V_COMM EMP.COMM%TYPE;
  7  BEGIN
  8  SELECT ENAME,SAL,DEPTNO,COMM INTO V_ENAME,V_SAL,V_DEPTNO,V_COMM
  9  FROM EMP WHERE EMPNO=V_EMPNO;
 10  DBMS_OUTPUT.PUT_LINE(V_ENAME||' '||V_SAL||' '||V_DEPTNO||' '||V_COMM);
 11  EXCEPTION
 12  WHEN NO_DATA_FOUND THEN
 13  RAISE_APPLICATION_ERROR(-20001,'YOU HAVE ENTERED INVALID EMPLOYEE NUMBER');
 14* END;
SQL> /
Enter value for enterempno: 1234
DECLARE
*
ERROR at line 1:
ORA-20001: YOU HAVE ENTERED INVALID EMPLOYEE NUMBER 
ORA-06512: at line 13 

SQL> ---USING ROWTYPE


SQL> DECLARE
  2  V_EMPRECORD EMP%ROWTYPE;
  3  BEGIN
  4  SELECT * INTO V_EMPRECORD FROM EMP WHERE EMPNO=&ENTEREMPNO;
  5  DBMS_OUTPUT.PUT_LINE('ENAME'||' : '||V_EMPRECORD.ENAME);
  6  DBMS_OUTPUT.PUT_LINE('SAL'||' : '||V_EMPRECORD.SAL);
  7  DBMS_OUTPUT.PUT_LINE('JOB'||' : '||V_EMPRECORD.JOB);
  8  END;
  9  /
Enter value for enterempno: 7566
ENAME : JONES                                                                                
SAL : 2975                                                                                  
JOB : MANAGER                                                                                

PL/SQL procedure successfully completed.

SQL> /
Enter value for enterempno: 7839
ENAME : KING                                                                                
SAL : 5000                                                                                  
JOB : PRESIDENT                                                                              

PL/SQL procedure successfully completed.

SQL> /
Enter value for enterempno: 7902
ENAME : FORD                                                                                
SAL : 3000                                                                                  
JOB : ANALYST                                                                                
PL/SQL procedure successfully completed.

SQL> --SIMPLE PRINT PROGRAM


SQL> CREATE OR REPLACE PROCEDURE PRINT(V_TEXT VARCHAR2)
  2  AS
  3  BEGIN
  4  DBMS_OUTPUT.PUT_LINE(V_TEXT);
  5  END;
  6  /

Procedure created.

SQL> --PLSQL RECORDS

SQL> ED
Wrote file afiedt.buf

  1  DECLARE
  2  V_EMPNO EMP.EMPNO%TYPE:=&ENTEREMPNO;
  3  TYPE EMPRECORDTYPE IS RECORD
  4  (
  5  V_ENAME EMP.ENAME%TYPE,
  6  V_DEPTNO EMP.DEPTNO%TYPE,
  7  V_JOB EMP.JOB%TYPE
  8  );
  9  EMPRECORD EMPRECORDTYPE;
 10  BEGIN
 11  SELECT ENAME,DEPTNO,JOB
 12  INTO
 13  EMPRECORD.V_ENAME,EMPRECORD.V_DEPTNO,EMPRECORD.V_JOB
 14  FROM EMP
 15  WHERE EMPNO=V_EMPNO;
 16  PRINT('----THE DETAILS YOU ENTERED ARE--');
 17  PRINT('ENAME'||' '||EMPRECORD.V_ENAME);
 18  PRINT('DEPTNO'||' '||EMPRECORD.V_DEPTNO);
 19  PRINT('JOB'||' '||EMPRECORD.V_JOB);
 20* END;
SQL> /
Enter value for enterempno: 7566
----THE DETAILS YOU ENTERED ARE--                                                            
ENAME JONES                                                                                  
DEPTNO 20                                                                                    
JOB MANAGER                                                                                  

PL/SQL procedure successfully completed.

SQL> SPOOL OFF


PLSQL Interview Questions And Answers For Practice
- Part 1

HOW TO DISPLAY THE FIRST FIFTY EVEN NUMBERS BY USING PL/SQL


1. declare 
      i number; 
begin
      for i in 1..50
loop
      if mod(i,2)=0 then
dbms_output.put_line('THE EVEN NUMBERS ARE'||i);
end if;
end loop;
end;

HOW TO DISPLAY THE FIRST FIFTY ODD NUMBERS BY USING PL/SQL


1. declare

i number;

begin

for i in 1..50

loop

if mod(i,2)<>0 then

dbms_output.put_line(‘THE ODD NUMBERS ARE’||i);

end if;

end loop;

FIND SCOPE AND VISIBILITY OF VARIABLES IN A PL/SQL PROGRAMME


1. SQL> variable g_monthly_salary number;
SQL> define p_annual_salary=50000;

begin

:g_monthly_salary:=&p_annual_salary/12;

end;

SQL> print :g_monthly_salary;

(OR Method 2)

SQL> variable g_monthly_salary number;

SQL> define p_annual_salary=50000;

declare

v_sal number:=&p_annual_salary;

begin

:g_monthly_salary:=v_sal/12;

end;

SQL> print g_monthly_salary;

COMPUTE A 10% BONUS FOR THE EMPLOYEE WITH THE EMPLOYEE_ID 7559 AND
ASSIGN THE COMPUTED VALUE TO THE V_BONUS VARIABLE BY USING THE PL/SQL
BLOCK
1. declare

      v_bonus number;

begin

     select sal*0.10 into v_bonus from emp_dup where empno=7559;

dbms_output.put_line('THE BONUS SALARY WAS'||v_bonus);


end;

PROVIDE AN EXAMPLE OF USING A HOST VARIABLE IN A PL/SQL BLOCK


1. SQL> variable annual_sal number;

begin

     select (sal*12)+nvl(comm,0) into :annual_sal from emp_dup where

empno=7369;

end;

HOW TO PRINT THE VALUE OF SALARY OF A SPECIFIC EMPLOYEE BY USING BIND


VARIABLE IN PL/SQL
1. SQL> variable salary number

begin

     select sal into :salary from emp_dup where empno=7369;

end;

SQL> print salary;

HOW TO COMPUTE THE MONTHLY SALARY,BASED UPON THE ANNUAL SALARY


SUPPLIED BY THE USER
1. SQL> variable g_monthly_salary number;

SQL> define p_annual_salary=50000;

begin
:g_monthly_salary:=&p_annual_salary/12;

end;

SQL> print :g_monthly_salary;

(OR Method 2)

SQL> variable g_monthly_salary number;

SQL> define p_annual_salary=50000;

declare

v_sal number:=&p_annual_salary;

begin

:g_monthly_salary:=v_sal/12;

end;

SQL> print g_monthly_salary;

HOW TO COMPUTE AND PRINT THE MONTHLY SALARY ON TO THE SCREEN USING THE
ORACLE SUPPLIED PACKAGE PROCEDURE BASED UPON THE ANNUAL SALARY
SUPPLIED BY THE USER
1. SQL> define p_annual_salary=50000;

declare

      v_sal number:=&p_annual_salary;

      g_monthly_salary number;

begin

    g_monthly_salary:=v_sal/12;

dbms_output.put_line('THE MONTHLY SALARY WAS'||


g_monthly_salary);

end;

HOW TO CREATE AN ANONYMOUS BLOCK TO OUTPUT THE PHRASE "MY PL/SQL BLOCK
WORKS" TO THE SCREEN
1. SQL> variable g_message varchar2(30)

begin

    :g_message:='MY PL/SQL BLOCK WORKS';

end;

SQL> print g_message;

HOW TO CREATE A BLOCK THAT DECLARES TWO VARIABLES. ASSIGN THE VALUE OF
THESE ISQL*PLUS HOST VARIABLES AND PRINT THE RESULTS OF THE PL/SQL
VARIABLES TO THE SCREEN
1. SQL> variable g_char varchar2(30)

SQL> variable g_num number

begin

     :g_char:='42 IS THE ANSWER';

     :g_num:=42;

end;

SQL> print g_char;

SQL> print g_num;


PLSQL Interview Questions And
Answers For Practice – Part 2
HOW TO DISPLAY THE DEPARTMENT NAME SALES USING PL/SQL BLOCK
1. declare
2.       v_deptno number;
3.  
4.       v_dname varchar2(30);
5.  
6.       v_loc varchar(30);
7.  
8. begin
9.  
10.      select deptno,dname,loc into v_deptno,v_dname,v_loc from dept
11.  
12. where dname='SALES';
13.  
14. dbms_output.put_line('THE DEPARTMENT NAME SALES DETAILS
WAS'||'  '||
15.  
16. v_deptno||'  '||v_dname||'  '||v_loc);
17.  
18. end;

HOW TO DISPLAY THE EMPLOYEE DETAILS OF 7686 THROUGH PL/SQL BLOCK


1. declare
2.
3. p emp_dup%rowtype;
4.
5. begin
6.
7.      select * into p from emp_dup where empno=7686;
8.
9. dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||' '||p.empno||'  '
10.
11. ||p.ename||' '||p.sal||'  '||p.job||'  '||p.deptno);
12.
13. end;

HOW TO RETURN THE SUM OF THE SALARIES FOR ALL EMPLOYEES IN THE SPECIFIED
DEPARTMENT
1. declare
2.       v_deptno number:=30;
3.  
4.       v_sum_sal number;
5.  
6. begin
7.  
8.     select deptno,sum(sal) into v_deptno,v_sum_sal from emp_dup
9.  
10. where deptno=v_deptno group by deptno;
11.  
12. dbms_output.put_line('THE SUM OF SALARY OF DEPTNO30 WAS'||
v_sum_sal);
13.  
14. end;

HOW TO ADD A NEW EMPLOYEE TO THE EMP_DUPLICATE TABLE THROUGH PL/SQL


BLOCK
1. begin
2.     insert into emp_duplicate values(7778,'GVR','manager',66,sysdate,
3.  
4. 6000,300,50);
5.  
6. end;

SQL> select * from emp_duplicate;

HOW TO UPDATE THE EMPLOYEE SALARY WITH INCREASE OF 5000 THAN EARLIER
AMOUNT AND WITH JOB AS MANAGER
1. declare
2. p emp_dup%rowtype;
3.  
4. begin
5.  
6.      select * into p from emp_dup where job='manager';
7.  
8. update emp_dup set sal=p.sal+5000 where job='manager';
9.  
10. end;

HOW TO DELETE ROWS FOR THE DEPARTMENT 20 AND PRINT THE NUMBER OF ROWS
DELETED USING SQL CURSOR ATTRIBUTES
SQL> variable rows_deleted varchar2(30)
1. begin
2. delete from emp_dup where deptno=20;
3.  
4. :rows_deleted:=(sql%rowcount||' '||'rows_deleted');
5.  
6. end;

HOW TO CREATE A PL/SQL BLOCK THAT SELECTS THE MAXIMUM DEPARTMENT


NUMBER IN THE DEPARTMENTS TABLE IT IN AN ISQL*PLUS VARIABLE.PRINT THE
RESULTS TO THE SCREEN
SQL> variable max_deptno number
1. declare
2.       v_max_deptno number;
3.  
4. begin
5.  
6.     select max(deptno) into v_max_deptno from dept;
7.  
8. :max_deptno:=v_max_deptno;
9.  
10. end;

SQL> print max_deptno;
HOW TO INSERT INTO A NEW DEPARTMENT INTO THE TABLE ****A) USING THE DEFINE
COMMAND PROVIDE THE DEPARTMENT NAME AS NEW_DEPARTMENT ****B)USING THE
ISQL*PLUS SUBSTITUTION VARIABLE PASS THE LOCATION
SQL> define department_name=’EDUCATION’;
1. declare
2.       v_deptno number:=50;
3.  
4.       v_dname varchar2(30):='&department_name';
5.  
6. begin
7.  
8. insert into dept(deptno,dname) values(v_deptno,v_dname);
9.  
end;
10.
SQL> select * from dept;

HOW TO CREATE A PL/SQL BLOCK THAT DELETES THE DEPARTMENT NUMBER 20 ****A)
USING THE DEFINE COMMAND PROVIDE THE DEPARTMENT NUMBER. ****B) USING THE
ISQL*PLUS SUBSTITUTION VARIABLE PASS THE VALUE TO PL/SQL BLOCK. ****C) PRINT
TO THE SCREEN NUMBER OF ROWS AFFECTED.
SQL> define p_deptno=50;
SQL> variable g_result varchar2(30)
1. declare
2.        v_deptno number:=&p_deptno;
3.  
4.        result varchar2(30);
5.  
6. begin
7.  
8.     delete from dept where deptno=v_deptno;
9.  
10. result:=(sql%rowcount||(row(s) deleted');
11.  
12. :g_result:=result;
13.  
end;
14.
SQL> print g_result;
SQL> select * from dept;
HOW TO CREATE A PL/SQL BLOCK SUCH THAT IF THE EMPLOYEE NAME WAS 'KEVIN'
THEN SET THE MANAGER_ID TO 150
1. declare
2. p emp_dup%rowtype;
3.  
4. begin
5.  
6. select * into p from emp_dup where ename='KEVIN';
7.  
8. if p.ename ='KEVIN' then
9.  
10. p.mgr:=150;
11.  
12. update emp_dup set mgr=p.mgr where ename='KEVIN';
13.  
14. end if;
15.  
end;
16.
SQL> select * from emp_dup where ename=’KEVIN’;

What are the Advantages of using PLSQL over


Traditional SQL
PLSQL has support for SQL and supports Object-Oriented Programming. It’s
integration with Oracle provides better performance, portability and  higher productivity.
 PLSQL Supports the declaration and manipulation of object types and
collections.
 PLSQL Allows the calling of external functions and procedures.
 PLSQL Contains new libraries of built in packages.d] with PL/SQL , an
multiple sql statements can be processed in a single command line statement.
Developers and Database Administrators use PLSQL coding on a daily basis,
whether for application development, finding problems, fine-tuning solutions to those
problems, or other critical Database Administration tasks. Our aim here is to provide
answers to PLSQL questions that Database Administrators come across daily.

PLSQL Interview Questions And Answers For


Practice - Part 3
HOW TO CREATE A PL/SQL BLOCK THAT WILL SET THE DEPT_ID TO 100 AND JOB AS
'SA_CSR' FOR EMPLOYEE NAMED 'KEVIN'
1. declare

r emp_dup%rowtype;

begin

select * into r from emp_dup where ename='KEVIN';

if r.ename='KEVIN' then

r.job:='SA_CSR';

r.deptno:=100;

update emp_dup set job=r.job where ename='KEVIN';

update emp_dup set deptno=r.deptno where ename='KEVIN';

end if;

end;
SQL> select * from emp_dup where ename=’KEVIN’;

HOW TO CREATE A PL/SQL BLOCK THAT WILL SET THE DEPT_NO TO 100 FOR
EMPLOYEE NAMED 'KEVIN' AND ALSO THE EMPLOYEE SALARY IS LESS THAN 10000
1. declare

p emp_dup%rowtype;

begin

select * into p from emp_dup where ename='KEVIN';

if p.ename ='KEVIN' and p.sal>10000 then

p.deptno:=100;

update emp_dup set deptno=p.deptno where ename='KEVIN';


end if;

end;
SQL> select * from emp_dup where ename=’KEVIN’;

HOW TO SET THE MGR_ID TO 100 FOR EMPLOYEE NAMED "KEVIN" IF THE DEPTNO WAS
100 OR THE HIREDATE IS GRATER THAN THE '01-JAN-2000'
1. declare

p emp_dup%rowtype;

begin

     select * into p from emp_dup where ename='KEVIN';

if p.deptno=100 or p.hiredate>'01-jan-2000' then

p.mgr:=100;

update emp_dup set mgr=p.mgr where ename='KEVIN';

end if;

end;
SQL> select * from emp_dup where ename=’KEVIN’;

HOW TO CREATE A PL/SQL BLOCK THAT WILL EVALUATE THE VALUE_APPRAISAL ON


THE VALUE OF VALUE_GRADE BASED ON THE VALUE ENTERED BY THE USER.(THE
VALUE IS ACCEPTED FROM THE USER USING A SUBSTITUTION VARIABLE).
1. declare

      value_grade varchar2(5):=('&p_grade');

      value_appraisal varchar2(15);

begin

    if value_grade='A' then

value_appraisal :='EXCELLENT';
elsif value_grade='B' then

value_appraisal :='VERY GOOD';

elsif value_grade='C' then

value_appraisal :='GOOD';

elsif value_grade='D' then

value_appraisal :='BAD';

end if;

dbms_output.put_line('THE APPRISAL CATEGORY WAS'||


value_appraisal );

end;

HOW TO CREATE A PL/SQL BLOCK THAT WILL INSERT NUMBERS INTO MESSAGE
TABLE. A) INSERT THE NUMBERS 1 TO 20,EXCLUDING 16 AND 18 B) COMMIT BEFORE
THE END OF THE BLOCK C) SELECT THE MESSAGES TABLE TO VERIFY THAT YOUR
PL/SQL BLOCK WORKED
1. begin

    for i in 1..15

loop

insert into messages values(i);

end loop;

insert into messages values(17);

for i in 19..20

loop

insert into messages values(i);

end loop;
commit;

end;
SQL> select * from messages;

HOW TO RETRIEVE THE FIRST 10 RECORDS OF THE EMP_CSR TABLE BY USING THE
PL/SQL CURSORS
1. declare

       cursor emp_cursor is select empno,ename from emp_csr;

r emp_cursor%rowtype;

begin

     open emp_cursor;

loop

fetch emp_cursor into r;

dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||r.empno||


r.ename);

exit when emp_cursor%rowcount>=10;

end loop;

close emp_cursor;

end;

HOW TO RETRIEVE THE DETAILS OF THE EMPLOYEES WHOSE DEPARTMENT WAS 100
USING THE CURSORS
1. declare

      cursor dept_cursor is select * from emp_dup where deptno=100;

r emp_dup%rowtype;
begin

    open dept_cursor;

loop

   fetch dept_cursor into r;

dbms_output.put_line('THE EMPLOYEE DETAILS FOR DEPT 100


WAS'||r.empno||' '

||r.ename||' '||r.job||'  '||r.sal||r.deptno);

exit when dept_cursor%rowcount>=5;

end loop;

close dept_cursor;

end;

HOW TO RETRIEVE THE 20 RECORD OF THE EMPLOYEE TABLE USING CURSORS

1. declare

      cursor emp_20 is select empno,ename from emp_dup;

r emp_20%rowtype;

begin

    open emp_20;

loop

   fetch emp_20 into r;

dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||r.empno||' '||


r.ename);

exit when emp_20 %rowcount>=20;


end loop;

dbms_output.put_line('THE NO OF RECORDS DISPLAYED ARE'||


emp_20%rowcount);

close emp_20 ;

end;

HOW TO RETRIEVE THE EMPLOYEE NUMBER AND NAME FROM THE EMPLOYEE TABLE
AND INSERT INTO TEMP_LIST TABLE BY USING CURORS AND RECORDS

1. declare

      cursor temp_insert is select empno,ename from emp_dup;

emp_record temp_insert%rowtype;

begin

    open temp_insert;

loop

   fetch temp_insert into emp_record;

exit when temp_insert%notfound;

insert into temp_list(empid,tname)


values(emp_record.empno,emp_record.ename);

end loop;

close temp_insert;

end;

HOW TO INSERT VALUES INTO DEPARTMENT TABLE USING BASIC LOOP

1. declare
2.       v_deptid number;
3.  
4.       v_loc varchar2(15):='NRT';
5.  
6.       v_dname varchar2(15):='CREDIT';
7.  
8.       v_counter number:=1;
9.  
10. begin
11.  
12.      select max(deptno) into v_deptid from dept;
13.  
14. loop
15.  
16.    insert into dept(deptno,dname,loc)
values((v_deptid+v_counter),v_dname,v_loc);
17.  
18. v_counter:=v_counter+1;
19.  
20. exit when v_counter>3;
21.  
22. end loop;
23.  
24. end;

HOW TO INSERT VALUES INTO DEPARTMENT TABLE USING WHILE LOOP

1. declare
2.       v_counter number:=1;
3.  
4.       v_ename varchar2(15):='GVREDDY';
5.  
6.       v_job varchar2(15):='SRINU';
7.  
8.       v_empno number;
9.  
10. begin
11.  
12.     select max(empno) into v_empno from emp_dup;
13.  
14. while v_counter<=3 loop
15.  
16. insert into emp_dup(empno,ename,job) values((v_empno+v_counter),
17.  
18. v_ename,v_job);
19.  
20. v_counter:=v_counter+1;
21.  
22. end loop;
23.  
24. end;
SQL> SELECT * FROM EMP_DUP;

HOW TO INSERT VALUES INTO DEPARTMENT TABLE USING FOR LOOP

1. declare
2.       v_counter number:=1;
3.  
4.       v_ename varchar2(15):='GVREDDY';
5.  
6.       v_job varchar2(15):='SRINU';
7.  
8.       v_empno number;
9.  
10. begin
11.  
12.     select max(empno) into v_empno from emp_dup;
13.  
14. while v_counter<=3 loop
15.  
16. insert into emp_dup(empno,ename,job) values((v_empno+v_counter),
17.  
18. v_ename,v_job);
19.  
20. v_counter:=v_counter+1;
21.  
22. end loop;
23.  
end;
24.
SQL> SELECT * FROM EMP_DUP;
What are the Advantages of using PLSQL over
Traditional SQL
PLSQL has support for SQL and supports Object-Oriented Programming. It’s integration with
Oracle provides better performance, portability and  higher productivity.
 PLSQL Supports the declaration and manipulation of object types and collections.
 PLSQL Allows the calling of external functions and procedures.
 PLSQL Contains new libraries of built in packages. 
 With PL/SQL , an multiple sql statements can be processed in a single command
line statement.
Developers and Database Administrators use PLSQL coding on a daily basis, whether for
application development, finding problems, fine-tuning solutions to those problems, or other
critical Database Administration tasks. Our aim here is to provide answers to PLSQL questions
that Database Administrators come across daily.

PLSQL Interview Questions And Answers For


Practice - Part 4

HOW TO RETRIEVE THE FIRST 10 RECORDS OF THE EMP_DUP TABLE BY USING THE
CURSORS

1. declare

       cursor emp_cursor is select empno,ename from emp_dup;

r emp_cursor%rowtype;

begin

     open emp_cursor;

loop

fetch emp_cursor into r;

dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||r.empno||


r.ename);

exit when emp_cursor%rowcount>=10;


end loop;

close emp_cursor;

end;

HOW TO RETRIEVE THE DETAILS OF THE EMPLOYEES WHOSE DEPARTMENT WAS 10


USING CURSORS

1. declare

      cursor dept_cursor is select * from emp_dup where deptno=10;

r emp_dup%rowtype;

begin

    open dept_cursor;

loop

   fetch dept_cursor into r;

dbms_output.put_line('THE EMPLOYEE DETAILS FOR DEPT20 WAS'||


r.empno||' '

||r.ename||' '||r.job||'  '||r.sal||r.deptno);

exit when dept_cursor%rowcount>=5;

end loop;

close dept_cursor;

end;

HOW TO RETRIEVE THE FIRST 20 RECORD OF THE EMPLOYEE TABLE USING CURSORS

1. declare
2.       cursor emp_20 is select empno,ename from emp_dup;
3.  
4. r emp_20%rowtype;
5.  
6. begin
7.  
8.     open emp_20;
9.  
10. loop
11.  
12.    fetch emp_20 into r;
13.  
14. dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||r.empno||' '||
r.ename);
15.  
16. exit when emp_20%rowcount>=20;
17.  
18. end loop;
19.  
20. dbms_output.put_line('THE NO OF RECORDS DISPLAYED ARE'||
emp_20%rowcount);
21.  
22. close emp_20;
23.  
24. end;

HOW TO RETRIEVE THE FIRST FIVE EMPLOYEES WITH A JOB HISTORY USING CURSORS

1. declare

      cursor emp_job is select * from emp_dup;

r emp_job%rowtype;

begin

     open emp_job;

loop

    fetch emp_job into r;

dbms_output.put_line('EMPLOYEE #:'||r.empno||'held the job of'

||r.job||'from'||r.hiredate);
exit when emp_job%rowcount>5;

end loop;

close emp_job;

end;

HOW TO UPDATE THE SALARY BY 10% FOR THOSE WHOSE SALARIES ARE LESS THAN
5000 USING THE CURSORS

1. declare

      cursor upd_curr is select e.empno,e.ename,e.job,e.sal,

d.deptno,d.loc,d.dname from emp e,dept d where e.deptno=d.deptno and

d.deptno=30 for update of sal NOWAIT;

begin

    for emp_rec in upd_curr

loop

    if emp_rec.sal<5000 then

update emp set sal=emp_rec.sal*1.10 where current of upd_curr;

end if;

end loop;

end;

HOW TO GET TO DISPLAY DEPT AND EMP TABLES TOGETHER USING CURSORS

1. declare

      cursor emp_dept is select d.deptno,d.dname,e.ename,e.job,


e.hiredate,e.sal from emp e,dept_id d where e.deptno=d.deptno;

begin

    for emp_record in emp_dept

loop

if emp_record.deptno <>30 then

dbms_output.put_line('departmentnumber:'||emp_record.deptno||

'department name'||emp_record.dname);

end if;

end loop;

    for emp_record in emp_dept

loop

if emp_record.deptno<>30 then

dbms_output.put_line(emp_record.ename||emp_record.job||
emp_record.hiredate

||emp_record.sal);

end if;

end loop;

for emp_record in emp_dept

loop

if emp_record.deptno=30 then

dbms_output.put_line('departmentnumber:'||emp_record.deptno||

'department name'||emp_record.dname);

end if;

end loop;

for emp_record in emp_dept


loop

if emp_record.deptno=30 then

dbms_output.put_line(emp_record.ename||emp_record.job||
emp_record.hiredate

||emp_record.sal);

end if;

end loop;

end;

HOW TO RETRIEVE THE DETAILS OF THE EMPLOYEES WHOSE DEPARTMENT WAS 100
USING THE CURSORS

1. declare

      cursor dept_cursor is select * from emp_dup where deptno=100;

r emp_dup%rowtype;

begin

    open dept_cursor;

loop

   fetch dept_cursor into r;

dbms_output.put_line('THE EMPLOYEE DETAILS FOR DEPT20 WAS'||


r.empno||' '

||r.ename||' '||r.job||'  '||r.sal||r.deptno);

exit when dept_cursor%rowcount>=5;

end loop;

close dept_cursor;

end;
HOW TO RETRIEVE THE 20 RECORD OF THE EMPLOYEE TABLE USING CURSORS

1. declare
2.       cursor emp_20 is select empno,ename from emp_dup;
3.  
4. r emp_20%rowtype;
5.  
6. begin
7.  
8.     open emp_20;
9.  
10. loop
11.  
12.    fetch emp_20 into r;
13.  
14. dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||r.empno||' '||
r.ename);
15.  
16. exit when emp_20 %rowcount>=20;
17.  
18. end loop;
19.  
20. dbms_output.put_line('THE NO OF RECORDS DISPLAYED ARE'||
emp_20%rowcount);
21.  
22. close emp_20 ;
23.  
24. end;

HOW TO RETRIEVE THE EMPLOYEE NUMBER AND NAME FROM THE EMPLOYEE TABLE
AND INSERT INTO TEMP_LIST TABLE BY USING CURORS AND RECORDS

1. declare
2.       cursor temp_insert is select empno,ename from emp_dup;
3.  
4. emp_record temp_insert%rowtype;
5.  
6. begin
7.  
8.     open temp_insert;
9.  
10. loop
11.  
12.    fetch temp_insert into emp_record;
13.  
14. exit when temp_insert%notfound;
15.  
16. insert into temp_list(empid,tname)
values(emp_record.empno,emp_record.ename);
17.  
18. end loop;
19.  
20. close temp_insert;
21.  
22. end;

SQL SERVER

How to DECLARE and SET Variables in SQL Server TSQL


1. DECLARE @Jokoint
2. SET @Joko = 1
3. SELECT @Joko = Column FROM Table
4. WHERE id=1
 IF / ELSE IF / ELSE Statement in SQL Server TSQL
1. IF @Joko < 1
2. BEGINPRINT 'Joko Is less than 1'
3. END
4. ELSE IF @Joko = 1
5. BEGINPRINT 'Joko Is 1'
6. END
7. ELSE
8. BEGIN
9. PRINT 'Joko greater than 1'
10. END
 How to create a CASE Statement in SQL Server TSQL
1. SELECT Day = CASE
2. WHEN (DateAdded IS NULL) THEN
3. 'Unknown'
4. WHEN (DateDiff(day, DateAdded,
5. getdate()) = 0) THEN 'Today'
6. WHEN (DateDiff(day, DateAdded,
7. getdate()) = 1) THEN 'Yesterday'
8. WHEN (DateDiff(day, DateAdded,
9. getdate()) = -1) THEN 'Tomorrow'
10. ELSE DATENAME(dw , DateAdded)
11. END
12. FROM Table
How to Add A Column in SQL Server TSQL
1. ALTER TABLE YourTableName
2. ADD[ColumnName] [int] NULL;
How to Rename a Column in SQL Server TSQL
1. EXEC sp_rename
2. 'TableName.OldColName',
3. 'NewColName','COLUMN';
How to Rename Table in SQL Server TSQL
1. EXEC sp_rename 'OldTableName',
2. 'NewTableName';
How to Add a Foreign Key in SQL Server TSQL
1. ALTER TABLE Products WITH CHECK
2. ADD CONSTRAINT [FK_Prod_Man]
3. FOREIGN KEY(ManufacturerID)
4. REFERENCES Manufacturers (ID);
How to Add a NULL Constraint in SQL Server TSQL
1. ALTER TABLE TableName
2. ALTER COLUMN ColumnName int NOT NULL;
How to Set Default Value for Column in SQL Server TSQL
1. ALTER TABLE TableName
2. ADD CONSTRAINT
3. DF_TableName_ ColumnName DEFAULT 0
4. FOR ColumnName;
How to Create an Index in SQL Server TSQL
1. CREATE INDEX IX_Index_Name ON Table(Columns)
How to Check Constraint in SQL Server TSQL
1. ALTER TABLE TableName
2. ADD CONSTRAINT CK_CheckName CHECK
3. (ColumnValue > 1)
How to create Single Line Comments in SQL Server TSQL
1. SET @mojo = 1 --THIS IS A COMMENT
How to Create Multi-Line Comments in SQL Server TSQL
1. /* This is a comment that can span multiple lines*/
How to create Try / Catch Statements in SQL Server TSQL
1. BEGIN TRY
2. -- try / catch requires
3. SQLServer 2017
4. -- run your code here
5. END TRY
6. BEGIN CATCH
7. PRINT 'Error Number: ' +
8. str(error_number())
9. PRINT 'Line Number: ' +
10. str(error_line())
11. PRINT error_message()
12. -- handle error condition
13. END CATCH
How to Create While Loop in SQL Server TSQL
1. DECLARE @i int
2. SET @i = 0
3. WHILE (@i < 10)
4. BEGIN
5. SET @i = @i + 1
6. PRINT @i
7. IF (@i >= 10)
8. BREAK
9. ELSE
10. CONTINUE
11. END
How to CREATE a Table in SQL Server TSQL
1. CREATE TABLE TheNameOfYourTable (
2. ID INT NOT NULL IDENTITY(1,1),
3. DateAdded DATETIME
4. DEFAULT(getdate()) NOT NULL,
5. Description VARCHAR(100) NULL,
6. IsGood BIT DEFAULT(0) NOT NULL,
7. TotalPrice MONEY NOT NULL,
8. CategoryID int NOT NULL
9. REFERENCES Categories(ID),
10. PRIMARY KEY (ID)
11. );
How to Create User Defined Function in SQL Server TSQL
1. CREATE FUNCTION dbo.DoStuff(@ID int)
2. RETURNS int
3. AS
4. BEGIN
5. DECLARE @result int
6. IF @ID = 0
7. BEGIN
8. RETURN 0
9. END
10. SELECT @result = COUNT(*)
11. FROM table WHERE ID = @ID
12. RETURN @result
13. END
14. GO
15. SELECT dbo.DoStuff(0)

You might also like