[英]Convert multiple columns (year,month,day) to a date
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
. 问题是月份或日期可以是个位数,而我一直在丢失该
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
. 在进行转换之前,我先在视图上尝试了该方法,但是甚至无法获得这三列来给出类似
20090517
的字符串。
Any ideas? 有任何想法吗?
CAST
and RIGHT
doesn't seem to be doing it for me. CAST
和RIGHT
似乎并没有为我做。
You can use DATEADD 您可以使用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 结果是2013-05-20
You can replace the variables in the SELECT command with the ones in your table. 您可以将SELECT命令中的变量替换为表中的变量。
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
我最终使用
dateadd(month,(@YEAR-1900)* 12 + @MONTH - 1,0) + (@DAY-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.