Converting data with to_date function and combination of substrings - sql

some of my teammates messed up date format which is now in YYYY-DD-MM format 2013-24-09 in my table on Oracle database. I want to convert it into date format and try following code:
TO_DATE((SUBSTR(BEGINNING_DATE, 1, 4)||'-'||substr(BEGINNING_DATE, 9,2)||'-'||substr(BEGINNING_DATE,6, 2)), 'YYYY-MM-DD')
Still an error appears:
ERROR [HY000] ERROR: to_timestamp(): bad value 31 for day of the month
When I hower select seprate substrings into columns everything looks like below and I believe it is ok.
YYYY MM DD
2013 12 31
I wonder where do I make mistake. Can you help me?

If the value is stored in the database as a string, and you just want a date out of it, TO_DATE(BEGINNING_DATE, 'YYYY-DD-MM') should suffice. You could then convert it back with TO_CHAR (with the correct format) if you're trying to fix the records in the database.
As for your particular error, if they are all stored as strings, you might want to check what value it is failing on, and make sure that one in particular is valid (e.g., it isn't '2013-02-31' or something).

Related

SQL Server Not Casting String YYYYMMdd to Date

I have a query that was working fine before a server migration and now is not working. I'm trying to convert all dates to a specific month and year, but I keep getting this error:
Conversion failed when converting date and/or time from character string.
Looking into the data, there are no null values in InputDate, which is a date data type column. When I run the Concat() function everything is formatted as 'YYYYMMdd', yet both CAST and CONVERT fail with the same error.
Is there an issue with my query that I'm not seeing?
SELECT RandoSTUFF,
DATEADD(day,2,CAST(CONCAT('2023','02',FORMAT(InputDate,'dd')) AS date)) AS MovedDate
FROM a_table_
I expect the issue is you have date values near the end of their months, and you're trying to compose the equivalent values for February, which is shorter.
So if you have an InputDate value of, say, 2022-12-31 and run the code in the question, it will extract the 31 and concat it with the other values, and you'll end up trying to do this:
CAST('20230231' as Date)
Of course, there is no such date.
As it is, it's not clear whether you want such an input to map to February 28 or March 3. To fix this, you'll need to rethink the problem so you only try to map to valid dates, and ensure the final result is more clearly defined. This is one of the many reasons it's almost always better to use Date/time functions instead of composing dates from strings.

Change system date suggestions nedded

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)

Why is there an issue with the ADD_MONTHS function in Oracle SQL

I am using the online APEX Oracle DB for some training and have ran into a problem with one of the functions that has me scratching my head.
I have done some testing and have been able to get it to work the long hand way but not the shortened syntax. Using the shortened syntax returns an error which I can't figure out. Any help would be appreciated.
What I have tried:
select add_months('2015/10/12', 4) from dual
returns an error:
ORA-01846: not a valid day of the week
What I got to work:
select add_months(to_date('2015/10/12', 'yyyy/mm/dd'), 4) from dual
when I use the add_months(to_date()) format
I get back the correct result of, Friday, 12 February, 2016
If I use the add_months(arg1, arg2) it returns the error.
add_months expects date but you are providing VARCHAR without formatting which causes unexpected errors.
Basically oracle cannot implicitly converts given format to date
I was able to get this figured out. I ran systimestamp and this was what was returned :
Saturday, 02 February, 2019.
I then took and plugged in this into the function I was having trouble with
select add_months(systimestamp, 4) from dual and it returned the correct result :
Sunday, 02 June, 2019 depending on my date formatting.
Find you current NLS_DATE_FORMAT with below SQL
SELECT value FROM v$nls_parameters WHERE parameter ='NLS_DATE_FORMAT';
Basically when you pass a date as varchar2 string, this format is used for the implicit date conversion.
So, instead of dealing with the default date format, we should always use explicit date conversion using TO_DATE()

Conversion of Date for direct sql query in OBIEE using presentation variable

