Soham Dasgupta
Soham Dasgupta

Reputation: 5199

SQL Server cast string to datetime

I have a string 010910 in ddMMyy format thatI have to cast this string a SQL Server datetime datatype, like 2010-09-01 00:00:00.000.

How can this be done?

Upvotes: 2

Views: 2433

Answers (3)

t-clausen.dk
t-clausen.dk

Reputation: 44316

SELECT CAST(right(s, 2) + left(s,4) as datetime)
FROM (SELECT '010910' s) a

Upvotes: 2

Adriaan Stander
Adriaan Stander

Reputation: 166376

How about something like

DECLARE @String VARCHAR(6)
SELECT  @String = '010910'

SELECT  CONVERT(DATETIME,LEFT(@String,2) + '/' + SUBSTRING(@String, 3, 2) + '/' + RIGHT(@String,2),3)

Have a look at SQL Server Date Formats and CAST and CONVERT (Transact-SQL)

Upvotes: 5

Marcelo Cantos
Marcelo Cantos

Reputation: 185842

Pull the bits out using SUBSTRING and put them back together by concatenating.

Upvotes: 1

Related Questions