Link to home
Start Free TrialLog in
Avatar of Larry Brister
Larry BristerFlag for United States of America

asked on

Casting varchar as DateTime SQL Server 2005 with smallest unit of time

In SQL Server 2005, does it only calculate to milliseconds?

Looking for an explanation for below

DECLARE @dt VARCHAR(26)
SET @dt = '2013-07-24 12:20:42.005135'

--This works
SELECT @dt

--This works
SELECT CONVERT(VARCHAR(23),@dt)

--This fails
SELECT CAST(@dt AS DATETIME)
--Msg 241, Level 16, State 1, Line 7
--Conversion failed when converting datetime from character string.
Avatar of edtechdba
edtechdba
Flag of United States of America image

This should work.
SELECT CONVERT(VARCHAR(23),@dt,101)

Open in new window


And if you would like your date in a different format, here's a reference for changing 101 (above) to a different date format.
http://www.sql-server-helper.com/tips/date-formats.aspx
Oops, I'm sorry! Looks like you are trying to convert VARCHAR back to DATETIME. :)

Here you go .. VARCHAR to DATETIME
SELECT CONVERT(DATETIME,CAST('2013-07-24 12:20:42.005135' AS VARCHAR(23)))
SELECT CONVERT(DATETIME,CAST(@dt AS VARCHAR(23)))

Open in new window

Avatar of Larry Brister

ASKER

My question was does sql server only go to milliseconds?
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks