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 2000 Forums
 Transact-SQL (2000)
 Convert Varchar to Date

Author  Topic 

andersonb
Starting Member

5 Posts

Posted - 2012-05-09 : 10:09:07
New to SQL needing to convert:
InvoiceDate (varchar(8), not null) to a date to be able to select a date range in a view.
Can anyone help?
Sample: 20110401

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-05-09 : 10:31:00
VARCHAR(7) doesn't look like it would be long enough to store a date unless it is stored with a 2-digit century. Can you post some sample data that you are trying to convert to DATE?
Go to Top of Page

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-05-09 : 10:55:04
Assuming that it is in the YYYYMMDD format (i.e., 20110401 is April 1, 2011), you can simply cast it to DATETIME or SMALLDATETIME type.
CAST(InvoiceDate AS DATETIME)
Typically the expert recommendation is that you store the data in the correct data type to begin with. So ideally InvoiceDate column should be of type DATETIME or SMALLDATETIME.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2012-05-10 : 07:09:02
Also check for valid dates

select cast(col as datetime) from..
where len(col)=8 and isdate(col)=1
http://beyondrelational.com/modules/2/blogs/70/posts/10807/handle-isdate-with-care.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -