开发者

How to convert a string to datetime using T-SQL?

开发者 https://www.devze.com 2023-03-25 07:53 出处:网络
Hi all i\'m trying to parse an xml file in SQl Server 2005. I have a datetime field in the xml which is a string as follows: \'20110805060028.387\'. I want to conve开发者_运维百科rt this to a datetime

Hi all i'm trying to parse an xml file in SQl Server 2005. I have a datetime field in the xml which is a string as follows: '20110805060028.387'. I want to conve开发者_运维百科rt this to a datetime field in sql server, but i'm struggling with the syntax. Is it possible to get dd/mm/yyy hh:mm:ss.ms (ms = micro seconds) from this string?


Its not a supported format so you will need to;

declare @dt varchar(42)= '20110805060028.387'
--convert to '20110805 06:00:28.387'
select cast(stuff(stuff(stuff(@dt, 9, 0, ' '), 12, 0, ':'), 15, 0, ':') as datetime)

>>2011-08-05 06:00:28.387


Substring is your friend here:

DECLARE @Value NVarChar(50)
SET @Value = '20110805060028.387'
SELECT Convert(DateTime, 
    SubString(@Value, 1, 4) + '-' + 
    SubString(@Value, 5, 2) + '-' + 
    SubString(@Value, 7, 2) + ' ' + 
    SubString(@Value, 9, 2) + ':' + 
    SubString(@Value, 11, 2) + ':' + 
    SubString(@Value, 13, 10))

(by the way, I am purposefully NOT following your "dd/mm/yyy" format when creating a parseable date string here, but rather an international (not quite ISO-standard) format that SQL server will read correctly regardless of the server's DATEFORMAT settings)


DECLARE @parsedValue VARCHAR(MAX)
DECLARE @rawDateValue VARCHAR(MAX)
SET @rawDateValue  = '20110805060028.387'

SET @parsedValue =  SUBSTRING(@rawDateValue, 1, 4) + '/' +
SUBSTRING(@rawDateValue, 5, 2) + '/' +
SUBSTRING(@rawDateValue, 7, 2) + ' ' +
SUBSTRING(@rawDateValue, 9, 2) + ':' +
SUBSTRING(@rawDateValue, 11, 2) + ':' +
SUBSTRING(@rawDateValue, 13, 2) + ':' +
SUBSTRING(@rawDateValue, 16, 3)

SELECT CONVERT(datetime, @parsedValue)


My take (necessarily not the best):

DECLARE @val VARCHAR(30)='20110805060028.387'
SELECT LEFT(@val,4) [yyyy], RIGHT(LEFT(@val,6),2)[mm], RIGHT(LEFT(@val,8),2)[dd], 
      RIGHT(LEFT(@val,10),2)[hh], RIGHT(LEFT(@val,12),2)[mi], 
      RIGHT(LEFT(@val,14),2)[ss],SUBSTRING(@val, 15,LEN(@val)-14) [ms]

DECLARE @date DATETIME
SELECT @date = CAST(LEFT(@val,4) + '-' + RIGHT(LEFT(@val,6),2) + '-' + 
               RIGHT(LEFT(@val,8),2) + ' ' + RIGHT(LEFT(@val,10),2) + ':' +
               RIGHT(LEFT(@val,12),2) + ':' + RIGHT(LEFT(@val,14),2) + 
               SUBSTRING(@val, 15,LEN(@val)-14) AS DATETIME)

SELECT @date, DATEPART(MILLISECOND,@date)[ms], DATEPART(MONTH,@date)[MM]
0

精彩评论

暂无评论...
验证码 换一张
取 消