I am trying to achieve this use case: when there is no date picked I want to show all the results but when I have date picked I want it to filter.
fyi:
the date getting picked are YYYY-MM-DD HH24:MI:SS in the presentation variable, but the date format in my query is dd-mon-yy. So when I need to convert the value of the presntation varible to dd-mon-yy.
OBIEE doesnt like when I play around with the values, and the BI server does not let me look at the error message.
I dont have access to change the format on the server level so my only option is to use formulas
I'm new to presentation variable.
ALso I need you'll to remember if there is no date selected in the prompt I would want all values returned
code:
and
( ( main_query.schd_compare >= (#{pv_task_sch_st_date}['#']{NVL(main_query.schd_compare,'None')})
)
AND (
main_query.schd_compare <= (#{pv_task_sch_end_date}['#']{NVL(main_query.schd_compare,'None')})
) )
I need help with syntax for obiee
Inside the database, it doesn't care if a date is "DD Mon YY" or "YYYY-MM-DD HH24:MI:SS". Those are just formatting, and the actual bit value of that date will be the same. So if both "dates" are actually a date datatype, then you can just use something like:
....
AND (
(
main_query.schd_compare >= NVL(pv_task_sch_st_date,main_query.schd_compare)
)
AND
(
main_query.schd_compare <= NVL(pv_task_sch_end_date,main_query.schd_compare)
)
)
That's if your pv_task_sch_???_date are passed as NULL values when not selected. Oracle does seem to treat empty strings and NULL the same in comparisons like this, but you it can be hard to debug if you get in the habit of relying on NULL and '' being the same.
As for your query, my guess is that your pv_task... values are actually being passed to your query as a some sort of string. If that's the case, then you'll need to put a TO_DATE() around your pv_task... variables.
Take a look at https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=2066b2005a22769e785815f6b03750a1. I stepped through a few examples of how your dates can be treated.
I did say earlier that the database doesn't care when format your date is in. And it is stored the same, no matter the format. But when you're using TO_DATE() or other similar functions, Oracle wants you to specify the proper mask of your data. If you send "01 Jan 99" to TO_DATE(), Oracle needs to know how to interpret that value. So you tell it that the string is "DD Mon YY". You can't do TO_DATE('2018-09-10','YYYY-MM-DD HH24:MI:SS') because my input doesn't have a time component. ( I would also caution about using 2-digit years. )
By the way, I hate dates. And dealing with dates in Oracle reinforces that hatred.

character_length Teradata SQL Assistant

I have to run column checks for data consistency and the only thing that is throwing off my code is checking for character lengths for dates between certain parameters.
SEL
sum(case when ( A.date is null or (character_length(A.date) >8)) then 1 else 0 end ) as Date
from
table A
;
The date format of the column is YYYY-MM-DD, and the type is DA. When I run the script in SQL Assistant, I get an error 3580 "Illegal use of CHARACTERS, MCHARACTERS, or OCTET_LENGTH functions."
Preliminary research suggests that SQL Assistant has issues with the character_length function, but I don't know how to adjust the code to make it run.
with chareter length are you trying to get the memory used? Becuase if so that is constant for a date field. If you are trying to get the length of the string representation i think LENGTH(A.date) will suffice. Unfortanatly since teradata will pad zeros on conversions to string, I think this might always return 10.
UPDATE :
Okay so if you want a date in a special 'form' when you output it you need to select it properly. In teradata as with most DBs Date are not store in strings, but rather as ints, counting days from a given 'epoch' date for the database (for example the epoch might be 01/01/0000). Each date type in teradata has a format parameter, which places in the record header instructions on how to format the output on select. By default a date format is set to this DATE FROMAT 'MM/DD/YYYY' I believe. You can change that by casting.
Try SELECT cast(cast(A.date as DATE FORMAT 'MM-DD-YYYY') as CHAR(10)) FROM A. and see what happens. There should be no need to validate the form of the dates past a small sample to see if the format is correct. The second cast forces the database to perform the conversion and use the format header specified. Other wise what you might see is the database will pass the date in a date form to SQL Assitant and sql assitant will perform the conversion on the application level, using the format specified in its own setting rather then the one set in the database.