Kash
Kash

Reputation: 41

SQL Server - Convert number to date

I have a column that has year and month values together such as 201908. I would like to use this column to filter with regular calendar dates and wondering if there are any suggestions?

Upvotes: 0

Views: 99

Answers (1)

dvo
dvo

Reputation: 2153

Try adding a static '01' to your value and then you should be able to cast it to DATE or DATETIME:

DECLARE @str VARCHAR(10) = '201908'

SELECT CAST(CONCAT(@str, '01') AS DATE)

-- Returns DATE Value = '2019-08-01'

or

DECLARE @str VARCHAR(10) = '201908'

SELECT CAST(@str + '01' AS DATE)

-- Returns DATE Value = '2019-08-01'

Upvotes: 2

Related Questions