Question

I've got a few columns that I'm trying to convert to one, but I'm having some issues here.

The problem is that the Month or day can be single digit, and I keep losing that 0.

I'm trying it on a view first before I do the conversion, but can't even get the three columns to give a string like this 20090517.

Any ideas? CAST and RIGHT doesn't seem to be doing it for me.

Was it helpful?

Solution 2

Alternatively

DECLARE @YEAR int
DECLARE @MONTH int
DECLARE @DAY int

SET @YEAR = 2013
SET @MONTH = 5
SET @DAY = 20

SELECT RIGHT('0000'+ CONVERT(VARCHAR,@Year),4) + RIGHT('00'+ CONVERT(VARCHAR,@Month),2) + RIGHT('00'+ CONVERT(VARCHAR,@Day),2)

Gives

20130520

OTHER TIPS

You can use DATEADD

DECLARE @YEAR int
DECLARE @MONTH int
DECLARE @DAY int

SET @YEAR = 2013
SET @MONTH = 5
SET @DAY = 20


SELECT CONVERT(DATE,
 DATEADD(yy, @YEAR -1900, DATEADD(mm, @MONTH -1 ,DATEADD(dd, @DAY -1, 0))))

Result is 2013-05-20

You can replace the variables in the SELECT command with the ones in your table.

I ended up using

dateadd(month,(@YEAR-1900)* 12 + @MONTH - 1,0) + (@DAY-1)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top