I'm not sure what I'm doing wrong here. I'm trying to build an oracle query that I will be executing from my php project via oci. I need to select all records between a specific date range.
In trying to get the syntax down, I wrote out this test query:
SELECT * FROM SHIPPED
WHERE user_seq_id = 381 AND
LOT_DATE BETWEEN TO_DATE('05/27/2014', 'MM/DD/YYYY')
AND TO_DATE('06/03/2014','MM/DD/YYYY');
This syntax seems like it should work but it's not. I'm definitely not an oracle developer so I'm positive I"m misunderstanding something. When I've looked at similar posts I haven't found anything that would point to what I'm doing wrong.
This is a rather tricky error. The problem would occur if LOT_DATE were stored as a character string rather than a date -- and the string contained invalid data.
By explicitly converting the right hand side of the comparison to dates, the comparison is attempted by converting the field to a date. And there is an error.
The fix is to fix the data in the field. if something is in a field called "date", then it should probably have a date data type.
For identifying unsupported string value for date - You can create a PL/SQL function which accepts string and validate for correct date format, sample of function:
CREATE OR REPLACE FUNCTION VERIFY_DATE(v_date IN VARCHAR2) RETURN NUMBER IS
v_date1 DATE;
BEGIN
select to_date(v_date) into v_date1 from dual;
RETURN 1;
Exception WHEN Others THEN
RETURN 0;
END;
Now, identify rows which are having invalid string value for which you should correct to run your query:
select * from
(
select VERIFY_DATE(LOT_DATE) DateVerified,s.* from SHIPPED s
)
where
DateVerified=0
Related
I'm new to oracle and trying to run a simple query to pass date dynamically
DEFINE startdate = TO_DATE(select TRUNC(LAST_DAY(ADD_MONTHS( max(nav_last_calc_dt) ,-1))+1) from tb);
DEFINE enddate = TO_DATE(select TRUNC(LAST_DAY(ADD_MONTHS(max(nav_last_calc_dt),0))) from tb);
begin
select Count(1)
FROM tb
WHERE DATE BETWEEN &startdate AND &enddate;
end;
I received the below error when executing using script (F5), TOAD script runner.
ORA-06550: line 4, column 78:
PL/SQL: ORA-00936: missing expression
ORA-06550: line 2, column 1:
PL/SQL: SQL Statement ignored
But when using SQL PLUS , it returned 7 as result. So I'm confused.
SQL*Plus isn't returning 7 as the result; you haven't completed the anonymous PL/SQL block, so it is showing you 7 as the next line number (as 'begin' is line 1 and 'end;' is line 6, and is waiting for input. If you enter a slash and hit return it will then execute the block; which will throw the same ORA-00936 error.
In both clients the problem is the DATE keyword - it's expecting that to be the start of a date literal, and doesn't see the rest of the literal value as it expects. That should be a column name, presumably:
WHERE nav_last_calc_dt DATE BETWEEN &startdate AND &enddate;
But the block will still fail, possibly for different reasons in the two clients; in SQL*Plus it will still get ORA-00936 because the defined value ends at the first space (which you can fix by enclosing in double quotes), and Toad may throw that error or complain that your select has no 'into' clause. (Or it might do something else; SQL Developer against 12cR1 is throwing an internal error.) The outer TO_DATE in your defined expressions is also not ideal - it will implicitly convert the date you have to a string and then convert that string back again to a real date, both using your session NLS settings; which might work, but isn't needed.
It's not clear why you are using PL/SQL there, or really why you are using a substitution variable - it's not really dynamic, it just makes the final statement a bit more obscure.
The date calculation also seems a bit complicated. It looks like you're trying to count rows from the last month with any data; and you're finding the first day of that month using add_months and last_day - which could be done more simply just by truncating the maximum date using the 'MM' date component:
select count(*)
from tb
where nav_last_calc_dt >= (select trunc(max(nav_last_calc_dt), 'MM') from tb)
Assuming the column used for the filter is `nav_last_calc_dt, and not some other column, you don't need an upper bound - you know the maximum date is in that month, so it has to be within the month.
If if was another column, with later dates, and you used between then you would exclude any values after midnight on the last day of that month. It's safer to use a full month range:
select count(*)
from tb
where some_date >= (select trunc(max(nav_last_calc_dt), 'MM') from tb)
and some_date < (select add_months(trunc(max(nav_last_calc_dt), 'MM'), 1) from tb)
which would find all values at or after midnight on the first day of the target month, and before midnight on the first day of the following month.
It might then be worth getting the maximum date once, but you could do that in a CTE or an inline view rather than via define, which wouldn't actually save you anything the way you are trying to use it - since both defined queries would be substituted into the query/block before it's executed.
if i used like this im not get any error
(ph.x_date >= to_date('01/05/2016') and ph.x_date <= to_date('01/04/2020'))
but if range is big like this
(ph.x_date >= to_date('01/05/2002') and ph.x_date <= to_date('01/04/2020'))
i get invalid number error.
where is my mistake. Thanks
To_date() has to be always used when you know the date data would come in a particular format always that you know before hand. Use to_date like this To_date('date', <dateformat>) this reads the date in the explicit format that you may want to make it read.
In your case it reads default but what if your order of retrieval changes in your x_date i guess your data in xdate column has some issues. Check data before 2016. Different order like mm/yy/dd or etc data different from the to_date format is there
you need to specify the format of date, e.g. to_date('01/05/2002','DD/MM/YYYY') and make sure the date format you get from the table is the same as you specified
I think your data in SELECT list is having an issue
Please check the output of the below command and see whether it returns the output
select *
from data ph
where ph.x_date >= to_date('01/05/2002') and
ph.x_date <=to_date('01/05/2016') ;
We have a new software package that allows the company to write SQL code to be place on Query portals. We have several reports we wish to code using the previous day as one of the selections. If a report is ran on MONDAY we want to automatically select the previous FRIDAY as the selection date, We have ORACLE SQL DEVELOPER 4.1. The code we are trying to use is listed below:
SELECT ALERT_CD,ALERT_KEY,CHG_DTM,
CASE
WHEN TO_CHAR(SYSDATE,'fmday')='sunday'
THEN SYSDATE-2
WHEN TO_CHAR(SYSDATE,'fmday')='monday'
THEN SYSDATE-3
ELSE SYSDATE-1
END "change"
FROM SG00400T
WHERE ALERT_CD='AUTO'
and CHG_DTM >= to_date('SYSDATE', 'mm/dd/yyyy')
The error we are receiving:
ORA-01858: a non-numeric character was found where a numeric was expected
01858. 00000 - "a non-numeric character was found where a numeric was expected"
*Cause: The input data to be converted using a date format model was
incorrect. The input data did not contain a number where a number was
required by the format model.
*Action: Fix the input data or the date format model to make sure the
elements match in number and type. Then retry the operation.
The CHG_DTM is a date/time field which could be part of the problem we do not full understand at this time.
Any help would be greatly appreciated.
The expression to_date('SYSDATE', 'mm/dd/yyyy') is are trying to convert the string constant 'SYSDATE' to a date - which can't work.
But you should never, ever call to_date() on a value that is already a date. That will first convert the date value to a varchar just to convert that varchar back to a date which it was to begin with.
So the to_date() function is wrong at that place to begin with. Most probably you want:
and CHG_DTM >= trunc(SYSDATE)
I know there are loads of postings regarding fixing this error but, I'm just not understanding it!
val_strg1 value is 01.04.2016. I want to use this and not show lines where this date is older than current date, (i.e. and trunc(sysdate) < dv.val_strg1).
But, even though I have used a to_date format, I still get the a non-numeric character was found where a numeric was expected error?
I have tried several to_date formats;
to_date(val_strg1,'DDMMYYYY'), to_date(val_strg1,'DD-MM-YYYY')
The following gives me a 'not a valid month' error?
to_date(val_strg1,'DD-MON-YYYY')
My script...
select val_strg, val_strg1, to_date(val_strg1,'DDMMYYYY')
from sd_domainval_org
where name = 'HYPERCARE_CUNR'
order by sort_no
How can I use the val_strg1 as a date?
It seems you are using a text column (e.g. VARCHAR2) for the date. And you are saying that
to_date(val_strg1, 'DD.MM.YYYY')
results in an error. So you have a value in that column that does not match the pattern. Here is a query to find such invalid entries:
select *
from domainval
where name = 'HYPERCARE_CUNR'
and not regexp_like(val_strg1, '^[[:digit:]]{2}\.[[:digit:]]{2}\.[[:digit:]]{4}$');
You can then correct the wrong entries, but a better solution would of course be not to store dates in string columns at all. Use date columns instead, so as to not have such issues.
if your string date val_strg1 is in the form 'DD.MM.YYYY' (i.e. '01.04.2016'), then you have to use to_date(val_strg1,'DD.MM.YYYY');
for example: Select to_date('01.04.2016','DD.MM.YYYY') from dual;
If you have errors again, probably you have a string in the recordset that is not in a valid form for the to_date function (check the values in the val_strg1 column).
Bye,
Igor
I found an answer...
and trunc(sysdate) < to_date(regexp_substr(val_strg1, '^[[:digit:]]{2}\.[[:digit:]]{2}\.[[:digit:]]{4}$'),'DD.MM.YYYY')
...seems to work OK.
you have to tune formating string to exactly match your date structure
in this case
select val_strg, val_strg1, to_date(val_strg1,'DD.MM.YYYY')
from sd_domainval_org
where name = 'HYPERCARE_CUNR'
order by sort_no;
Oracle 10.2.0.5
What is the easiest way to identify rows in a table that have "invalid" values in DATE columns. By "invalid" here what I mean is a binary representation that violates Oracle rules for date values.
I recently had an issue with an invalid date stored in a column.
I was able to use a query predicate to find a particular problematic row:
WHERE TO_CHAR(date_expr,'YYYYMMDDHH24MISS') = '00000000000000'
In the case I had, the century byte was invalid...
select dump(h.bid_close_date) from mytable h where h.id = 54321
Typ=12 Len=7: 220,111,11,2,1,1,1
The century byte should be 100 + two digit century. In this case, there was an extra 100 added, as if the century value was "120", making the year "12011". (The only way I know to get invalid DATE values into the database is using OCI, using native 7-byte DATE representation.)
In this case, the TO_CHAR function returned an identifiable string, which I could use for identifying the wonky DATE value.
My question: is there an more general or easier approach (preferably using a SQL SELECT statement) to identify rows with "invalid" values in DATE columns.
This is a pretty unusual scenario (although I have come across something similar once before). The more common problem is finding invalid dates which are held as strings in a date column. You could adapt the solution for that to your situation, by building your own date validator.
Something like this:
create or replace function is_a_date
( p_date in date )
return varchar2
is
d date;
begin
d := to_date(to_char(p_date, 'SYYYYMMDDHH24MISS'), 'SYYYYMMDDHH24MISS') ;
if d != p_date then
return 'not a proper date';
else
return 'good date';
end if;
exception
when others then
return 'not a date';
end;
/
This converts a date into a string and back again. It catches exceptions thrown by date casting. If the end product is not the same as the input date then presumably something got lost in translation; to be honest I'm not sure whether the 12011 date would cast successfully to a string, so this is a belt'n'braces approach. It's a bit tricky writing this utility without some test data!
This query would identify all the non-valid dates:
select h.id, dump(h.bid_close_date)
from mytable h
where h.bid_close_date is not null
and is_a_date(h.bid_close_date) != 'good date';
Without adding a function, a simple predicate
TO_CHAR(date_col,'YYYYMMDDHH24MISS') = '000000000000'
appears to be satisfactory to identify corrupted values stored in an Oracle DATE column. The addition of a function appears to be unnecessary. Checking for corrupted dates should be able to be done in a SQL SELECT statement, and not require a user to have CREATE FUNCTION privilege on the database.
This identifies invalid months
SELECT rowid,
pk_column,
DUMP(date_column, 1010) AS dump1
FROM table
WHERE TO_NUMBER(SUBSTR(DUMP(date_column, 1010), INSTR(DUMP( date_column, 1010),
',', 1, 2
) + 1,
INSTR(DUMP(date_column, 1010), ',', 1, 3) - (
INSTR(DUMP( date_column, 1010), ',', 1, 2) + 1
))) = 0;
Update using the same where clause, I found the month number was zero in these cases.
I'd go for a method that can be implemented as a check constraint, probably through checking that the date is in the range of legal values.
However, ask yourself also whether it is valid to have a date of 1066-10-14? It is a legal value, but you probably do not have invoices printed on that day, for example. So you might like to roll the invalid date check into a larger issue of what you really consider to be valid in the context of your application.
I had an SQL Error: ORA-01841: (full) year must be between -4713 and +9999, and not be 0
01841. 00000 - "(full) year must be between -4713 and +9999, and not be 0".
So to identify the rows that had a bad date I did the following.
declare
cursor mydates is select table_pk, your_date_col from table;
c_date table.your_date_col%type;
c_pk table.table_pk%type;
testrow table.your_date_col%type;
begin
open mydates;
loop
begin
fetch mydates into c_pk, c_date;
exit when mydates%notfound;
testrow := TO_TIMESTAMP(c_date,'YYYY-MM-DD HH24:MI:SS');
exception when others then
dbms_output.put_line('bad file: ' || c_pk);
end;
end loop;
close mydates;
end;
So all I did was create a cursor, loop through the elements and tested each one and display the identifier so I could easily find the bad rows.