如何将此格式转换为日期时间?我使用的是SQL Server 2008.
字符串可以是d/m/aaaa
或dd/m/dddd
或d/mm/aaaa
或dd/mm/aaaa
,我需要将这些格式转换为datetime
。有什么想法吗?
答案 0 :(得分:1)
您可以将CONVERT()
用作:
DECLARE @S1 VARCHAR(20) = '1-1-2017';
DECLARE @S2 VARCHAR(20) = '11/1/2017';
DECLARE @S3 VARCHAR(20) = '1/11/2017';
DECLARE @S4 VARCHAR(20) = '11/11/2017';
SELECT CONVERT(DATETIME, @S1 , 104) AS S1,
CONVERT(DATETIME, @S2 , 104) AS S2,
CONVERT(DATETIME, @S3 , 104) AS S3,
CONVERT(DATETIME, @S4 , 104) AS S4;
结果:
+---------------------+---------------------+---------------------+---------------------+
| S1 | S2 | S3 | S4 |
+---------------------+---------------------+---------------------+---------------------+
| 01.01.2017 00:00:00 | 11.01.2017 00:00:00 | 01.11.2017 00:00:00 | 11.11.2017 00:00:00 |
+---------------------+---------------------+---------------------+---------------------+