|
database
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
cast and convert differ?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 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 > > 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. -- Tibor Karaszi, SQL Server MVP http://www.karaszi.com/sqlserver/default.asp http://www.solidqualitylearning.com/ "cn.popeye" <cn-po***@126.com> wrote in message news:udB$yXFvGHA.1224@TK2MSFTNGP03.phx.gbl... This one fails. Code 120 is 'yyyy-mm-dd' with optional time part. Your string has spaces and not > 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 "-"s. > replace space to '-' This on is OK because you first replace the spaces with "-" so the string follow code 120 rule. The > select convert(datetime,replace(@d_date,' ','-') ,120) > ------ > 01 08 2006 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 '/' This gives same result as above. Apparently, SQL Server tries to be friendly and accelt "/" instead > select convert(datetime,replace(@d_date,' ','/') ,120) > ------ > 01 08 2006 of "-" even though > using cast: First, you need SELECT in front of above. Second, above fails with conversion error. See > cast(@d_date as datetime) > ------ > 2006-08-01 00:00:00.000 http://www.karaszi.com/SQLServer/info_datetime.asp |
|||||||||||||||||||||||