SQL generate string from splitting another - sql

I have a number of corrupt Dates in an Advantage database, but luckily I have a reverse date field which is intact.
I need to use SQL to recreate the Date field in the form 'DD/MM/YYYY' from the RDate string 'YYYYMMDD'.
Something equivalent to:
UPDATE table SET Date = FormatDate('DD/MM/YY',StrToDate('YYYYMMDD',RDate))
I don't know if this is possible to select character positions and use variables this way in SQL or if I'll have to write a program (in Delphi) to do the operation.
Thanks

Try something like
update table set
date = cast(substring(rdate, 5, 2) + '/' +
right(rdate, 2) + '/' +
left(rdate, 4) as date)
/* where ... */
(assuming your connection's date format setting is the default 'MM/DD/YYYY')

TOndrej I'm not sure if it was a syntax error or if cast is not recognised but I achieved the desired result with the following SQL:
update members set "Expiry Date" = ((substring(RExpiryDate,7,2)) + '/' + (substring(RExpiryDate,5,2)) + '/' + (substring(RExpiryDate,1,4)))
Thanks for your help

Related

Change Date Format using Existing Date

I have a table that contains 20,000 rows. I want to change my existing date format from 2016-04-04 to 4/4/16. I have googled it but I only found the solution for changing to the current time. This is my query.
UPDATE [master].[dbo].[TRY]
SET Target_Hire_Date = CONVERT(VARCHAR(20), GETDATE(), 103)
But this query only for the current time which is not working for my problem.
Use your date column instead.
UPDATE [master].[dbo].[TRY]
SET Target_Hire_Date = CONVERT(VARCHAR(20), [YOUR-DATE-COLUMN], 103)
UPDATE [master].[dbo].[TRY]
SET Target_Hire_Date =
CONVERT(VARCHAR(10),CAST(#a as DATE),103)
to have exactly the format d/m/yy, try this:
UPDATE [master].[dbo].[TRY]
SET Target_Hire_Date = convert(nvarchar,day(YOUR_EXISTING_DATE)) + '/'
+ convert(nvarchar,MONTH(YOUR_EXISTING_DATE)) + '/' +
convert(nvarchar,RIGHT(YEAR(YOUR_EXISTING_DATE),2))
just supposing the YOUR_EXISTING_DATE is DATETIME
is better to store dates in a DATE column, then choose the format with the query

Oracle use LIKE '%' on DATE

My table myTab has the column startDate, which has the datatype "DATE". The data in this column are stored like dd.mm.yyyy.
Now I'm trying to get data with this query:
SELECT * FROM myTab WHERE startDate like '%01.2015"
Somehow it doesn't work and I don't know why.
Hope someone can help.
To make a text search on the date you would have to convert the date to text.
It's more efficient if you calculate the first and last date for what you want to find and get everything between them. That way it's done as numeric comparisons instead of a text pattern match, and it can make use of an index if there is one:
SELECT * FROM myTab WHERE startDate >= DATE '2015-01-01' AND startDate < DATE '2015-02-01'
SELECT * FROM myTab WHERE TO_CHAR(startDate,'dd.mm.yyyy') LIKE '%01.2015'
If the field type is "DATE" then the value isn't stored as a string, it's a number managed by Oracle, so you have to convert it to a string:
SELECT * FROM myTab WHERE to_char(startDate, 'MM.YYYY') = '01.2015';
You can also use date ranges in SQL queries:
SELECT * FROM myTab
WHERE startDate
BETWEEN to_date('01.01.2015', 'DD.MM.YYYY')
AND to_date('31.01.2015', 'DD.MM.YYYY');
Regarding you actual question "Somehow it doesn't work and I don't know why."
Oracle make an implicit conversion from DATE to VARHCAR2, however it uses the default NLS_DATE_FORMAT which is probably different to what you use in your query.
The data in this column are stored like dd.mm.yyyy.
Oracle does not store date in the format you see. It stores it internally in proprietary format in 7 bytes with each byte storing different components of the datetime value.
WHERE startDate like '%01.2015"
You are comparing a DATE with a STRING, which is pointless.
From performance point of view, you should use a date range condition so that if there is any regular INDEX on the date column, it would be used.
SELECT * FROM table_name WHERE date_column BETWEEN DATE '2015-01-01' AND DATE '2015-02-01'
To understand why a Date range condition is better in terms of performance, have a look at my answer here.
I solved my problem that way. Thank you for suggestions for improvements. Example in C#.
string dd, mm, aa, trc, data;
dd = nData.Text.Substring(0, 2);
mm = nData.Text.Substring(3, 2);
aa = nData.Text.Substring(6, 4);
trc = "-";
data = aa + trc + mm + trc + dd;
"Select * From bdPedidos Where Data Like '%" + data + "%'";
To provide a more detailed answer and address this https://stackoverflow.com/a/42429550/1267661 answer's issue.
In Oracle a column of type "date" is not a number nor a string, it's a "datetime" value with year, month, day, hour, minute and seconds.
The default time is always midnight "00:00:00"
The query:
Select * From bdPedidos Where Data Like '%" + data + "%'"
won't work in all circumstances because a date column is not a string, using "like" forces Oracle to do a conversion from date value to string value.
The string value may be year-month-day-time or month-day-year-time or day-month-year-time, that all depends how a particular Oracle instance has set the parameter NLS_DATE_FORMAT to show dates as strings.
The right way to cover all the possible times in a day is:
Select *
From bdPedidos
Where Data between to_date('" + data + " 00:00:00','yyyy-mm-dd hh24:mi:ss')
and to_date('" + data + " 23:59:59','yyyy-mm-dd hh24:mi:ss')
SELECT * FROM myTab WHERE startDate like '%-%-2015';
This will search for all dates in 2015. If this doesn't work, try:
SELECT * FROM myTab WHERE startDate like '%-%-15';

Converting nvarchar to date column

I have a table that has a column of dates in m/d/yyyy format stored in nvarchar(50) data types (I inherited this...). I would like to convert these columns into date data types so they are correctly stored, but can't afford to accidentally drop the data in the columns.
I've tried doing this in SQL server 2008R2, using the designer to change the data type to date. This worked for my test column (kept the dates, corrected the format, etc.) but all nulls became 1900-01-01. I can live with that but it seems there's a more eloquent solution.
However, when I tried it on the real data column, I received an error:
Unable to modify table. Conversion failed when converting date and/or time from character string.
What would be the proper way to handle this? Sorry if this is duplicate. I've been looking for an hour and haven't figured it out.
You apparently have data somewhere in the table that SQL Server is unable to convert to date. You can find the rows with a query along these lines:
SELECT * FROM TableName WHERE ISDATE(ColumnName) != 1
Obviously, you'll need to substitute TableName and ColumnName with the actual names.
Once you've identified the rows with bad data, handling it is up to you... change the data manually for each row, set them to null, whatever you feel is acceptable in this case.
I would suggest you add a new column with a Date datatype then convert/copy the data over and finally delete the original column.
what you can do is
add another column to the table of type DATETIME
Update new column values by casting the existing column values as DATETIME
Remove the existing column
Maybe you can temporally duplicate the columns with the data type of date, with this you can run an update command to convert the varchar to datetime and store it in this new columns, when you are sure that all information is correct, you can delete the columns and rename the new ones to their original name.
I always do this when I need to ensure to not lose information on change data types.
You can use following query to update your date to ISO Format (yyyymmdd) which will gurantee to work in any server. SQL SERVER - DEMO covers 4 possible cases of your date like 'd/m/yyyy','dd/m/yyyy','d/mm/yyyy' & 'dd/mm/yyyy' and update them to ISO Format
Update mytable
Set d = right(d,charindex('/',reverse(d),1)-1) +
right('0' + substring(d, charindex('/',d,1) + 1, charindex('/', d, charindex('/',d,1) + 1 ) - charindex('/',d,1) -1 ),2) +
right('0' + left(d,charindex('/',d,1)-1),2)
Or you can use this method directly in a select query as
Select id,convert(date,
right(d,charindex('/',reverse(d),1)-1) +
right('0' + substring(d, charindex('/',d,1) + 1, charindex('/', d,
charindex('/',d,1) + 1 ) - charindex('/',d,1) -1 ),2) +
right('0' + left(d,charindex('/',d,1)-1),2)
) correctDate
From mytable

update date value in oracle

I need to convert date format in ORACLE SQL Developer
The current format is yyyy/mm/dd-hh:mm:ss:sss and I need to convert it to yyyy-mm-dd hh:mm:ss CST
I don't really know SQL but did some research.
Here is the command that I consultanted other people on the forum. but it throws me unrecognized command error. table name is B and column name is First
UPDATAE B
set First = concat(to_char(substring(FIRST,1,4) + '-' + substring(FIRST, 6, 2) + '-' + substring(FIRST, 9, 2) + ' ' + substring(FIRST, 12, 8));
Could anyone here help me with it? thanks in advance.
The "unrecognized command" is merely a misspelling of UPDATE:
UPDATAE B
// Should be
UPDATE B
To verify the result is what you expect before executing the UPDATE statement, use a SELECT:
SELECT
to_char(substr(FIRST,1,4) || '-' || substr(FIRST, 6, 2) || '-' || substr(FIRST, 9, 2) || ' ' || substr(FIRST, 12, 8)) AS Test
FROM B
Umm... I'm either missing something extremely obvious or everyone else is.
You want to date operations? Use to_date and to_char. I'm going to assume this ss:sss means, seconds, then fractional seconds. You date appears to be a string so we need to convert it twice:
update b
set first = to_char( to_date( my_date, 'yyyy/mm/dd-hh:mi:ss:ff3')
,'yyyy-mm-dd hh:mi:ss' )
Generally, when using dates it's far, far easier to only use date functions and the provided formats.
As an added point if you have a date, store it as a date. It'll save a world of bother later on.

Computed column

In current table I have a column that holds the date field in ddmmyyyy format and it is of type varchar(8). The column has some string value also. I want to create a computed column that will hold the value in DateTime format if the value in source column is valid date time.
Assuming your varchar(8) column is dateString :
Cast([dateString] as datetime)
SQL Server prefers dates in the format of yyyymmdd so there will be some string manipulation involved to format your data like this. We should also use the IsDate function to make sure we have a valid date.
So:
Cast(Case When IsDate(Right(#Data, 4)
+ SubString(#Data, 3, 2)
+ Left(#Data, 2)) = 1
Then Right(#Data, 4)
+ SubString(#Data, 3, 2)
+ Left(#Data, 2) End As DateTime)
Notice that this code should correctly handle invalid dates contained within your varchar column. If a date is invalid, this code will return NULL.
try parsing your varchar into dd/mm/yyyy before attempting the cast:
cast(substring([datestring],1,2) + '/' +
substring([datestring],3,2) + '/' +
substring([datestring],5,4) as datetime)