Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 casting string to datetime

Author  Topic 

phaze
Starting Member

42 Posts

Posted - 2010-01-26 : 18:31:27
how would i cast a string to date?

for example my column has this 9/21/2009 as a string and i want to make it into a date

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2010-01-26 : 18:38:54
You can simply CAST or CONVERT it. If you are concerned about the regional settings you can use CONVERT with a STYLE parameter. For example:
CAST(MyString AS DATETIME)
CONVERT(DATETIME, MyString)
CONVERT(DATETIME, MyString, 101)
Go to Top of Page

phaze
Starting Member

42 Posts

Posted - 2010-01-26 : 18:44:03
now what if i wanted to change my entire column to datetime?

Go to Top of Page

russell
Pyro-ma-ni-yak

5072 Posts

Posted - 2010-01-26 : 20:17:26
ALTER TABLE tableName ALTER COLUMN columnName DATETIME;
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2010-01-27 : 04:17:56
That will make an implicit cast though, so be careful that your dates will be preserved.

If you do SELECT CAST('01/02/03' AS DATETIME)

that will tell you how an implicit cast will treat each of the three date parts

If that is not the right implicit cast for your date format you will need to:

Add a new, temporary, column with DATETIME datatype

UPDATE the table to convert the existing datetime column to the new, temporary, one using EXPLICIT CONVERT() with appropriate format (3rd parameter) specified

Drop the old column

Rename the temporary column to the original name

You may also have to recreate any indexes on the original column; hopefully no foreign keys using it!
Go to Top of Page
   

- Advertisement -