Post on 06-Aug-2015
INDEX
1. Query for retrieving N highest paid employees FROM each Department.2. Query that will display the total no. of employees, and of that total the number
who were hired in 1980, 1981, 1982, and 1983. 3. Query for listing Deptno, ename, sal, SUM(sal in that dept).4. Matrix query to display the job, the salary for that job based on department
number, and the total salary for that job for all departments.5. Nth Top Salary of all the employees. 6. Retrieving the Nth row FROM a table. 7. Tree Query. 8. Eliminate duplicates rows in a table. 9. Displaying EVERY Nth row in a table. 10. Top N rows FROM a table.11. COUNT/SUM RANGES of data values in a column. 12. For equal size ranges it might be easier to calculate it with
DECODE(TRUNC(value/range), 0, rate_0, 1, rate_1, ...). 13. Count different data values in a column. 14. Query to get the product of all the values of a column. 15. Query to display only the duplicate records in a table.16. Query for getting the following output as many number of rows in the table. 17. Function for getting the Balance Value. 18. Function for getting the Element Value. 19. SELECT Query for counting No of words.20. Function to check for a leap year.21. Query for removing all non-numeric.22. Query for translating a column values to INITCAP.23. Function for displaying Rupees in Words.24. Function for displaying Numbers in Words25. Query for deleting alternate even rows FROM a table. 26. Query for deleting alternate odd rows FROM a table. 27. Procedure for sending Email. 28. Alternate Query for DECODE function. 29. Create table adding Constraint to a date field to SYSDATE or 3 months later.30. Query to list all the suppliers who r supplying all the parts supplied by supplier
'S2'. 31. Query to get the last Sunday of any month.32. Query to get all those who have no children themselves. 33. Query to SELECT last N rows FROM a table. 34. SELECT with variables. 35. Query to get the DB Name. 36. Getting the current default schema. 37. Query to get all the column names of a particular table. 38. Spool only the query result to a file in SQLPLUS. 39. Query for getting the current SessionID. 40. Query to display rows FROM m to n. 41. Query to count no. Of columns in a table. 42. Procedure to increase the buffer length. 43. Inserting an & symbol in a Varchar2 column. 44. Removing Trailing blanks in a spooled file. 45. Samples for executing Dynamic SQL Statements. 46. Differences between SQL and MS-Access. 47. Query to display all the children, sub children of a parent. 48. Procedure to read/write data from/to a text file.
Patni Public
49. Query to display random number between any two given numbers. 50. Time difference between two date columns. 51. Using INSTR and SUBSTR52. View procedure code 53. To convert signed number to number in oracle54. Columns of a table55. Delete rows conditionally56. CLOB to Char 57. Change Settings58. Double quoting a Single quoted String59. Time Conversion60. Table comparison61. Running Jobs62. Switching Columns63. Replace and Round64. First date of the year65. Create Sequence66. Cursors67. Current Week68. Create Query to restrict the user to a single row. 69. Query to get the first inserted record FROM a table. 70. Concatenate a column value with multiple rows. 71. Query to delete all the tables at once. 72. SQL Query for getting Orphan Records.
1. The following query retrieves "2" highest paid employees FROM each Department:
SELECT deptno, empno, salFROM emp eWHERE 2 > ( SELECT COUNT(e1.sal) FROM emp e1 WHERE e.deptno = e1.deptno AND e.sal < e1.sal )ORDER BY 1,3 DESC;
SELECT * FROM EMP A WHERE &N > ( SELECT COUNT(DISTINCT SAL) FROM EMP B WHERE B.SAL>A.SAL) ORDER BY A.SAL DESC;
SELECT * FROM(SELECT * FROM emp ORDER BY salary DESC)WHERE ROWNUM <3
Index
Patni Public
2. Query that will display the total no. of employees, and of that total the number who were hired in 1980, 1981, 1982, and 1983. Give appropriate column headings.
I am looking at the following output. We need to stick to this format.
Total 1980 1981 1982 1983----------- ------------ ------------ ------------- -----------14 1 10 2 1
SELECT COUNT (*), COUNT(DECODE(TO_CHAR (hiredate, 'YYYY'),'1980', empno)) "1980", COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1981', empno)) "1981",
COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1982', empno)) "1982", COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1983', empno)) "1983"
FROM emp;
Index
3. Query for listing Deptno, ename, sal, SUM(sal in that dept) : SELECT a.deptno, ename, sal, (SELECT SUM(sal) FROM emp b WHERE a.deptno = b.deptno) FROM emp aORDER BY a.deptno;
OUTPUT :=======DEPTNO ENAME SAL SUM (SAL)========= ======= ==== ========= 10 KING 5000 11725 30 BLAKE 2850 10900 10 CLARK 2450 11725 10 JONES 2975 11725 30 MARTIN 1250 10900 30 ALLEN 1600 10900 30 TURNER 1500 10900 30 JAMES 950 10900 30 WARD 2750 10900 20 SMITH 8000 33000 20 SCOTT 3000 33000 20 MILLER 20000 33000
Index
Patni Public
4. Create a matrix query to display the job, the salary for that job based on department number, and the total salary for that job for all departments, giving each column an appropriate heading.
The output is as follows - we need to stick to this format :
Job Dept 10 Dept 20 Dept 30 Total---------- --------------- ------------- ------------- ---------ANALYST 6000 6000CLERK 1300 1900 950 4150MANAGER 2450 2975 2850 8275PRESIDENT 5000 5000SALESMAN 5600 5600
SELECT job "Job", SUM (DECODE (deptno, 10, sal)) "Dept 10", SUM (DECODE (deptno, 20, sal)) "Dept 20", SUM (DECODE (deptno, 30, sal)) "Dept 30", SUM (sal) "Total"
FROM empGROUP BY job ;
Index
5. 4th Top Salary of all the employees :
SELECT DEPTNO, ENAME, SAL FROM EMP AWHERE3 = (SELECT COUNT(B.SAL) FROM EMP BWHERE A.SAL < B.SAL) ORDER BY SAL DESC;
SELECT * FROM EMP AWHERE &N-1 = (SELECT COUNT (DISTINCT SAL) FROM EMP B WHERE B.SAL>A.SAL);
Alternate
SELECT ename, deptno, sal FROM (SELECT * FROM emp ORDER BY sal DESC) WHERE ROWNUM < N;
Index
6.1 Retrieving the 5th row FROM a table :
SELECT DEPTNO, ENAME, SAL FROM EMP WHERE ROWID = (SELECT ROWID FROM EMP WHERE ROWNUM <= 5
MINUS SELECT ROWID FROM EMP WHERE ROWNUM < 5)
Patni Public
6.2 Display the alternate row from the table.
select rownum,empno,ename from emp group by rownum,empno,ename having mod(rownum,2)=0; OR
select * from emp where rowid in (select decode(mod(rownum,2),0,rowid) from emp) OR For Even Rownumber Select * from emp Where (rowid,0) in (select rowid, mod(rownum,2) from emp)
For Odd Rownumber Select * from emp Where (rowid, 1) in (select rowid, mod(rownum,2) from emp)
Index
7. Tree Query :
Name Null? Type-------------------------------------------------------------------SUB NOT NULL VARCHAR2(4)SUPER VARCHAR2(4)PRICE NUMBER(6,2)
SELECT sub, super FROM partsCONNECT BY PRIOR sub = superSTART WITH sub = 'p1';
Index
8. Eliminate duplicates rows in a table :
DELETE FROM table_name A WHERE ROWID > ( SELECT min(ROWID) FROM table_name B WHERE A.col = B.col);
OR
DELETE FROM table_name A WHERE ROWID < ( SELECT max(ROWID) FROM table_name B WHERE A.col = B.col);
Index
Patni Public
15. Query to display only the duplicate records in a table:
SELECT num FROM satyam GROUP BY numHAVING COUNT(*) > 1;
Index
9. Displaying EVERY 4th row in a table : (If a table has 14 rows, 4,8,12 rows will be selected)
SELECT *FROM empWHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4)
FROM emp);ALTERNATE
SELECT * FROM TB_CNR014_DIM_BRAND WHERE ROWID IN (SELECT DECODE(MOD(BRAND_ID, 4), 0, ROWID) FROM TB_CNR014_DIM_BRAND)
25. Query for deleting alternate even rows FROM a table :
DELETEFROM srinuWHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,2) FROM srinu);
26. Query for deleting alternate odd rows FROM a table :
DELETEFROM srinuWHERE (ROWID,1) IN (SELECT ROWID, MOD(ROWNUM,2) FROM srinu);
Index
10. Top N rows FROM a table : (Displays top 9 salaried people)
SELECT ename, deptno, sal FROM (SELECT * FROM emp ORDER BY sal DESC) WHERE ROWNUM < 10;
Index
11. How does one count/sum RANGES of data values in a column? A value x will be between values y and z if GREATEST(x, y) = LEAST(x, z).
SELECT f2,
COUNT(DECODE(greatest(f1,59), least(f1,100), 1, 0)) "Range 60-100", COUNT(DECODE(greatest(f1,30), least(f1, 59), 1, 0)) "Range 30-59",
Patni Public
COUNT(DECODE(greatest(f1,29), least(f1, 0), 1, 0)) "Range 00-29" FROM my_table GROUP BY f2;
Correct Answer: Do not Consider 0
SELECT COUNT(*), count(decode( greatest(field_3,20),least(field_3,49),1)) AS "Range 20-50", count(decode( greatest(field_3,50),least(field_3,59),1)) AS "Range 50-60", count(decode( greatest(field_3,60),least(field_3,69),1)) AS "Range 60-70", count(decode( greatest(field_3,90),least(field_3,99),1)) AS "Range 90-100"FROM test_mapping
Alternate Answer:
SELECT COUNT(*), count(CASE WHEN field_3 > 20 AND field_3 < 50 THEN field_3 END) AS "Range 20-50" , count(CASE WHEN field_3 >= 50 AND field_3 < 60 THEN field_3 END)AS "Range 50-60" , count(CASE WHEN field_3 >= 60 AND field_3 < 70 THEN field_3 END)AS "Range 60-70", count(CASE WHEN field_3 >= 90 AND field_3 < 100 THEN field_3 END)AS "Range 90-100"FROM test_mapping
Index
12. For equal size ranges it migth be easier to calculate it with DECODE(TRUNC(value/range), 0, rate_0, 1, rate_1, ...).
SELECT ename "Name", sal "Salary", DECODE( TRUNC(sal/1000, 0), 0, 0.0, 1, 0.1, 2, 0.2, 3, 0.3) "Tax rate"FROM emp;
13. How does one count different data values in a column?
COL NAME DATATYPE----------------------------------------DNO NUMBERSEX CHAR
SELECT dno, SUM(DECODE(sex,'M',1,0)) MALE, SUM(DECODE(sex,'F',1,0)) FEMALE, COUNT(DECODE(sex,'M',1,'F',1)) TOTALFROM t1GROUP BY dno;
Index
14. Query to get the product of all the values of a column :
SELECT EXP(SUM(LN(col1))) FROM srinu;
Index
Patni Public
16. Query for getting the following output as many number of rows in the table :
***************
SELECT RPAD(DECODE(temp,temp,'*'),ROWNUM,'*') FROM srinu1;
Index
17. Find the date of last Thursday of the Month
select next_day(last_day(sysdate)-7,’thursday’) from dual;
18. Update multiple row in using single update statement.
Update emp set sal= Case job When ‘CLERK’ then sal+500 When ‘SALESMAN’ then sal+600 When ‘MANAGER’ then sal+2000 Else sal End;
OR
Update emp set sal= Decode(job,’CLERK’,sal+200,’SALESMAN’,sal+300,’MANAGER’,sal+500);
19. Show the ename of all employees together with the number of completed months that they have been employed.
SELECT ENAME,TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12) YEAR, MOD(TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)),12) MONTH FROM EMP
20. Display the following output:
DNO ASAL ECOUNT ENAME SAL JOB---- ---------- ---------- ---------- ---------- --------- 10 2916.66667 3 CLARK 2450 MANAGER KING 5000 PRESIDENT MILLER 1300 CLERK
20 3614.8 5 SMITH 4000 CLERK ADAMS 1100 CLERK FORD 3000 ANALYST SCOTT 6999 ANALYST JONES 2975 MANAGER
Patni Public
30 1400 6 ALLEN 600 SALESMAN BLAKE 2850 MANAGER MARTIN 1250 SALESMAN JAMES 950 CLERK TURNER 1500 SALESMAN WARD 1250 SALESMAN
SOLUTION:
BREAK ON DNO ON ASAL ON ECOUNT SKIP 1 select d.deptno dno,avg(d.sal) asal,count(d.ename) ecount, e.ename,e.sal,e.job from emp d,emp e where d.deptno=e.deptno group by d.deptno,e.ename,e.sal,e.job
OR
SELECT DNO,ASAL,ECOUNT,E.ENAME,E.SAL,E.JOB FROM (SELECT DEPTNO DNO, AVG(SAL) ASAL,COUNT(ENAME) ECOUNT FROM EMP GROUP BY DEPTNO),EMP E WHERE DNO=E.DEPTNO;
21.Display the first and second higest sal from each deprtment
select deptno,max(sal) from emp group by deptnounionselect deptno,max(sal) from (select deptno,sal from emp minusselect deptno,max(sal) from emp group by deptno) group by deptno
or
select sal from emp e1 where &n>=(select count(distinct sal) from emp e2 where e1.sal<=e2.sal and e1.deptno=e2.deptno)
22. Date related Query.
Find out the current date:
Select sysdate from dual;
Find out the date of the next date
Select sysdate+1 from dual;
Find out the one hour from now
Select to_char(sysdate+1/24,’hh’) from dual;
Find out the three hours from now
Select to_char(sysdate+3/24,’hh’) from dual;
Find out the half an hour from now
Patni Public
Select to_char(sysdate+1/48,’hh:mi’) from dual;
Find out the 10 minutes from now
Select to_char(sysdate+10/1440,’mi’) from dual;
Find out the 10 second from now
Select to_char(sysdate+10/86400,’SS’) from dual;
Find out the tomorrow at the midinight 12:00
Select to_char(trunc(sysdate+1),’dd-mm-yy-/hh:mi:ss’) from dual;
Find the date of tomorrow at 8:00 A.M.
Select to_char(trunc(sysdate+1)+8/24) from dual;
Find out the next Monday at 12:00 noon
Select next_day(trunc(sysdate),'Monday')+12/24 from dual;
Find out the first day of next month at 12 mid night
Select trunc(last_day(sysdate)+1) from dual;
Find out the first day of current month
Select last_day(add_months(sysdate,-1))+1 from dual;
23. Display the bytes occupied by each ename in the emp table.
Select vsize(ename) from emp;
24. Diplat the our age in days.
Select to_date(sysdate)-to_date('14-Aug-1980') Days from dual;
25. Display the our age in year.
select trunc(trunc(months_between(sysdate,'14-aug-80'))/12) year from dual;
26. Display the emp whose sal is greater than their manager.
select e.ename from emp e,emp m where e.mgr=m.empno and e.sal>m.sal;
27.Display the emp who are working in the same dept where his manager is working.
select e.ename from emp e,emp m where e.mgr=m.empno and e.deptno=m.deptno;
28.Display the ename whose manager is blake.
Patni Public
select e.ename from emp e,emp m where e.mgr=m.empno and m.ename=’BLAKE’;
29. Find the date for nearest Saturday after current date.
Select next_day(sysdate,’saturday’) from dual;
DDL Queries.
30. Rename the column name from the table.
alter table ddl rename column empno to eno;
31. Rename the table name
rename ddl to emp;
32. Drop the column from any table
alter table ttl drop column sal
33. Add the column in the table.
Alter table ttl add(sal number(4));
34. Add constraint in the table.
Alter table ttl add(empno number primary key);
35. Count the No. of Column from particular table.
select count(*) from cols where table_name='EMP';
36. Insert data from one table to another table.
Insert into emp1 select * from emp;
37. .create table structure from another table.
Create table emp1 as select * from emp;38. Create index command
create index i1 on ttl(empno);create bitmap index bi on ttl(mgr);create index i2 on ttl(job) online;
39. Create cluster command.
Create cluster c1 (empno number);
Patni Public
40. Multi table update using trigger.
create or replace trigger multi_table_update after update of sal on emp for each row begin update emp1 set sal=:new.sal where empno=7369; update emp2 set sal=:new.sal where empno=7369; end; / 41. PL/sql user defined datatypes or userdifined datatypes.
pl/sql user defined data types=======================1.Record type2.Object type3.collection type
There are two types of collection---------------------------------- a.Table type b.Varray
There are two types of table ------------------------------- aa.Index-by-table or (pl/sql table) or (assosciative array) bb.Nested Table
Implementation:============Record Type:==========
Unlike varray,table types, record type cannot be created and stored in the database.
Ex1:-declare type deptrec is record( dept_id dept.deptno%type, dept_name varchar2(14), dept_loc varchar2(13));ex2:-declare type stockitem is record( item_no integer(30), description varchar2(50), quantity integer, price real(7,2));ex3:-declare type emprec is record( emp_id emp.emno%type, last_name varchar2(20), job_title varchar2(9),
Patni Public
salary number(7,2));Object types=============ex1:-------create type coplex as object ( rpart real, --attribute ipart real, member function plus (c complex) return comples, --method member function less (x complex) return complex, member function times(x complex) return complex, member function divby(x comples) return complex
);
create type body complex as
member function plus (x complex) return complex is begin return complex(rpart+x.rpart,ipart+x.ipart); end plus;
member function less (x complex) return comples is begin return complex(rpart-x.rpart,ipart-x.ipart); end less;
member function times (x complex) return complex is begin return complex(rpart*x.rpart-ipart*x.ipart, rpart*s.ipart+ipart*x.ipart); end times;
member function divby (x complex) return complex is z real:=x.rpart**2+x.ipart**2; begin return complex((rpart*x.rpart+ipart*x.ipart)/z, (ipart*x.rpart-rpart*x.ipart)/z); end divby;end;/
ex2:-create type Stack as object ( max_size integer, top integer, position intarray, --intarray is varray type member procedure initialize, member function full return boolean, member function empty return boolean, member procedure push (n in integer), member procedure pop (N OUT INTEGER));
Patni Public
CREATE TYPE BODY Stack AS MEMBER PROCEDURE initialize IS BEGIN top := 0; position := IntArray(NULL); max_size := position.LIMIT; -- get varray size constraint position.EXTEND(max_size - 1, 1); -- copy element 1 into 2..25 END initialize;
MEMBER FUNCTION full RETURN BOOLEAN IS BEGIN RETURN (top = max_size); -- return TRUE if stack is full END full;
MEMBER FUNCTION empty RETURN BOOLEAN IS BEGIN RETURN (top = 0); -- return TRUE if stack is empty END empty; MEMBER PROCEDURE push (n IN INTEGER) IS BEGIN IF NOT full THEN top := top + 1; -- push integer onto stack position(top) := n; ELSE -- stack is full RAISE_APPLICATION_ERROR(-20101, ’stack overflow’); END IF; END push; MEMBER PROCEDURE pop (n OUT INTEGER) IS BEGIN IF NOT empty THEN n := position(top); top := top - 1; -- pop integer off stack ELSE -- stack is empty RAISE_APPLICATION_ERROR(-20102, ’stack underflow’); END IF; END pop; END; /Collection Type ==================Index by table----------------ex1:----DECLARE
TYPE associative_array_type IS TABLE OF NUMBERINDEXED BY BINARY_INTEGER;v1 associative_array_type; ex2:------DECLARE
Patni Public
TYPE population_type IS TABLE OF NUMBER INDEX BY VARCHAR2(64);country_population population_type;continent_population population_type;howmany NUMBER;which VARCHAR2(64)BEGINcountry_population(’Greenland’) := 100000;country_population(’Iceland’) := 750000;howmany := country_population(’Greenland’);continent_population(’Australia’) := 30000000;continent_population(’Antarctica’) := 1000; -- Creates new entrycontinent_population(’Antarctica’) := 1001; -- Replaces previousvaluewhich := continent_population.FIRST; -- Returns ’Antarctica’-- as that comes first alphabetically.which := continent_population.LAST; -- Returns ’Australia’howmany := continent_population(continent_population.LAST);-- Returns the value corresponding to the last key, in this-- case the population of Australia.END;/Nested Table-------------ex1:-------CREATE TYPE CourseList AS TABLE OF VARCHAR2(10) -- define type/CREATE TYPE Student AS OBJECT ( -- create objectid_num INTEGER(4),name VARCHAR2(25),address VARCHAR2(35),status CHAR(2),courses CourseList) -- declare nested table as attribute/varray--------CREATE TYPE ProjectList AS VARRAY(50) OF VARCHAR2(16);/
CREATE TABLE department ( -- create database tabledept_id NUMBER(2),name VARCHAR2(15),budget NUMBER(11,2),-- Each department can have up to 50 projects.projects ProjectList)/
Patni Public
42. Perform scd type1 using pl/sql
CREATE OR REPLACE PROCEDURE PROCEDURE_SCD1 IS BEGIN MERGE INTO PROC_SCD1 T USING EMP S ON(T.EMPNO=S.EMPNO) WHEN MATCHED THEN UPDATE SET T.SAL=S.SAL WHEN NOT MATCHED THENINSERT VALUES(S.EMPNO,S.ENAME,S.JOB,S.MGR,S.HIREDATE,S.SAL,S.COMM,S.DEPTNO); END; /43. perform scd2 through pl/sql
CREATE OR REPLACE PROCEDURE PROCEDURE_SCD2 IS BEGIN INSERT ALL WHEN PK IS NULL THEN INTO PROC_SCD2 VALUES(S1.NEXTVAL,EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO,1000) WHEN PK IS NOT NULL AND SAL<>TGT_SAL THEN INTO PROC_SCD2VALUES(S1.NEXTVAL,EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO,VERSION+1) SELECT PK,EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO, TGT_EMPNO ,TGT_ENAME ,TGT_JOB ,TGT_MGR ,TGT_HIREDATE, TGT_SAL ,TGT_COMM ,TGT_DEPTNO,VERSION FROM EMP LEFT OUTER JOIN ( SELECT * FROM PROC_SCD2 WHERE ROWID IN ( SELECT MAX(ROWID) FROM PROC_SCD2 GROUP BY TGT_EMPNO)) ON (TGT_EMPNO=EMPNO);END ;/
DROP SEQUENCE S1;CREATE SEQUENCE S1START WITH 1INCREMENT BY 1MAXVALUE 15000
Patni Public
MINVALUE 1NOCACHENOCYCLE;
EXEC PROCEDURE_SCD2;
SELECT * FROM PROC_SCD2;
44. Write a procedure to load the time dimension.
create table time_dim(v_pm number(8),V_DATE DATE,DAY VARCHAR2(20),DAY_NO_OF_MONTH NUMBER(4),WEEK_OF_MONTH NUMBER(4),MONTH_NO NUMBER(4),MONTH_NAME VARCHAR2(20),WEEK_OF_YEAR NUMBER(4),DAY_NO_OF_YEAR NUMBER(4),YEAR NUMBER(4));
drop sequence seq;create sequence seqstart with 1increment by 1maxvalue 150000minvalue 1nocachenocycle/
CREATE OR REPLACE procedure proc_time_dim(i_date date,l_date date)isv_date date;v_day varchar2(20);v_day_no_of_month number(4);v_week_no_month number(4);v_month_no number(4);v_month_name varchar2(20);v_week_of_year number(4);v_day_no_of_year number(4);v_year number(4);v number(8):=1;beginv_date:=i_date;while(l_date>=v_date)loopv_day:=to_char(V_date,'Day');v_day_no_of_month:=to_number(to_char(V_date,'dd'));v_week_no_month:=to_number(to_char(V_date,'w'));
Patni Public
v_month_no:=to_number(to_char(V_date,'mm'));v_month_name:=to_char(V_date,'Month');v_week_of_year:=to_number(to_char(V_date,'ww'));v_day_no_of_year:=to_number(to_char(V_date,'ddd'));v_year:=to_number(to_char(V_date,'yyyy'));insert into time_dim values(seq.nextval,v_date,v_day,v_day_no_of_month,v_week_no_month,v_month_no,v_month_name,v_week_of_year,v_day_no_of_year,v_year);v_date:= v_date+1;end loop;end proc_time_dim;/
truncate table time_dim;EXEC PROC_TIME_DIM(2003,2003);SELECT * FROM TIME_dIM ORDER BY V_PM;
45. Storage Units.
Storage Units================ 2 bit=1 b
1024 b=1kb 1024 kb=1mb =1024*1024b 1024 mb=1gb =1024*1024*1024b 1024 gb=1tb =1024*1024*1024*1024b 1024 tb=1zb =1024*1024*1024*1024*1024b
where b=byte, kb=kilo byte, mb=mega byte, gb=giga byte, tb=tera byte, zb=zega byte
Cluster:
A cluster provides an optional method of storing table data. A cluster is made up of a group of tables that share the same data blocks. The tables are grouped together because they share common columns and are often used together. For example, the emp and dept table share the deptno column. When you cluster the emp and dept tables (see Figure 18–1), Oracle physically stores all rows for each department from both the emp and dept tables in the same data blocks. Because clusters store related rows of different tables together in the same data blocks, properly used clusters offer two primary benefits:
Patni Public
<> Disk I/O is reduced and access time improves for joins of clustered tables.<> The cluster key is the column, or group of columns, that the clustered tables have in common.
You specify the columns of the cluster key when creating the cluster. You subsequently specify the same columns when creating every table added to the cluster. Each cluster key value is stored only once each in the cluster and the cluster index, no matter how many rows of different tables contain the value.Therefore, less storage might be required to store related table and index data in a cluster than is necessary in non-clustered table format. For example, in Figure 18–1, notice how each cluster key (each deptno) is stored just once for many rows that contain the same value in both the emp and dept tables.After creating a cluster, you can create tables in the cluster. However, before any rows can be inserted into the clustered tables, a cluster index must be created. <> Using clusters does not affect the creation of additional indexes on the clustered tables;<> They can be created and dropped as usual.<> You should not use clusters for tables that are frequently accessed individually.
Patni Public
17. Function for getting the Balance Value:
FUNCTION F_BALANCE_VALUE(p_business_group_id number, p_payroll_action_id number, p_balance_name varchar2, p_dimension_name varchar2) RETURN NUMBER ISl_bal number;l_defined_bal_id number;l_assignment_action_id number;BEGIN SELECT assignment_action_id
INTO l_assignment_action_id FROM pay_assignment_actions
WHEREassignment_id = :p_assignment_idAND payroll_action_id = p_payroll_action_id;
SELECT defined_balance_id INTO l_defined_bal_id FROM pay_balance_types pbt, pay_defined_balances pdb, pay_balance_dimensions pbd WHERE pbt.business_group_id = p_business_group_id AND UPPER(pbt.balance_name) = UPPER(p_balance_name) AND pbt.business_group_id = pdb.business_group_id AND pbt.balance_type_id = pdb.balance_type_id AND UPPER(pbd.dimension_name) = UPPER(p_dimension_name) AND pdb.balance_dimension_id = pbd.balance_dimension_id; l_bal := pay_balance_pkg.get_value(l_defined_bal_id,l_assignment_action_id); RETURN (l_bal); exception
WHEN no_data_found THEN
Patni Public
RETURN 0; END;
Index
18. Function for getting the Element Value :
FUNCTION f_element_value( p_classification_name in varchar2, p_element_name in varchar2, p_business_group_id in number, p_input_value_name in varchar2, p_payroll_action_id in number, p_assignment_id in number ) RETURN number IS l_element_value number(14,2) default 0; l_input_value_id pay_input_values_f.input_value_id%type; l_element_type_id pay_element_types_f.element_type_id%type;BEGIN
SELECT DISTINCT element_type_idINTO l_element_type_idFROM pay_element_types_f pet,
pay_element_classifications pecWHERE pet.classification_id = pec.classification_idAND upper(classification_name) = upper(p_classification_name)AND upper(element_name) = upper(p_element_name)AND pet.business_group_id = p_business_group_id;
SELECT input_value_idINTO l_input_value_idFROM pay_input_values_fWHERE upper(name) = upper(p_input_value_name)AND element_type_id = l_element_type_id;
SELECT NVL(prrv.result_value,0) INTO l_element_value FROM pay_run_result_values prrv, pay_run_results prr,
pay_assignment_actions paa WHERE prrv.run_result_id = prr.run_result_id
AND prr.assignment_ACTION_ID = paa.assignment_action_id AND paa.assignment_id = p_assignment_id AND input_value_id = l_input_value_id
AND paa.payroll_action_id = p_payroll_action_id;
RETURN (l_element_value); exception
WHEN no_data_found THEN RETURN 0;
END;
Index
Patni Public
19. SELECT Query for counting No of words:
SELECT ename,NVL(LENGTH(REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ',' @'),' ',''))+1,1) word_lengthFROM emp;
Explanation :
TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ',' @') -- This will translate all the characters FROM A-Z including a single quote to a space. It will also translate a space to a @.
REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ',' @'),' ','') -- This will replace every space with nothing in the above result.
LENGTH(REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ',' @'),' ',''))+1 -- This will give u the count of @ characters in the above result.
Alternate:
SELECT length('samir') - length(REPLACE('samir','r','')) FROM dual;
Index
20. Function to check for a leap year:
CREATE OR REPLACE FUNCTION is_leap_year (p_date IN DATE) RETURN VARCHAR2 AS v_test DATE; BEGIN
v_test := TO_DATE ('29-Feb-' || TO_CHAR (p_date,'YYYY'),'DD-Mon-YYYY'); RETURN 'Y';
EXCEPTION WHEN OTHERS THEN
RETURN 'N'; END is_leap_year; SQL> SELECT hiredate, TO_CHAR (hiredate, 'Day') weekday FROM emp WHERE is_leap_year (hiredate) = 'Y';
Index
21. Query for removing all non-numeric :
SELECT TRANSLATE(LOWER(ssn),'abcdefghijklmnopqrstuvwxyz- ','') FROM DUAL;
Patni Public
Index22. Query for translating a column values to INITCAP :
SELECT TRANSLATE(INITCAP(temp),SUBSTR(temp, INSTR(temp,'''')+1,1), LOWER(SUBSTR(temp, INSTR(temp,'''')+1)))FROM srinu1;
Index
23. Function for displaying Rupees in Words :
CREATE OR REPLACE FUNCTION RUPEES_IN_WORDS(amt IN NUMBER) RETURN CHARIS amount NUMBER(10,2); v_length INTEGER := 0; v_num2 VARCHAR2 (50) := NULL; v_amount VARCHAR2 (50); v_word VARCHAR2 (4000) := NULL; v_word1 VARCHAR2 (4000) := NULL; TYPE myarray IS TABLE OF VARCHAR2 (255); v_str myarray := myarray (' thousand ', ' lakh ', ' crore ', ' arab ', ' kharab ', ' shankh ');BEGIN
amount := amt;IF ((amount = 0) OR (amount IS NULL)) THEN
v_word := 'zero';ELSIF (TO_CHAR (amount) LIKE '%.%') THEN
IF (SUBSTR (amount, INSTR (amount, '.') + 1) > 0) THEN v_num2 := SUBSTR (amount, INSTR (amount, '.') + 1); IF (LENGTH (v_num2) < 2) THEN v_num2 := v_num2 * 10; END IF;
v_word1 := ' AND ' || (TO_CHAR (TO_DATE (SUBSTR (v_num2, LENGTH (v_num2) - 1,2), 'J'), 'JSP' ))|| ' paise ';
v_amount := SUBSTR(amount,1,INSTR (amount, '.')-1); v_word := TO_CHAR (TO_DATE (SUBSTR (v_amount, LENGTH (v_amount) - 2,3), 'J'), 'Jsp' ) || v_word; v_amount := SUBSTR (v_amount, 1, LENGTH (v_amount) - 3); FOR i in 1 .. v_str.COUNT LOOP EXIT WHEN (v_amount IS NULL); v_word := TO_CHAR (TO_DATE (SUBSTR (v_amount, LENGTH (v_amount) - 1,2), 'J'), 'Jsp' ) || v_str (i) || v_word; v_amount := SUBSTR (v_amount, 1, LENGTH (v_amount) - 2); END LOOP; END IF;
ELSE
Patni Public
v_word := TO_CHAR (TO_DATE (SUBSTR (amount, LENGTH (amount) - 2,3), 'J'), 'Jsp' ); amount := SUBSTR (amount, 1, LENGTH (amount) - 3); FOR i in 1 .. v_str.COUNT LOOP EXIT WHEN (amount IS NULL); v_word := TO_CHAR (TO_DATE (SUBSTR (amount, LENGTH (amount) - 1,2), 'J'), 'Jsp' ) || v_str (i) || v_word; amount := SUBSTR (amount, 1, LENGTH (amount) - 2); END LOOP;
END IF;
v_word := v_word || ' ' || v_word1 || ' only '; v_word := REPLACE (RTRIM (v_word), ' ', ' '); v_word := REPLACE (RTRIM (v_word), '-', ' ');
RETURN INITCAP (v_word);END;
Index
24. Function for displaying Numbers in Words:SELECT TO_CHAR( TO_DATE( SUBSTR( TO_CHAR(5373484),1),'j'),'Jsp') FROM DUAL;
Only up to integers from 1 to 5373484
Index
27. Procedure for sending Email :
CREATE OR REPLACE PROCEDURE Send_Mail IS sender VARCHAR2(50) := 'sender@something.com'; recipient VARCHAR2(50) := 'recipient@something.com'; subject VARCHAR2(100) := 'Test Message';message VARCHAR2(1000) := 'This is a sample mail ....';lv_mailhost VARCHAR2(30) := 'HOTNT002'; l_mail_conn utl_smtp.connection; lv_crlf VARCHAR2(2):= CHR( 13 ) || CHR( 10 ); BEGIN l_mail_conn := utl_smtp.open_connection (lv_mailhost, 80); utl_smtp.helo ( l_mail_conn, lv_mailhost); utl_smtp.mail ( l_mail_conn, sender); utl_smtp.rcpt ( l_mail_conn, recipient); utl_smtp.open_data (l_mail_conn); utl_smtp.write_data ( l_mail_conn, 'FROM: ' || sender || lv_crlf); utl_smtp.write_data ( l_mail_conn, 'To: ' || recipient || lv_crlf); utl_smtp.write_data ( l_mail_conn, 'Subject:' || subject || lv_crlf); utl_smtp.write_data ( l_mail_conn, lv_crlf || message); utl_smtp.close_data(l_mail_conn); utl_smtp.quit(l_mail_conn);
EXCEPTION
Patni Public
WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Error');
END; /
Index
28. Alternate Query for DECODE function :
SELECT case WHEN sex = 'm' THEN 'male'WHEN sex = 'f' THEN 'female'ELSE 'unknown'END
FROM mytable;
Index
29. Create table adding Constraint to a date field to SYSDATE or 3 months later:
CREATE TABLE srinu(dt1 date DEFAULT SYSDATE, dt2 date,CONSTRAINT check_dt2 CHECK ((dt2 >= dt1) AND (dt2 <= ADD_MONTHS(SYSDATE,3)));
Index
30. Query to list all the suppliers who supply all the parts supplied by supplier 'S2' :
SELECT DISTINCT a.SUPPFROM ORDERS aWHERE a.supp != 'S2'AND a.parts IN(SELECT DISTINCT PARTS FROM ORDERS WHERE supp = 'S2')GROUP BY a.SUPPHAVINGCOUNT(DISTINCT a.PARTS) >=(SELECT COUNT(DISTINCT PARTS) FROM ORDERS WHERE supp = 'S2');
Table : orders
SUPP PARTS-------------------- -------S1 P1S1 P2S1 P3S1 P4S1 P5S1 P6S2 P1S2 P2S3 P2S4 P2S4 P4S4 P5
Patni Public
Index
31. Query to get the last Sunday of any month :
SELECT NEXT_DAY(LAST_DAY(TO_DATE('26-10-2001','DD-MM-YYYY')) - 7,'sunday') FROM DUAL;
SELECT NEXT_DAY(to_date(LAST DAY OF THE MONTH)-7, 'sunday') FROM dual
Index
32. Query to get all those who have no children themselves :
table data :id name parent_id-------------------------------1 a NULL - the top level entry2 b 1 - a child of 13 c 14 d 2 - a child of 25 e 2 6 f 37 g 38 h 49 i 810 j 9
SELECT ID FROM MY_TABlE WHERE PARENT_ID IS NOT NULLMINUSSELECT PARENT_ID FROM MY_TABlE;
Index
33. Query to SELECT last N rows FROM a table :
SELECT empno FROM emp WHERE ROWID in(SELECT ROWID FROM empMINUSSELECT ROWID FROM emp WHERE ROWNUM <= (SELECT COUNT(*)-5 FROM emp));
SELECT * FROM test_mapping WHERE ROWNUM < 11 MINUS SELECT * FROM test_mapping WHERE ROWNUM < 9
Index
34. SELECT with variables:
CREATE OR REPLACE PROCEDURE dispASxTableName varchar2(25):='emp';
Patni Public
xFieldName varchar2(25):='ename';xValue NUMBER;xQuery varchar2(100);name varchar2(10) := 'CLARK';BEGINxQuery := 'SELECT SAL FROM ' || xTableName || ' WHERE ' || xFieldName ||
' = ''' || name || '''';
DBMS_OUTPUT.PUT_LINE(xQuery);
EXECUTE IMMEDIATE xQuery INTO xValue;DBMS_OUTPUT.PUT_LINE(xValue);END;
Index
35. Query to get the DB Name:
SELECT name FROM v$database;
Index
36. Getting the current default schema :
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;
Index
37. Query to get all the column names of a particular table :
SELECT column_nameFROM all_tab_columnsWHERE TABLE_NAME = 'ORDERS';
Index
38. How do I spool only the query result to a file in SQLPLUS :
Place the following lines of code in a file and execute the file in SQLPLUS :
set heading offset feedback offset colsep ' 'set termout offset verify offspool c:\srini.txtSELECT empno,ename FROM emp; /* Write your Query here */spool off/
Index
39. Query for getting the current SessionID :
SELECT SYS_CONTEXT('USERENV','SESSIONID') Session_ID FROM DUAL;
Patni Public
Index
40. Query to display rows FROM m to n :
To display rows 5 to 7 :
SELECT DEPTNO, ENAME, SALFROM EMPWHERE ROWID IN
(SELECT ROWID FROM EMP WHERE ROWNUM <= 7 MINUSSELECT ROWID FROM EMPWHERE ROWNUM < 5);
OR
SELECT ename FROM empGROUP BY ROWNUM, enameHAVING ROWNUM > 1 and ROWNUM < 3;
Index
41. Query to count no. Of columns in a table:
SELECT COUNT(column_name) FROM user_tab_columns WHERE table_name = 'MYTABLE';
Index
42. Procedure to increase the buffer length :
dbms_output.enable(4000); /*allows the output buffer to be increased to the specified number of bytes */
DECLAREBEGINdbms_output.enable(4000);FOR i IN 1..400LOOPDBMS_OUTPUT.PUT_LINE(i);END LOOP;END;/
Index
43. Inserting an & symbol in a Varchar2 column :
Set the following to some other character. By default it is &.
Patni Public
set define '~'
Index
44. How do you remove Trailing blanks in a spooled file :
Change the Environment Options Like this :set trimspool onset trimout on
Index
45. Samples for executing Dynamic SQL Statements :
Sample :1CREATE OR REPLACE PROCEDURE CNT(P_TABLE_NAME IN VARCHAR2)ASSqlString VARCHAR2(200);tot number;BEGINSqlString:='SELECT COUNT(*) FROM '|| P_TABLE_NAME;EXECUTE IMMEDIATE SqlString INTO tot;DBMS_OUTPUT.PUT_LINE('Total No.Of Records In ' || P_TABLE_NAME || ' ARE=' || tot);END;
Sample :2DECLARE
sql_stmt VARCHAR2(200);plsql_block VARCHAR2(500);emp_id NUMBER(4) := 7566;salary NUMBER(7,2);dept_id NUMBER(2) := 50;dept_name VARCHAR2(14) := ’PERSONNEL’;location VARCHAR2(13) := ’DALLAS’;emp_rec emp%ROWTYPE;
BEGINEXECUTE IMMEDIATE 'CREATE TABLE bonus (id NUMBER, amt NUMBER)';
sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)';EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;
sql_stmt := 'SELECT * FROM emp WHERE empno = :id';EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;
plsql_block := 'BEGIN emp_pkg.raise_salary(:id, :amt); END;';EXECUTE IMMEDIATE plsql_block USING 7788, 500;
sql_stmt := 'UPDATE emp SET sal = 2000 WHERE empno = :1RETURNING sal INTO :2';EXECUTE IMMEDIATE sql_stmt USING emp_id RETURNING INTO salary;
EXECUTE IMMEDIATE 'DELETE FROM dept WHERE deptno = :num'USING dept_id;
Patni Public
EXECUTE IMMEDIATE ’ALTER SESSION SET SQL_TRACE TRUE’;END;
Sample 3CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
v_cursor integer; v_dname char(20); v_rows integer;BEGIN v_cursor := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x',
DBMS_SQL.V7); DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no); DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20); v_rows := DBMS_SQL.EXECUTE(v_cursor); LOOP IF DBMS_SQL.FETCH_ROWS(v_cursor) = 0 THEN EXIT; END IF; DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname); DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname); END LOOP; DBMS_SQL.CLOSE_CURSOR(v_cursor);EXCEPTION WHEN OTHERS THEN DBMS_SQL.CLOSE_CURSOR(v_cursor); raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '||
sqlerrm);END;
Index
46.Differences between SQL and MS-Access :
Difference 1:Oracle : select name from table1 where name like 'k%';Access: select name from table1 where name like 'k*';
Difference 2:Access: SELECT TOP 2 name FROM Table1;Oracle : will not work there is no such TOP key word.
Index
47. Query to display all the children, sub children of a parent :
SELECT organization_id,nameFROM hr_all_organization_unitsWHERE organization_id in(SELECT ORGANIZATION_ID_CHILD FROM PER_ORG_STRUCTURE_ELEMENTSCONNECT BY PRIORORGANIZATION_ID_CHILD = ORGANIZATION_ID_PARENTSTART WITH ORGANIZATION_ID_CHILD = (SELECT organization_id
Patni Public
FROM hr_all_organization_unitsWHERE name = 'EBG Corporate Group'));
Index
48. Procedure to read/write data from a text file :
CREATE OR REPLACE PROCEDURE read_dataASc_path varchar2(100) := '/usr/tmp';c_file_name varchar2(20) := 'EKGSEP01.CSV';v_file_id utl_file.file_type;v_buffer varchar2(1022) := This is a sample text’;BEGINv_file_id := UTL_FILE.FOPEN(c_path,c_file_name,'w');UTL_FILE.PUT_LINE(v_file_id, v_buffer);UTL_FILE.FCLOSE(v_file_id);
v_file_id := UTL_FILE.FOPEN(c_path,c_file_name,'r');UTL_FILE.GET_LINE(v_file_id, v_buffer);DBMS_OUTPUT.PUT_LINE(v_buffer);UTL_FILE.FCLOSE(v_file_id);END;/
Index
49. Query to display random number between any two given numbers :
SELECT DBMS_RANDOM.VALUE (1,2) FROM DUAL;
Index
50. How can I get the time difference between two date columns :
SELECT FLOOR((date1-date2)*24*60*60)/3600) || ' HOURS ' || FLOOR((((date1-date2)*24*60*60) - FLOOR(((date1-date2)*24*60*60)/3600)*3600)/60) || ' MINUTES ' || ROUND((((date1-date2)*24*60*60) - FLOOR(((date1-date2)*24*60*60)/3600)*3600 - (FLOOR((((date1-date2)*24*60*60) - FLOOR(((date1-date2)*24*60*60)/3600)*3600)/60)*60))) || ' SECS ' time_differenceFROM my_table;
Index
51. Using INSTR and SUBSTR
I have this string in a column named location
LOT 8 CONC3 RR
Patni Public
Using instr and substr, I want to take whatever value follows LOT and putit into a different column and whatever value follows CONC and put it intoa different column
select substr('LOT 8 CONC3 RR',4,instr('LOT 8 CONC3 RR','CONC')-4) fromdual;
select substr('LOT 8 CONC3 RR',-(length('LOT 8 CONC3 RR')-(instr('LOT 8CONC3 RR','CONC')+3))) from dual
Index
52. View procedure code
select text from all_source where name = 'X'order by line;select text from user_source where name = 'X'select text from user_source where type = 'procedure' andname='procedure_name';select name,text from dba_source where name='ur_procedure'and owner='scott';
Index
53. To convert signed number to number in oracle
select to_number('-999,999.99', 's999,999.99') from dual; -999,999.99select to_number('+0,123.45', 's999,999,999.99') from dual; 123.45select to_number('+999,999.99', 's999,999.99') from dual; 999,999.99
Index
54. Columns of a table
select column_name from user_tab_columns where TABLE_NAME = 'EMP'select column_name from all_tab_columns where TABLE_NAME = 'EMP'select column_name from dba_tab_columns where TABLE_NAME = 'EMP'select column_name from cols where TABLE_NAME = 'EMP'
Index
55. Delete rows conditionallyI have a table have a,b,c field,
a,b should be unique, and leave max(c) row in.How can I delete other rows?
delete from 'table'where (a,b,c) not in (select a,b,max(c) from 'table' group by a,b);
Index
Patni Public
56.CLOB to Char
1) This function helps if your clob column value not exceed 4000 bytes(varchar2 limit).if clob column's data exceeds 4000 limit, you have tofollow different approach.
create or replace function lob_to_char(clob_col clob) return varchar2 IS buffer varchar2(4000); amt BINARY_INTEGER := 4000; pos INTEGER := 1; l clob; bfils bfile; l_var varchar2(4000):=''; begin LOOP
if dbms_lob.getlength(clob_col)<=4000 THEN dbms_lob.read (clob_col, amt, pos, buffer); l_var := l_var||buffer; pos:=pos+amt;
ELSE l_var:= 'Cannot convert to varchar2..Exceeding varchar2 field
limit'; exit;
END IF; END LOOP; return l_var; EXCEPTION
WHEN NO_DATA_FOUND THEN return l_var; END;
2) CREATE GLOBAL TEMPORARY TABLE temp_tab(id number,varchar_colvarchar2(4000));
SQL> var r refcursorSQL> exec lobpkg.lob_to_char(:r);SQL> print r
create or replace package lobpkg istype ref1 is ref cursor;n number:=0;PROCEDURE lob_to_char(rvar IN OUT lobpkg.ref1) ;end;/
create or replace package body lobpkg is
PROCEDURE lob_to_char(rvar IN OUT lobpkg.ref1) ISbuffer varchar2(4000);amt BINARY_INTEGER := 4000;pos INTEGER := 1;l clob;r lobpkg.ref1;
Patni Public
bfils bfile;l_var varchar2(4000):='';CURSOR C1 IS SELECT * FROM clob_tab;-- change clob_tab to your_table_namebeginn:=n+1;FOR crec IN c1 LOOPamt:=4000;pos:=1;BEGIN
LOOP
--change crec.clob_col to crec.your_column_name
dbms_lob.read (crec.clob_col, amt, pos, buffer);
--change next line if you create temporary table with different name
insert into temp_tab values (n,buffer);
pos:=pos+amt;
END LOOP;EXCEPTION
WHEN NO_DATA_FOUND THENNULL;
END;END LOOP;--change next line if you create temporary table with different nameopen rvar for select vchar from temp_tab where id=n;
END;END;
Index
57. Change Settings
Open file oracle_home\plus32\glogin.sql andadd this set linesize 100set pagewidth 20and save the fileand exit from sql and reload then it will set it.
Index
58. Double quoting a Single quoted String
declare -- we need one here to get a single quote into the variable v_str varchar2 (20) := 'O''reilly''s'; begin
Patni Public
DBMS_OUTPUT.PUT_LINE ( 'original single quoted v_str= ' || v_str ); v_str := replace(v_str, '''', ''''''); DBMS_OUTPUT.PUT_LINE ( 'after double quoted v_str= ' || v_str ); end;SQL> /original single quoted v_str= O'reilly'safter double quoted v_str= O''reilly''s
Index
59. Time Conversion
CREATE OR REPLACE FUNCTION to_hms (i_days IN number) RETURN varchar2ISBEGIN RETURN TO_CHAR (TRUNC (i_days)) || ' days ' ||
TO_CHAR (TRUNC (SYSDATE) + MOD (i_days, 1), 'HH24:MI:SS');END to_hms;
select to_hms(to_date('17-Jan-2002 13:20:20', 'dd-Mon-yyyy hh24:mi:ss') - to_date('11-Jan-2002 11:05:05', 'dd-Mon-yyyy hh24:mi:ss')) fromdual;
Index
60. Table comparisonThe table in both the schemas should have exactly the same structure. The data init could be same or different a-b and b-a
select * from a.a minus select * from b.a and select * from b.a minus select * from a.a
Index
61.Running Jobs
select * from user_jobs;exec dbms_job.remove(job_no);
Index
62.Switching ColumnsUpdate tblname Set column1 = column2,
Column2 = column1;
Index
63.Replace and RoundI have the number e.g. 63,9823874012983 and I want to round it to 63,98 and at the
same time change the , to a .
Patni Public
select round(replace('63,9823874012983',',','.'),2) from dual;
Index
64.First date of the yearselect trunc(sysdate, 'y') from dual;
01-jan-2002
last year this month through a select statementselect add_months(sysdate, -12) from dual;05-APR-01
Index
65.Create Sequencecreate sequence sh increment by 1 start with 0;
Index66.Cursorscursor is someting like pointers in C language.u fetch the data using cursor.( wiz...store it somewhere temporarily). ucan do any manipulation to the data that is fetched by the cursor. liketrim, padd, concat or validate. all this are done in temporary areas calledas context area or the cursor area. u can insert this data again in someother table or do anything u want!!...like setting up some flags etc.U can display the contents of cursor using the dbms_output only. U cancreate an anonymous plsql block or a stored procedure. the major advantageof cursors is that you can fetch more thatn one row and u can loop throughthe resultset and do the manupulations in a secure manner.
set serveroutput on;declarecursor c1 is select * from emp;beginfor var in c1 loopexit when c1%notfound;dbms_output.put_line('the employee' || var.ename ||'draws asalary of '|| var.sal);end loop;end;
Index
67.Current Week
select next_day(sysdate-7,'SUNDAY'), next_day(sysdate,'SATURDAY') from dual;
NEXT_DAY( NEXT_DAY(--------- ---------07-APR-02 13-APR-02
Index
68.Create Query to restrict the user to a single row 69.Query to get the first inserted record FROM a table
Patni Public
70.How to concatenate a column value with multiple rows 71.Query to delete all the tables at once 72.SQL Query for getting Orphan Records :
Index
Patni Public