Home All Groups Group Topic Archive Search About

cast and convert differ?

Author
10 Aug 2006 8:22 AM
cn.popeye
this is date: 01 08 2006
declare @d_date varchar(20)
set @d_date = '01 08 2006'

using convert:
select convert(datetime,@d_date ,120)
------
01 08 2006

replace space to '-'
select convert(datetime,replace(@d_date,' ','-') ,120)
------
01 08 2006

replace space to '/'
select convert(datetime,replace(@d_date,' ','/') ,120)
------
01 08 2006

using cast:
cast(@d_date as datetime)
------
2006-08-01 00:00:00.000

Author
10 Aug 2006 8:27 AM
Uri Dimant
Hi
CONVERT function has a third parameter STYLE. For details please refer to
the BOL



Show quote
"cn.popeye" <cn-po***@126.com> wrote in message
news:udB$yXFvGHA.1224@TK2MSFTNGP03.phx.gbl...
> this is date: 01 08 2006
> declare @d_date varchar(20)
> set @d_date = '01 08 2006'
>
> using convert:
> select convert(datetime,@d_date ,120)
> ------
> 01 08 2006
>
> replace space to '-'
> select convert(datetime,replace(@d_date,' ','-') ,120)
> ------
> 01 08 2006
>
> replace space to '/'
> select convert(datetime,replace(@d_date,' ','/') ,120)
> ------
> 01 08 2006
>
> using cast:
> cast(@d_date as datetime)
> ------
> 2006-08-01 00:00:00.000
>
>
Author
10 Aug 2006 10:05 AM
Tibor Karaszi
I do not get the same result as you posted. See my comments with my results inline below. I executed
the code from SSMS running against SQL Server 2005 with sp1.

"cn.popeye" <cn-po***@126.com> wrote in message news:udB$yXFvGHA.1224@TK2MSFTNGP03.phx.gbl...
> this is date: 01 08 2006
> declare @d_date varchar(20)
> set @d_date = '01 08 2006'
>
> using convert:
> select convert(datetime,@d_date ,120)
> ------
> 01 08 2006

This one fails. Code 120 is 'yyyy-mm-dd' with optional time part. Your string has spaces and not
"-"s.


> replace space to '-'
> select convert(datetime,replace(@d_date,' ','-') ,120)
> ------
> 01 08 2006

This on is OK because you first replace the spaces with "-" so the string follow code 120 rule. The
output, btw is:
-----------------------

2006-01-08 00:00:00.000

Reason for above output is that result from query is datetime datatype and SSMS is free to convert
that binary datetime information to something humany readable. If you see something different it
would be because you have some other tool and possibly specified the tool to use regional settings
when presenting datetime data.


> replace space to '/'
> select convert(datetime,replace(@d_date,' ','/') ,120)
> ------
> 01 08 2006

This gives same result as above. Apparently, SQL Server tries to be friendly and accelt "/" instead
of "-" even though



> using cast:
> cast(@d_date as datetime)
> ------
> 2006-08-01 00:00:00.000

First, you need SELECT in front of above. Second, above fails with conversion error. See
http://www.karaszi.com/SQLServer/info_datetime.asp

AddThis Social Bookmark Button