HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Changing an nvarchar column to datetime

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
changingnvarchardatetimecolumn

Problem

I am new to SQL Server and I have a problem.

I created a database to store dates in an nvarchar field but now I need to convert that field to datetime. I searched the internet and couldn't find a proper solution.

One thing I found was to create a new datetime column, copy string value to that, then rename the new column to original one.

My string value format is 21/11/2014. I need to keep the same format. If anyone could give me a SQL Server query that can do that, I'd highly appreciate. I'm using SQL Server Management Studio 2014.

Solution

As you probably have already found out, dates should be stored as dates and not as their human readable representation (varchar).

In order to convert from string to date, you have to use the conversion functions available in your version of SQL Server (which seems to be 2014 if it is the same as Management Studio). In this case, you can use the PARSE function.

Example:

SELECT PARSE('21/11/2014' AS datetime USING 'it-IT')


You can read more about date to string and string to date datatype conversion in this article: http://www.sqlservercentral.com/articles/T-SQL/88152/

Back to your issue, add a new datetime column, for instance newCol, update the values parsing the strings, drop the old column and rename the new column to the original name:

ALTER TABLE YourTable ADD newCol datetime NULL;
UPDATE YourTable SET newCol = PARSE(oldCol AS datetime USING 'it-IT');
ALTER TABLE YourTable DROP COLUMN oldCol;
EXEC sp_rename 'YourTable.newCol', 'oldCol', 'COLUMN';

Code Snippets

SELECT PARSE('21/11/2014' AS datetime USING 'it-IT')
ALTER TABLE YourTable ADD newCol datetime NULL;
UPDATE YourTable SET newCol = PARSE(oldCol AS datetime USING 'it-IT');
ALTER TABLE YourTable DROP COLUMN oldCol;
EXEC sp_rename 'YourTable.newCol', 'oldCol', 'COLUMN';

Context

StackExchange Database Administrators Q#100727, answer score: 5

Revisions (0)

No revisions yet.