I have written a following query in my procedure which is not inserting the records in the TEST table. The KPI definition table has the following record:
KPI_DEF_ID KPI_FREQUENCY KPI_FREQ_TIME_UNIT EVENT_ID
1000136 30 MINUTE 10028
1000137 50 MINUTE 10028
I have a application in which user want to get the records depending on the timestamp. So user can enter in the application to get the records for example older than 30 min and newer than 24 hour. And the timestamp is changable. The older than timestamp comes from the KPI DEFINITION table and which is stored in the column KPI_FREQUENCY and KPI_FREQUENCY_UNIT and it can be changabler. And the newer than timestamp is fixed and i stored it in varaible LAST_OLDER_VAL and LAST_OLDER_VAL_UNIT. I used the insert using select query to store the records in table but its not working.
create or replace PROCEDURE "EXT_TEST" AS
LAST_WF_ID Number := 0;
--LAST_UNIT NUMBER:=10;
--LAST_UNIT_VAL VARCHAR2(20);
LAST_OLDER_VAL NUMBER := 24;
LAST_OLDER_VAL_UNIT VARCHAR2(10) := 'HOUR';
CURSOR WF_WORKFLOW_CUR IS
Select KPI_DEF_ID,KPI_FREQUENCY,KPI_FREQ_TIME_UNIT,EVENT_ID,BUSINESS_CHECK_PERIOD_ID FROM RATOR_MONITORING_CONFIGURATION.KPI_DEFINITION where EVENT_ID=10028;
BEGIN
--DBMS_OUTPUT.PUT_LINE('LAST_UNIT - ' || LAST_UNIT);
--DBMS_OUTPUT.PUT_LINE('LAST_UNIT_VAL - ' || LAST_UNIT_VAL);
-- removed, retrieve a new START_ID from source first, don't use the last id.
--SELECT LAST_TASK_ID INTO LAST_WF_ID FROM CAPTURING where DB_TABLE='TEMP_WF_WORKFLOW';
FOR WF_WORKFLOW_ROW IN WF_WORKFLOW_CUR
LOOP
--select MIN(ID) INTO LAST_WF_ID from WF_WORKFLOW#FONIC_RETAIL WF where WF.START_DATE > sysdate - numtodsinterval ( WF_WORKFLOW_ROW.KPI_FREQUENCY, WF_WORKFLOW_ROW.KPI_FREQ_TIME_UNIT );
Insert into TEST(ID,NAME,SUBSCRIPTION_ID,START_DATE,STATUS_ID,ACCOUNT_ID,END_DATE)
Select DISTINCT(WF.ID),WF.NAME,WF.SUBSCRIPTION_ID,WF.START_DATE,WF.STATUS_ID,WF.ACCOUNT_ID,WF.END_DATE
from WF_WORKFLOW#FONIC_RETAIL WF where WF.STATUS_ID = 0 and WF.NAME = 'SIGNUP_MOBILE_PRE_PAID'
and WF.START_DATE > SYSDATE - numtodsinterval ( LAST_OLDER_VAL, LAST_OLDER_VAL_UNIT
and WF.START_DATE < SYSDATE - numtodsinterval ( WF_WORKFLOW_ROW.KPI_FREQUENCY, WF_WORKFLOW_ROW.KPI_FREQ_TIME_UNIT ));
DBMS_OUTPUT.PUT_LINE('WF_WORKFLOW_ROW.KPI_FREQUENCY - ' || WF_WORKFLOW_ROW.KPI_FREQUENCY);
DBMS_OUTPUT.PUT_LINE('WF_WORKFLOW_ROW.KPI_FREQ_TIME_UNIT - ' || WF_WORKFLOW_ROW.KPI_FREQ_TIME_UNIT);
END LOOP;
END EXT_TEST;
You're currently looking for a start date that is older than 24 hours and newer than 30 minutes. Which is impossible, and not what you stated you needed, so that isn't what you mean really. Looks like you just have your < and > comparisons the wrong way around:
...
and WF.START_DATE > SYSDATE - numtodsinterval ( LAST_OLDER_VAL, LAST_OLDER_VAL_UNIT )
and WF.START_DATE < SYSDATE - numtodsinterval ( WF_WORKFLOW_ROW.KPI_FREQUENCY, WF_WORKFLOW_ROW.KPI_FREQ_TIME_UNIT );
Not directly relevant, but I'm not sure why you're using a loop for this, rather than a single insert ... select which joins WF_WORKFLOW_CUR and WF_WORKFLOW#FONIC_RETAIL. Or really why you'd use a stored procedure at all.
Related
I would like to group all values of my Column DATUM of the Table test_tbl which are greater than 01.01.2020 . When I run the query:
SELECT to_date("DATUM", 'YYYYMM')
FROM test_tbl
WHERE to_date("DATUM", 'YYYYMM') >= to_date('2020-01-01' ,'YYYY-MM-DD')
GROUP BY to_date("DATUM", 'YYYYMM')
I get the following Error
ORA-01841: (full) year must be between -4713 and +9999, and not be 0.
The table test_tbl looks like:
DATUM (varchar2)
201701
202001
201901
201801
202003
When I run only the GROUP BY without the WHERE CLAUSE the date convertation works and there are no NULL values or somithing similiar
SELECT to_date("DATUM", 'YYYYMM')
FROM test_tbl
GROUP BY to_date("DATUM", 'YYYYMM')
`
This is a data error. Somewhere in your DATUM column you have a string which cannot be cast to a date. This is always a risk when we store data as the wrong datatype.
If you are on Oracle 12c R2 or higher you can easily locate the errant row(s) with a query like this:
select * from your_table
where validate_conversion(datum as date, 'yyyymm') = 0
If you are on an earlier version of the database you can create a function which does something similar....
create or replace function is_date(p_str in varchar2
,p_mask in varchar2 := 'yyyymm' ) return number is
n pls_integer;
begin
declare
dt date;
begin
dt := to_date(p_str, p_mask);
n := 1;
exception
when others then
n := 0;
end;
return n;
end;
/
Like validate_conversion() this returns 1 for valid dates and 0 for invalid ones.
select * from your_table
where is_date(datum, 'yyyymm') = 0
This approach is safer because it applies Oracle's actual date verification mechanism. Whereas, using pattern matching regexes etc leaves us open to weak patterns which pass strings which can't be cast to dates.
Your datum column would need to contain only numeric data in order to be processed as a date in the format you specified. Plus the last two digits would need to be between 01 and 12; but that's a separate issue since your error message is complaining about the value for year.
So you could check for invalid values with:
SELECT
datum
,LENGTH(REGEXP_REPLACE(datum,'[0-9]','')) as char_count
FROM test_tbl
WHERE LENGTH(REGEXP_REPLACE(datum,'[0-9]','')) > 0
;
Should spin through 300k rows fairly quickly.
I have 2 columns in xyz table, as start_time and end_time in 2 different tables.
table 1 - start_time & end_time
table 2 - avg_start_time & avg_end_time.
I need to check whether start_time(table1) is greater than avg_start_time. some how I am not getting output, however I am getting the expected answer if I do the less than instead of greater than,
to_char(start_time,'hh24:mi:ss') < to_char(avg_start_time,'hh24:mi:ss') -- no output
to_char(start_time,'hh24:mi:ss') > to_char(avg_start_time,'hh24:mi:ss') --
table values output -
-- 20:11:04(start_time) 20:05:00(avg_start_time)
can you try MSSQL
CAST(start_timeas as time) < cast(avg_start_time as time)?
update answer
Oracle:
my idea is create new timestamps from date now and time from objects and that values compared
to_timestamp((to_char(trunc(sysdate),'dd.MM.yyyy') || ' ' || to_Char(start_timeas, 'hh24:mi:ss')),'dd.MM.yyyy hh24:mi:ss') < to_timestamp((to_char(trunc(sysdate),'dd.MM.yyyy') || ' ' || to_Char(avg_start_time, 'hh24:mi:ss')),'dd.MM.yyyy hh24:mi:ss')
I have the following query that I am attempting to use as a COMMAND in a crystal report that I am working on.
SELECT * FROM myTable
WHERE to_date(myTable.sdate, 'MM/dd/yyyy') <= {?EndDate}
This works fine, however my only concern is that the date may not always be in the correct format (due to user error). I know that when the to_date function fails it throws an exception.. is it possible to handle this exception in such a way that it ignores the corresponding row in my SELECT statement? Because otherwise my report would break if only one date in the entire database is incorrectly formatted.
I looked to see if Oracle offers an isDate function, but it seems like you are supposed to just handle the exception. Any help would be greatly appreciated. Thanks!!
Echoing Tony's comment, you'd be far better off storing dates in DATE columns rather than forcing a front-end query tool to find and handle these exceptions.
If you're stuck with an incorrect data model, however, the simplest option in earlier versions is to create a function that does the conversion and handles the error,
CREATE OR REPLACE FUNCTION my_to_date( p_date_str IN VARCHAR2,
p_format_mask IN VARCHAR2 )
RETURN DATE
IS
l_date DATE;
BEGIN
l_date := to_date( p_date_str, p_format_mask );
RETURN l_date;
EXCEPTION
WHEN others THEN
RETURN null;
END my_to_date;
Your query would then become
SELECT *
FROM myTable
WHERE my_to_date(myTable.sdate, 'MM/dd/yyyy') <= {?EndDate}
Of course, you'd most likely want a function-based index on the MY_TO_DATE call in order to make this query reasonably efficient.
In 12.2, Oracle has added extensions to the to_date and cast functions to handle conversions that error
SELECT *
FROM myTable
WHERE to_date(myTable.sdate default null on conversion error, 'MM/dd/yyyy') <= {?EndDate}
You could also use the validate_conversion function if you're looking for all the rows that are (or are not) valid dates.
SELECT *
FROM myTable
WHERE validate_conversion( myTable.sdate as date, 'MM/DD/YYYY' ) = 1
If your data is not consistent and dates stored as strings may not be valid then you have 3 options.
Refactor your DB to make sure that the column stores a date datatype
Handle the exception of string to date in a stored procedure
Handle the exception of string to date in a (complex) record selection formula
I would suggest using the first option as your data should be consistent.
The second option will provide some flexibility and speed as the report will only fetch the rows that are needed.
The third option will force the report to fetch every record in the table and then have the report filter down the records.
I have the same problem... an old legacy database with varchar fields for dates and decades of bad data in the field. As much as I'd like to, I can't change the datatypes either. But I came up with this solution to find if a date is current, which seems to be what you're doing as well:
select * from MyTable
where regexp_like(sdate, '[0-1][0-9].[0-3][0-9].[0-9][0-9][0-9][0-9]')
-- make sure it's in the right format and ignore rows that are not
and substr(sdate,7,10) || substr(sdate,1,2) || substr(sdate,4,5) >= to_char({?EndDate}, 'YYYYMMDD')
-- put the date in ISO format and do a string compare
The benefit of this approach is it doesn't choke on dates like "February 30".
Starting from Oracle 12c there is no need to define a function to catch the conversion exception.
Oracle introduced an ON CONVERSION ERROR clause in the TO_DATE function.
Basically the clause suppress the error in converting of an invalid date string (typical errors are ORA-01843, ORA-01841, ORA-011861, ORA-01840) and returns a specified default value or null.
Example of usage
select to_date('2020-99-01','yyyy-mm-dd') from dual;
-- ORA-01843: not a valid month
select to_date('2020-99-01' default null on conversion error,'yyyy-mm-dd') from dual;
-- returns NULL
select to_date('2020-99-01' default '2020-01-01' on conversion error,'yyyy-mm-dd') from dual;
-- 01.01.2020 00:00:00
Solution for the Legacy Application
Let's assume there is a table with a date column stored as VARCHAR2(10)
select * from tab;
DATE_CHAR
----------
2021-01-01
2021-99-01
Using the above feature a VIRTUAL DATE column is defined, that either shows the DATE or NULL in case of the conversion error
alter table tab add (
date_d DATE as (to_date(date_char default null on conversion error,'yyyy-mm-dd')) VIRTUAL
);
select * from tab;
DATE_CHAR DATE_D
---------- -------------------
2021-01-01 01.01.2021 00:00:00
2021-99-01
The VIRTUAL column can be safely used because its format is DATE and if required an INDEX can be set up on it.
select * from tab where date_d = date'2021-01-01';
Since you say that you have "no access" to the database, I am assuming that you can not create any functions to help you with this and that you can only run queries?
If that is the case, then the following code should get you most of what you need with the following caveats:
1) The stored date format that you want to evaluate is 'mm/dd/yyyy'. If this is not the case, then you can alter the code to fit your format.
2) The database does not contain invalid dates such as Feb 30th.
First, I created my test table and test data:
create table test ( x number, sdate varchar2(20));
insert into test values (1, null);
insert into test values (2, '01/01/1999');
insert into test values (3, '1999/01/01');
insert into test values (4, '01-01-1999');
insert into test values (5, '01/01-1999');
insert into test values (6, '01-01/1999');
insert into test values (7, '12/31/1999');
insert into test values (8, '31/12/1999');
commit;
Now, the query:
WITH dates AS (
SELECT x
, sdate
, substr(sdate,1,2) as mm
, substr(sdate,4,2) as dd
, substr(sdate,7,4) as yyyy
FROM test
WHERE ( substr(sdate,1,2) IS NOT NAN -- make sure the first 2 characters are digits
AND to_number(substr(sdate,1,2)) between 1 and 12 -- and are between 0 and 12
AND substr(sdate,3,1) = '/' -- make sure the next character is a '/'
AND substr(sdate,4,2) IS NOT NAN -- make sure the next 2 are digits
AND to_number(substr(sdate,4,2)) between 1 and 31 -- and are between 0 and 31
AND substr(sdate,6,1) = '/' -- make sure the next character is a '/'
AND substr(sdate,7,4) IS NOT NAN -- make sure the next 4 are digits
AND to_number(substr(sdate,7,4)) between 1 and 9999 -- and are between 1 and 9999
)
)
SELECT x, sdate
FROM dates
WHERE to_date(mm||'/'||dd||'/'||yyyy,'mm/dd/yyyy') <= to_date('08/01/1999','mm/dd/yyyy');
And my results:
X SDATE
- ----------
2 01/01/1999
The WITH statement will do most of the validating to make sure that the sdate values are at least in the proper format. I had to break out each time unit month / day / year to do the to_date evaluation because I was still getting an invalid month error when I did a to_date on sdate.
I hope this helps.
Trust this reply clarifies...
there is no direct EXCEPTION HANDLER for invalid date.
One easy way is given below once you know the format like DD/MM/YYYY then below given REGEXP_LIKE function will work like a charm.
to_date() also will work, when invalid_date is found then cursor will goto OTHERS EXCEPTION. given below.
DECLARE
tmpnum NUMBER; -- (1=true; 0 = false)
ov_errmsg LONG;
tmpdate DATE;
lv_date VARCHAR2 (15);
BEGIN
lv_date := '6/2/2018'; -- this will fail in *regexp_like* itself
lv_date := '06/22/2018'; -- this will fail in *to_date* and will be caught in *exception WHEN OTHERS* block
lv_date := '07/03/2018'; -- this will succeed
BEGIN
tmpnum := REGEXP_LIKE (lv_date, '[0-9]{2}/[0-9]{2}/[0-9]{4}');
IF tmpnum = 0
THEN -- (1=true; 0 = false)
ov_errmsg := '1. INVALID DATE FORMAT ';
DBMS_OUTPUT.PUT_LINE (ov_errmsg);
RETURN;
END IF;
tmpdate := TO_DATE (lv_date, 'DD/MM/RRRR');
--tmpdate := TRUNC (NVL (to_date(lv_date,'DD/MM/RRRR'), SYSDATE));
tmpnum := 1;
EXCEPTION
WHEN OTHERS
THEN
BEGIN
tmpnum := 0;
ov_errmsg := '2. INVALID DATE FORMAT ';
DBMS_OUTPUT.PUT_LINE (ov_errmsg || SQLERRM);
RETURN;
END;
-- continue with your other query blocks
END;
-- continue with your other query blocks
DBMS_OUTPUT.PUT_LINE (tmpnum);
END;
I have a RAW field in my Oracle database that represents the date of user registered in system.
The value is something like 24E2321A0000000000 However I need convert the value to the date it represents (etc 2008-12-25 15:04:31).
I tried with totimestamp (see this sqlfiddle) but that didn't work.
Maybe this will help:
SELECT utl_raw.cast_to_binary_integer('24E2321A0000000000') raw_to_int
FROM dual
/
Output is 36. I'm not sure if you need days or hours. Next example is about adding 36 hours to SYSDATE:
-- SYSDATE + 36/24 --
SELECT SYSDATE+(utl_raw.cast_to_binary_integer('24E2321A0000000000')/24) my_date
FROM dual
/
MY_DATE
---------------------
12/13/2013 4:29:22 AM
please try one
declare
d date;
begin
dbms_stats.convert_raw_value (hextoraw('7876070A010101'), d);
dbms_output.put_line (d);
end;
I have function which returns a list of comma seperated dates(e.g. 'Dec 24, 2011','Dec 26, 2011','Dec 18, 2011','Dec 27, 2011'.
I am receiving this as a single string.
I want to use this string to build a select query where I want to use the string in the IN clause.
e.g.
select *
from wfdisplaymgmt
where programstartdate IN(TO_DATE('Dec 26, 2011','MON dd, yyyy'))
Since I am getting a multiple dates I would like to use all the dates in my statement.how can I write the sql query which inlcudes multiple dates.Please help.
Update:
One more thing is I have window with a textbox and a button on clicking the button a sql query is executed.The query returns a distinct number of column values which has an option of selecting each of those values.when the user selects the required values ,the values are copied to the text box(e.g.'Dec 24, 2011','Dec 26, 2011','Dec 18, 2011','Dec 27, 2011' if I have selected four dates).Now the String I want to use this string in a sql statement where I select all the columns of the table based on the selected dates found in the string i.e.values found in the text box.
'Mon DD,YYYY' is the date format returned in the string.
I want a query similar to
select *
from wfdisplaymgmt
where programstartdate IN(the date values coming from the text box)
how do I do this?
Change your PLSQL function to return a user-defined data type TABLE OF DATE (or TIMESTAMP) and use IN to match values.
Note you will probably need to TRUNC the date values in order to match them. Noon != Midnight!
The following code illustrates the approach.
WHENEVER SQLERROR EXIT FAIL ROLLBACK
set echo on
COLUMN programstartdate FORMAT A45
column column_value format a45
set serveroutput on
<<REINITIALIZE>>
BEGIN
FOR DOIT IN (SELECT 'DROP TABLE ' || TABLE_NAME AS CMD FROM USER_TABLES WHERE TABLE_NAME = 'WFDISPLAYMGMT')
LOOP
EXECUTE IMMEDIATE DOIT.CMD;
DBMS_OUTPUT.PUT_LINE ('Dropped test table via command: ' || doit.CMD);
end loop;
dbms_random.seed('This doesn''t quite feel random until I add the microseconds ' || to_char (systimestamp, 'D FF9'));
END REINITIALIZE;
/
CREATE OR REPLACE TYPE DATELIST AS TABLE OF date;
/
show errors type datelist
CREATE OR REPLACE FUNCTION GETDATES (HOWMANY IN NUMBER) RETURN DATELIST
IS
TO_RETURN DATELIST := datelist();
BEGIN
for stepback in 1 .. howmany
loop
to_return.extend();
TO_RETURN(stepback) := trunc(sysdate - stepback);
end loop;
RETURN TO_RETURN;
END GETDATES;
/
show errors function getdates;
select * from table(cast (getdates (7) as datelist));
create table WFDISPLAYMGMT
as
select
TRUNC(dbms_random.value (50, 10000)) as bogus_id,
column_value as programstartdate
from (select rownum as row_no, column_value from table(cast (getdates (30) as datelist)))
where abs (mod (row_no, 3)) = 1
;
commit;
select count (*) as generated_rows from WFDISPLAYMGMT;
select *
from WFDISPLAYMGMT
where programstartdate in (select * from table (cast (getdates (15) as datelist)));
Here's a slightly convoluted way to do this in SQL only. The below is a sample you can run immediately in your instance to check it out:
select to_date(replace(VAL, '''', ''), 'Mon dd, yyyy') as NEWDATE
from (with TST1 as
(select length(DTXT) - length(translate(DTXT, REPLVAL || VALSEP, REPLVAL)) + 1 as NUMVAL
,VALSEP
,DTXT || VALSEP as DTXT
from (select replace('''Dec 24, 2011'',''Dec 26, 2011'',''Dec 18, 2011'',''Dec 27, 2011'''
,''','''
,'''|''')
as DTXT
,'|' as VALSEP
,chr(0) as REPLVAL
from dual))
select substr(TST1.DTXT
,decode(rownum, 1, 1, instr(TST1.DTXT, VALSEP, 1, rownum - 1) + length(VALSEP))
, instr(TST1.DTXT, VALSEP, 1, rownum)
- decode(rownum, 1, 0, instr(TST1.DTXT, VALSEP, 1, rownum - 1))
- 1)
as VAL
from TST1
connect by level <= TST1.NUMVAL)
What it does is take your comma-separated dates and converts them into individual records that can then be cast to date type. In your scenario you can replace the sub-query that selects from dual with your function, e.g.:
select *
from wfdisplaymgmt
where programstartdate IN (
select to_date(replace(VAL, '''', ''), 'Mon dd, yyyy') as NEWDATE
...
select replace(myfunctioncall()
,''','''
,'''|''')
as DTXT
,'|' as VALSEP
,chr(0) as REPLVAL
from dual
...
What I've done here is replace the comma separators with pipe separators as you have a comma appearing in the date format. Also, I have appended the pipe separator to the end of the text so that the last value is included. If you need further details on what each bit does then add a comment.
you can use the EXECUTE() function to execute a string as a sql statement, that would work, or else you just can split the string of dates up into a table variable and then use in on the table variable. Both work, I think the table variable is probably a better solution.
Assuming oracle and I'm rusty at best for that techology
select *
from wfdisplaymgmt
where instr(your_function_that_delivers_dates()
, TO_CHAR(programstartdate,'MON DD, YYYY')) > 0
Don't expect blasting performance on large tables because the queryplan is not going to use any index, instead it will do a full-table scan
Based on info found here
Consider creating a new function (or replacing the old) that returns you a table (array) of data instead of a csv list in single string. It will be much easier to actually use the function in a meaningful way:
-- Create types
CREATE TYPE t_tf_row AS OBJECT (
id NUMBER,
dte date
);
/
CREATE TYPE t_tf_tab IS TABLE OF t_tf_row;
/
-- Build the table function itself.
CREATE OR REPLACE FUNCTION get_tab_tf (p_rows IN NUMBER) RETURN t_tf_tab AS
l_tab t_tf_tab := t_tf_tab();
l_dte date;
BEGIN
-- create rows
FOR i IN 1 .. p_rows LOOP
l_dte := sysdate - i;
l_tab.extend;
l_tab(l_tab.last) := t_tf_row(i, l_dte);
END LOOP;
RETURN l_tab;
END;
/
-- test new function, selecting 20 dates
select * from MY_TABLE
where MY_DATE in (select dte from table(get_tab_tf(20)));
Of course, in your version of the function create the dates the way you need them. Also note that you could do a pipelined version as well, but I assume the list of dates is reasonable in length.