Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass time interval via variable in Oracle SQL

Tags:

sql

oracle

This query returns the value based on given interval time 10.

SELECT TO_CHAR((TO_DATE('23:20:20','HH24:MI:SS') - INTERVAL '10' MINUTE), 'HH24:MI:SS') 
FROM DUAL;

Output:

23:10:20

I want to pass this minute interval via variable using below code:

declare
test1 varchar(30);
begin
test1:=18;
SELECT TO_CHAR((TO_DATE('23:20:20','HH24:MI:SS') - INTERVAL ||test1|| MINUTE), 'HH24:MI:SS') 
 FROM DUAL;
 end;

But its not working - error is

PL/SQL: ORA-00904: "MINUTE": invalid identifier

Please assist me on this. Thanks!

like image 916
user2862073 Avatar asked Jul 22 '14 09:07

user2862073


People also ask

Why %type is used in SQL?

The %TYPE attribute, used in PL/SQL variable and parameter declarations, is supported by the data server. Use of this attribute ensures that type compatibility between table columns and PL/SQL variables is maintained.

What is %type in Oracle SQL?

The %TYPE attribute lets you declare a constant, variable, collection element, record field, or subprogram parameter to be of the same data type as a previously declared variable or column (without knowing what that type is).

What is HH24 in SQL?

HH24: Two-digit hour in 24-hour format : Date Format « SQL Data Types « Oracle PL/SQL Tutorial.

Is there a time datatype in Oracle?

Oracle Database has five date-time data types: TIMESTAMP. TIMESTAMP WITH TIME ZONE. TIMESTAMP WITH LOCAL TIME ZONE.


2 Answers

You can't do that as it has to be a string literal, not a variable. But you can use the numtodsinterval() function instead:

declare
  test1 number;
begin
  test1:=18;
  SELECT TO_CHAR(TO_DATE('23:20:20','HH24:MI:SS')
   - NUMTODSINTERVAL(test1, 'MINUTE'), 'HH24:MI:SS')
  INTO <something>
  FROM DUAL;
end;
/

SQL Fiddle, including a really simple function version.

like image 189
Alex Poole Avatar answered Sep 19 '22 02:09

Alex Poole


Try this:

DECLARE
   l_val      NUMBER;
   l_result   VARCHAR2( 20 );
BEGIN
   l_val := 10;

   SELECT TO_CHAR( ( TO_DATE( '23:20:20', 'HH24:MI:SS' ) - INTERVAL '1' MINUTE * l_val ), 'HH24:MI:SS' ) INTO l_result FROM DUAL;

   DBMS_OUTPUT.put_line( l_result );
END;

Output will be:
23:10:20

like image 31
Pranav Shah Avatar answered Sep 22 '22 02:09

Pranav Shah