Convert Nvarchar DD/MM/YYYY to YYYY-MM-DD in SQL Query

Viewed 17230

Hi I have a column in my 'Users' table called 'PersonalDetails_DOB'.

The data type is a NVARCHAR(10) and the 'format' the data is currently in DD/MM/YYYY.

I want to change the format to YYYY.MM.DD or YYYY-MM-DD, how would I do this?

I have already tried a running a query in SQL:

 SELECT CONVERT(nvarchar(10), PersonalDetails_DOB, 102) as
 'PersonalDetails_DOB' FROM Users;

Nothing happens and it doesn't change any date from e.g. 06/02/1967 to 1967.02.06

4 Answers

Store dates as dates, not strings. I recommend you pull the value as a date and not a string:

SELECT CONVERT(date, PersonalDetails_DOB, 103) as PersonalDetails_DOB
FROM Users;

You are safer using try_convert():

SELECT TRY_CONVERT(date, PersonalDetails_DOB, 103) as PersonalDetails_DOB
FROM Users;

To find the bad values, you can do:

select PersonalDetails_DOB
from users
where  TRY_CONVERT(date, PersonalDetails_DOB, 103) is null;

You can convert back a string if you want.

I would recommend that you fix the data structure. This should work:

update users
    set PersonalDetails_DOB = CONVERT(date, PersonalDetails_DOB, 103);

alter users alter column PersonalDetails_DOB date;

You need two convert() function :

SELECT PersonalDetails_DOB, 
       CONVERT(VARCHAR(10), CONVERT(DATE, PersonalDetails_DOB, 103), 102)
FROM Users;

You can try the below query to update the date values format and also their data type using SUBSTRING() function as shown below

declare @PersonalDetails_DOB NVARCHAR(10)
set @PersonalDetails_DOB = '13/10/2018' --dd/MM/yyyy

select SUBSTRING(@PersonalDetails_DOB,7,4) + '-' + SUBSTRING(@PersonalDetails_DOB,4,2) 
+ '-' + SUBSTRING(@PersonalDetails_DOB,1,2) 
         -- yyyy-MM-dd

create table Users(PersonalDetails_DOB NVARCHAR(10))
insert into Users values ('01/10/2018')
select * from Users --Before Update

--Updating date values
update Users
set PersonalDetails_DOB = (
    SUBSTRING(@PersonalDetails_DOB,7,4) + '-' + SUBSTRING(@PersonalDetails_DOB,4,2) 
        + '-' + SUBSTRING(@PersonalDetails_DOB,1,2) 
)where PersonalDetails_DOB is not null

select * from Users --After Update

--Change the datatype
ALTER TABLE Users
ALTER COLUMN PersonalDetails_DOB date;

You can find the live demo Live Demo Here

Maybe you should first set dateformat before conversion:

set dateformat dmy;
select PersonalDetails_DOB
    ,convert(nvarchar(10), cast(PersonalDetails_DOB as datetime), 102) as ANSI_DOB
    ,convert(nvarchar(10), cast(PersonalDetails_DOB as datetime), 120) as ODBC_DOB
from Users;
Related