Converting VARCHAR to Date using TO_DATE - snowflake-cloud-data-platform

I have a set of data where the col is VARCHAR() but I need it to be in DATE format.
I was trying to do it as follows:
CREATE OR REPLACE TABLE df_new
AS SELECT
col1 AS NAME
col2 AS first_name
col3 AS last_name
,TO_DATE(col4, 'yyyymmdd') AS date
FROM df_old
but I am getting an error "Can't parse '' as date with format 'yyyymmdd'".
I have tried messing with the input for the date format (such as 'yyyy/mm/dd') but I am pretty new to SQL so I am unsure of how to proceed.

Just use TRY_TO_DATE, it will return NULL for values where it can't parse the input.

If you are certain that all of your values other than NULLs are of the string 'yyyymmdd' then the following will work in snowflake.
TO_DATE(TO_CHAR(datekey),'yyyymmdd')

Sounds like some of your col4 entries are NULL or empty strings. Try maybe
... FROM df_old WHERE col4 ~ '[0-9]{8}'
to select only valid inputs. To be clear, if you give the format as 'YYYYMMDD' (you should use uppercase) an entry in col4 has to look like '20190522'.

All dates are stored in an internal format.
You cannot influence how a date is STORED. However you have it format it the way you want when you pull the data from the database via query.

I was able to resolve by the following:
CREATE OR REPLACE TABLE df_new
AS SELECT
,col1 AS NAME
,col2 AS first_name
,col3 AS last_name
,CASE WHEN "col4" = '' then NULL ELSE TO_DATE(col4, 'YYYYMMDD') AS date
FROM df_old

I resolved the issue as follows:
CREATE OR REPLACE TABLE df_new
AS SELECT
col1 AS NAME
,col2 AS first_name
,col3 AS last_name
,CASE WHEN col4 = '' THEN NULL ELSE TO_DATE(col4, 'YYYY-MM-DD') END AS date
FROM df_old

Related

convert different string date formats from single column to one form of output in sql server

I have one date columns as varchar datatype which has multiple date formats. I have to convert all different formats into one date format as 'YYYY-MM-DD'.
I am trying to convert it but couldn't make it. Below are different formats available in column.
Input
8/15/2022
15-Aug-22
15/08/2022
Required Output
2022-08-15
Honestly, I think you need to take the pessimistic approach here and assume that, possibly for a lot of your data, you don't know what the value is meant to be. As I stated in the comments, if you have the value '01/12/2021' is that 1 December 2021 or 12 January 2021, how do you know, and more importantly how would SQL Server know? As such, for dates like this you don't know and therefore the value NULL is more appropriate that a guess.
Here I use 3 different formats, an implicit one, and then 2 explicit ones (MM/dd/yyyy and dd/MM/yyyy) Then I check if the MIN and MAX values match (NULL values are ignored for aggregation), and if they do return that value. If they don't then NULL, as what value the date is is ambiguous and therefore intentionally shown as an unknown value (NULL):
You can, if needed, add more styles to the below, but this should be enough for you to work with.
CREATE TABLE dbo.YourTable (ID int IDENTITY(1,1), --I assume you have a unique identifier
StringDate varchar(20));
INSERT INTO dbo.YourTable (StringDate)
VALUES('8/15/2022'), --Must be M/d/yyyy
('15-Aug-22'),
('15/08/2022'), --Must be dd/MM/yyyy
('12/01/2021'); --Could be MM/dd/yyyy or dd/MM/yyyy
GO
SELECT YT.ID,
YT.StringDate,
CASE MAX(V.SomeDate) WHEN MIN(V.SomeDate) THEN MAX(V.SomeDate) END AS DateDate
FROM dbo.YourTable YT
CROSS APPLY (VALUES(TRY_CONVERT(date,YT.StringDate)), --Implicit conversion
(TRY_CONVERT(date,YT.StringDate,101)), --US style MM/dd/yyyy
(TRY_CONVERT(date,YT.StringDate,103)))V(SomeDate) --UK style dd/MM/yyyy
GROUP BY YT.ID,
YT.StringDate;
GO
DROP TABLE dbo.YourTable;
db<>fiddle
You can use a combination of TRY_CONVERT and REPLACE function in a CASE operator to do so.
As an example :
DECLARE #T TABLE(STR_DATE VARCHAR(32));
INSERT INTO #T VALUES
('8/15/2022'),
('15-Aug-22'),
('15/08/2022');
SELECT CASE
WHEN TRY_CONVERT(DATE, STR_DATE, 101) IS NOT NULL
THEN CONVERT(DATE, STR_DATE, 101)
WHEN TRY_CONVERT(DATE, REPLACE(STR_DATE, '-', ' '), 6) IS NOT NULL
THEN CONVERT(DATE, REPLACE(STR_DATE, '-', ' '), 6)
WHEN TRY_CONVERT(DATE, STR_DATE, 103) IS NOT NULL
THEN CONVERT(DATE, STR_DATE, 103)
END
FROM #T

