PL SQL Query to list the months between two dates
SELECT TO_CHAR(ADD_MONTHS(TRUNC(TO_DATE('01-JAN-22','DD-MON-YY'), 'MM'), LEVEL -1),'MON-YY')
MONTH_YEAR
FROM DUAL
CONNECT BY LEVEL <= MONTHS_BETWEEN(TO_DATE('01-DEC-22','DD-MON-YY'),
TO_DATE('01-JAN -22','DD-MON-YY')) + 1
ORDER BY LEVEL;
Result set
MONTH_YEAR
JAN-22
FEB-22
MAR-22
APR-22
MAY-22
JUN-22
JUL-22
AUG-22
SEP-22
OCT-22
NOV-22
DEC-22
Example of Cursor:
declare
cursor c1 is select first_name, salary from hr.employees;
begin
for c in c1
loop
dbms_output.put_line('Ename: ' || c.first_name || ', Salary: ' || c.salary);
end loop;
end;
Example of Ref Cursor
declare
c1 SYS_REFCURSOR;
ename varchar2(10);
sal number;
begin
open c1 for select first_name, salary from hr.employees;
LOOP
FETCH c1 into ename, sal;
EXIT WHEN c1%NOTFOUND;
dbms_output.put_line('Ename: ' || first_name || ', Salary: ' || salary);
END LOOP;
close c1;
end;
They are both cursors and can be processed in the same fashion and at the most basic level, they both are same. There are some important differences between regular cursors and ref cursors which are following:
A ref cursor can not be used in CURSOR FOR LOOP, it must be used in simple CURSOR LOOP statement as in example.
A ref cursor is defined at runtime and can be opened dynamically but a regular cursor is static and defined at compile time.
A ref cursor can be passed to another PL/SQL routine (function or procedure) or returned to a client. A regular cursor cannot be returned to a client application and must be consumed within same routine.
A ref cursor incurs a parsing penalty because it cannot cached but regular cursor will be cached by PL/SQL which can lead to a significant reduction in CPU utilization.
A regular cursor can be defined outside of a procedure or a function as a global package variable. A ref cursor cannot be; it must be local in scope to a block of PL/SQL code.
A regular cursor can more efficiently retrieve data than ref cursor. A regular cursor can implicitly fetch 100 rows at a time if used with CURSOR FOR LOOP. A ref cursor must use explicit array fetching.
Use of ref cursors should be limited to only when you have a requirement of returning result sets to clients and when there is NO other efficient/effective means of achieving the goal.
References
Ask Tom
greenstechnologys
A cursor variable is a cursor that contains a pointer to a query result set. The result set is determined by execution of the OPEN FOR statement using the cursor variable.
A cursor variable, unlike a static cursor, is not associated with a particular query. The same cursor variable can be opened a number of times with separate OPEN FOR statements containing different queries. A new result set is created each time and made available through the cursor variable.
Strong typed REF CURSOR
DECLARE TYPE customer_t IS REF CURSOR RETURN customers%ROWTYPE;
c_customer customer_t;
This form of cursor variable called strong typed REF CURSOR because the cursor variable is always associated with a specific record structure, or type.
And here is an example of a weak typed REF CURSOR declaration that is not associated with any specific structure:
Weak typed REF CURSOR
DECLARE TYPE customer_t IS REF CURSOR;
c_customer customer_t;
Starting from Oracle 9i, you can use SYS_REFCURSOR, which is a predefined weak typed REF CURSOR, to declare a weak REF CURSOR as follows:
DECLARE c_customer SYS_REFCURSOR;
The SYS_REFCURSOR data type is known as a weakly-typed REF CURSOR type. Strongly-typed cursor variables of the REF CURSOR type require a result set specification.
References
OracleTututorial
IBM
A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from pseudocolumns, but you cannot insert, update, or delete their values. A pseudocolumn is also similar to a function without arguments. However, functions without arguments typically return the same value for every row in the result set, whereas pseudocolumns typically return a different value for each row.
Rownum is an example for pseudocolumns.
References
Oracle Docs
ROWNUM is a pseudocolumn (not a real column) that is available in a query. ROWNUM will be assigned the numbers 1, 2, 3, 4, … N , where N is the number of rows in the set ROWNUM is used with. A ROWNUM value is not assigned permanently to a row. A row in a table does not have a number; you cannot ask for row 5 from a table—there is no such thing.
ROWNUM value is actually assigned. A ROWNUM value is assigned to a row after it passes the predicate phase of the query but before the query does any sorting or aggregation. Also, a ROWNUM value is incremented only after it is assigned, which is why the following query will never return a row:
select * from t
where ROWNUM > 1;
Below query will give you the wrong results,
select * from emp
where ROWNUM <= 5
order by sal desc;
To understand the above, check the below query with this structure:
select ..., ROWNUM
from t
where <where clause>
group by <columns>
having <having clause>
order by <columns>;
Think of it as being processed in this order:
- The FROM/WHERE clause goes first.
- ROWNUM is assigned and incremented to each output row from the FROM/WHERE clause.
- SELECT is applied.
- GROUP BY is applied.
- HAVING is applied.
- ORDER BY is applied.
Below is the way ti use the rownum
select * from
( select * from emp
order by sal desc )
where ROWNUM <= 5;
References
Oracle Blog
VALIDATE_CONVERSION determines whether expr can be converted to the specified data type. If expr can be successfully converted, then this function returns 1; otherwise, this function returns 0. If expr evaluates to null, then this function returns 1. If an error occurs while evaluating expr, then this function returns the error.
SELECT VALIDATE_CONVERSION(1000 AS BINARY_DOUBLE)
FROM DUAL;
SELECT VALIDATE_CONVERSION('1234.56' AS BINARY_FLOAT)
FROM DUAL;
SELECT VALIDATE_CONVERSION('July 20, 1969, 20:18' AS DATE,
'Month dd, YYYY, HH24:MI', 'NLS_DATE_LANGUAGE = American')
FROM DUAL;
SELECT VALIDATE_CONVERSION('200 00:00:00' AS INTERVAL DAY TO SECOND)
FROM DUAL;
SELECT VALIDATE_CONVERSION('P1Y2M' AS INTERVAL YEAR TO MONTH)
FROM DUAL;
SELECT VALIDATE_CONVERSION('$100,00' AS NUMBER,
'$999D99', 'NLS_NUMERIC_CHARACTERS = '',.''')
FROM DUAL;
SELECT VALIDATE_CONVERSION('29-Jan-02 17:24:00' AS TIMESTAMP,
'DD-MON-YY HH24:MI:SS')
FROM DUAL;
SELECT VALIDATE_CONVERSION('1999-12-01 11:00:00 -8:00'
AS TIMESTAMP WITH TIME ZONE, 'YYYY-MM-DD HH:MI:SS TZH:TZM')
FROM DUAL;
SELECT VALIDATE_CONVERSION('11-May-16 17:30:00'
AS TIMESTAMP WITH LOCAL TIME ZONE, 'DD-MON-YY HH24:MI:SS')
FROM DUAL;
References
Oracle Docs
The SELECT INTO is actually a standard SQL query where the SELECT INTO clause is used to place the returned data into predefined variables.
create or replace function auth_Name
( v_auth_state IN author.author_state%type)
return varchar2
as
v_authName author.author_last_name%type;
begin
select author_last_name into v_authName
from author
where author_state = v_auth_state;
return v_authName;
exception
when TOO_MANY_ROWS
then return 'Too Many Authors in that State';
when NO_DATA_FOUND
then return 'No Authors in that State';
when others
then raise_application_error(-20011,'Unknown Exception in authName Function');
end;
References
dba-Oracle
SELECT COUNT(*) INTO var WHERE CONDITION;
IF var > 0 THEN
SELECT NEEDED_FIELD INTO otherVar WHERE CONDITION;
In PLSQL method with count(*) is unsafe in above code. If another session deletes the row that met the condition after the line with the count(*), and before the line with the select ... into, the code will throw an exception that will not get handled.
Use the below insted,
SELECT NEEDED_FIELD INTO var WHERE CONDITION;
EXCEPTION
WHEN NO_DATA_FOUND
References
Stack Overflow
The SET DEFINE command changes the prefix character used to mark substitution variables. You can use SET DEFINE to turn variable substitution off.
SET DEF[INE] {OFF | ON | prefix_char}
Define is a SQL*Plus client variable. It is NOT a database level setting.
When you start SQL*Plus, variable substitution will be on by default, and the default prefix character is an ampersand. If you are running a script that uses ampersands in text strings, you may want to change the prefix character to something else. If your script doesn’t use substitution variables, you may find it easiest to turn the feature off.
References
Oreilly
The %TYPE attribute lets use the datatype of a field, record, nested table, database column, or variable in your own declarations, rather than hardcoding the type names.
You can use the %TYPE attribute as a datatype specifier when declaring constants, variables, fields, and parameters. If the types that you reference change, your declarations are automatically updated.
This technique saves you from making code changes when, for example, the length of a VARCHAR2 column is increased. Note that column constraints, such as the NOT NULL and check constraint, or default values are not inherited by items declared using %TYPE.