user2667326
user2667326

Reputation: 505

Can't convert column varchar to int

I have column of varchar data type with values like 5/3/2012. I want to convert into int as 2016-05-03. When I'm trying to do so, it is returning null as output

cast(convert(varchar(10), '5/3/2012', 112) as int) 

Upvotes: 0

Views: 167

Answers (3)

Nolan Shang
Nolan Shang

Reputation: 2328

  SELECT CONVERT(INT,convert(Datetime, '5/3/2012', 101))
--41030

Upvotes: 0

Michael
Michael

Reputation: 326

But if you truly do need to convert it to an INT, try this -

DECLARE @d DATE = '5/3/2012'
DECLARE @y int = YEAR( @d )
    , @m int = MONTH( @d )
    , @dy int = DAY( @d )

SELECT CAST(concat( @y, format(@m, '00'), format(@dy,'00')) as int)

Upvotes: 0

Pரதீப்
Pரதீப்

Reputation: 93694

2016-05-03 is a Date not a Integer value. So you need to convert it to Date

You just want to Convert it to Date with style 101

Select convert(Date, '5/3/2012', 101) --2012-05-03

Upvotes: 1

Related Questions