Date Conversion in snowflake

I am facing issue in date conversion in snowflake
Tab1 : Date(DD-MM-YYYYY) Col1 : 03-10-2018
Tab2 : Date(YYYY-MM-DD) Col2 : 2018-10-03
I need to join
Tab1.Col1=Tab2.Col1
I am getting error as
Date '03-10-2018' is not recognized.
How to convert this date into 'YYYY-MM-DD' Please advise.
I have tried with all format :
TO_TIMESTAMP_NTZ(Date(DOS, 'YYYY-MM-DD')),
Date((DOS, 'YYYY-MM-DD'),
TO_Varchar(Date(DOS, 'DD-MM-YYYY'),'YYYY-MM-DD')
All above mentioned formula facing the same error :
Thanks in advance
I don't quite understand this part of your question if datatype of your columns tab1.col1 and tab2.col2 is date: Date(DD-MM-YYYYY) and Date(YYYY-MM-DD)
Date is date, it does not have any formats when it is saved. You apply formats when you insert dates in text format to tell in which format the given value is, or when you select the date and want to output it in some specific format.
This works with date-type columns, joining is done without any formatting functions:
create table tab1 (col1 date);
create table tab2 (col2 date);
insert into tab1 (col1) values ( to_date('03-10-2018','dd-mm-yyyy') );
insert into tab2 (col2) values ( to_date('2018-10-03','yyyy-mm-dd') );
select *
from tab1, tab2
where Tab1.Col1=Tab2.Col2;

Change SQL Server date string ot other format

Please forgive me for my dunglish, I am dutch.
I have a table that looks like this:
CREATE TABLE [dbo].[WSLogons]
(
[Date] [nchar](15) NULL,
[Time] [nchar](15) NULL,
[Username] [nchar](15) NULL,
[Domain] [nchar](15) NULL,
[Computer] [nchar](15) NULL,
[HostComputerName] [nchar](15) NULL
) ON [PRIMARY]
There is no primary key.
I fill this table with some user data and I made a big mistake well multiple but I am facing the fact that my date and time columns are filled wrong.
This is have solved but in my database I have different date and time formats.
and I am querying with a convert date and time function.
This is not working because in some rows, I have date and time values like this:
5/18/2018 9:00 AM
5/18/2018 8:28 AM
and in some in the right way like this
18-05-2018 14:52
as I was saying, I query for information with a order by and a convert
order by CONVERT(date, Date, 105) desc
If in the results are date and time with the US notation, I get a format error.
Now I am as you can see not a SQL guru. I have corrected the script that is filling the table but now I want to convert the wrong dates into the right format so the data is saved.
I'd like to get a nice result in a query with this statement.
SELECT
CONVERT(date, [Date] ,101) as datum
,[Time]
,[Username]
,[Domain]
,[Computer]
,[HostComputerName]
FROM
[AuditLogons].[dbo].[WSLogons]
WHERE
date LIKE '%/%/%'
AND Time LIKE '%:% AM%' OR Time LIKE '%:% PM%'
Now the datum column is presented as
2018-05-18 11:59 AM
2018-05-18 1:25 PM
How do I get from here to update those rows in formatting the date like 18-5-2018?
If I try to convert to do
CONVERT(date, [Date], 105)
I get an error, too.
Hope you can understand my problem and I hope for some help
Many thanks.
Roger
This seems to work, but the underlying issue is that rule number one of database design is to use the appropriate data types. If you can change those columns, do it; if you can't, make sure you are validating your input.
DECLARE #WSLogons TABLE(
[Date] [nchar](15) NULL,
[Time] [nchar](15) NULL
)
INSERT INTO #WSLogons ([Date],[Time]) SELECT '5/18/2018','9:00 AM'
INSERT INTO #WSLogons ([Date],[Time]) SELECT '5/18/2018','09:00'
SELECT *
,CONVERT(datetime2, [Date] + ' ' + [Time]) as datum
FROM #WSLogons
first add real date column to your table:
alter table dbo.WSLogons add realDate datetime;
then update it with proper data ie:
update dbo.WSLogons
set realDate = CONVERT(datetime, Date, 101)
where Date like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'
for date format in dd/mm/yyyy style
for other formats see here

