문제

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.

도움이 되었습니까?

해결책 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

다른 팁

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top