1

I have a column in my SQL Server database of nvarchar datatype, and I store dates with ####/##/## format in it. With my mistake some of dates store with ##/##/#### format.

How can I modify all dates in my database to format ####,##,##?

Example: 01/01/2016 to 2016/01/01

6
  • Is the bad data mm/dd/yyyy (American) or dd/mm/yyyy (Nearly everywhere else) Commented Jan 12, 2017 at 13:16
  • 2
    Their is a datatype called date for saving dates then why are you trying to compromise with nvarchar Commented Jan 12, 2017 at 13:17
  • 7
    If you're in the mood to fix the data, why not do it right and switch to using a datetime2 or date column? Commented Jan 12, 2017 at 13:17
  • 2
    Don't store dates in your database as strings. Use the proper data type. Only convert to a string at the point where you actually need to display to the user. Commented Jan 12, 2017 at 13:22
  • 2
    The problem is the field type, not the format. You should store dates in date-typed fields (date, datetime etc). Fix your table schema, not your data Commented Jan 12, 2017 at 13:24

1 Answer 1

5

Use CONVERT function. Write simple SQL query:

UPDATE YourTable 
-- get Date from nvarchar and format to yyyy/mm/dd
SET DateColumn = CONVERT(nvarchar,CONVERT(DATE, DateColumn, 103), 111)
-- only in rows that can be parsed from dd/mm/yyyy format
WHERE TRY_CONVERT(DATE, DateColumn, 103) IS NOT NULL 

103 - dd/mm/yyyy format. 111 - yyyy/mm/dd format. check this article

But actually you really should store your dates in DATE type column not in NVARCHAR.

Sign up to request clarification or add additional context in comments.

4 Comments

i get this error : 'TRY_CONVERT' is not a recognized built-in function name.
@R.F.V what version of MS SQL do you use? It's 2012 version function
Microsoft SQL Server 2012 - 11.0.2100.60
@R.F.V strange... I tested on my 2012 db - woks fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.