sql CONVERT to datetime does not change printed date format

I have a column in a table updatedDate - which is a datetime data type.
Data sample:
2017-10-15 18:08:22.000
2017-10-15 18:07:44.000
2017-10-15 18:07:17.000
2017-10-15 18:07:10.000
2017-10-14 18:00:54.000
2017-10-13 17:59:23.000
2017-10-13 17:59:13.000
I would like to display a list of DISTINCT dates, in the format of dd/mm/yyyy, but for the life of me... I can't get it. I would think it should be:
SELECT DISTINCT convert(datetime,updatedDate,103)
FROM [tblStudentCourses]
ORDER BY updatedDate DESC
But it does not actually convert to the 103 format... it just gives it to me as the full date and time format as originally, without any CONVERT.
What I want to get would be:
15/10/2017
14/10/2017
13/10/2017
What am i doing wrong?
Thanks!
To display the date in DD/MM/YYYY format, you can use CONVERT(VARCHAR(10), DateColumn, 103).
To maintain the proper ordering, you can wrap it all in a subquery. For example:
SELECT DisplayDate
FROM (
SELECT DISTINCT
DisplayDate = CONVERT(VARCHAR(10), CAST(UpdatedDate AS DATE), 103),
ActualDate = CAST(UpdatedDate AS DATE)
FROM [tblStudentCourses]
) AS T
ORDER BY ActualDate;
Note: Cast the date column to date if it's datetime like your sample data.
SELECT DISTINCT convert(VARCHAR,updatedDate,103)
FROM [tblStudentCourses]
ORDER BY updatedDate DESC
You should use convert to varchar for formating to various date formats

TSQL : Conversion failed when converting date and/or time from character string

I had a query that was working but after importing again one table I see the following problem when converting a Varchar into DateTime.
I have the following problem when running the following query:
select FORMAT(convert (datetime,date) , 'ddMMyyyy') from kat.[dbo].[myTable]
If I try the following I see the same problem:
SELECT convert(datetime, date, 126) from kat.[dbo].[myTable]
The dates that I have in the main table follow the same format:
2017-09-01
EDit with Data Screenshot for the Format:
MAny thanks in advance,
Kat
The dates that I have in the main table follow the same format:
2017-09-01
There are some stings in your table that have different format.
Try to catch them with this code:
select *
from kat.[dbo].[myTable]
where dt not like '[1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]';
In future, don't store datetime values as strings, use datetime/date.
UPDATE
So it's not true that your strings are like '2017-09-01'
Here is my example with your date:
declare #t table (dt varchar(20));
insert into #t values ('2017-09-01');
select *
from #t
where dt not like '[1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]';
My code returns no rows because '2017-09-01' reflects the format you inicated, and if it returns all rows in your case, the format is different.
I actually think strings cannot be converted directly to dates (at least not when you use CAST)... Why not convert the string to an int first?
Assuming your column is named [Date], I would stick with:
SELECT
cast(DATEADD(DAY, cast([Date] as int), -2) as date) as [Date]
FROM kat.[dbo].[myTable]
If you have a different column name, here is the template:
SELECT
cast(DATEADD(DAY, cast([MyColumnName] as int), -2) as date) as [MyColumnName]
FROM kat.[dbo].[myTable]
Alternatively, I've also updated your code using CONVERT (which honestly I rarely every use so it could be wrong)
SELECT convert(datetime, convert(int, [Date]), 126) from kat.[dbo].[myTable]

Resources