[英]SQL int to string to datetime
I have date in integers. 我有整数日期。
What is the cleanest way to convert integers to datetime? 将整数转换为日期时间的最干净方法是什么?
I used this messy way: 我用这种凌乱的方式:
CONVERT(DATETIME, cast(source.Day as varchar(2)) + '/' + cast(source.Month as varchar(2)) + '/' + cast(source.Year as varchar(2)), 3),
You can use DATEFROMPARTS function: 您可以使用DATEFROMPARTS函数:
SELECT DATEFROMPARTS ( 2010, 12, 31 ) AS Result;
Note, it is only available in 2012+ editions. 请注意,仅在2012+版本中可用。
Here is how you can do that 这是你可以做到的
Declare @date date,
@year INT = 2014,
@Month INT = 10,
@DateDay INT = 12,
@parseDate char(20)
select @date = CONVERT(date,
CAST( Cast(@Year as char(4))
+ Cast(@Month as char(2)) +
cast(@DateDay as char(2)) AS CHAR(12)), 112)
select @date
Note : I am not handling NULL cases. 注意 :我不处理NULL情况。
尝试这个:
select CONVERT (datetime,convert(char(8),yourvalue))
Working from RTs solution this might work 在RT解决方案中工作可能会起作用
CREATE TABLE DATA(yr int, mth int, dy int);
INSERT INTO DATA
VALUES (2014,10,15);
SELECT
CONVERT (DATETIME,
CONVERT(char(4), yr) +
CONVERT(char(2), mth) +
CONVERT(char(2), dy)
) as Result
FROM DATA
This is still a bit messy and assumes a 4 digit year integer. 这仍然有点混乱,并假设使用4位数字的年整数。
SQL Fiddle here: http://sqlfiddle.com/#!6/cbf62/2 SQL小提琴在这里: http ://sqlfiddle.com/#!6/cbf62/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.