在SQL Server 2008中使用T-SQL将格式日期字符串转换为datetime

时间:2017-09-29 08:46:01

标签: sql sql-server-2008 tsql datetime

如何将此格式转换为日期时间?我使用的是SQL Server 2008.

字符串可以是d/m/aaaadd/m/ddddd/mm/aaaadd/mm/aaaa,我需要将这些格式转换为datetime。有什么想法吗?

1 个答案:

答案 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 |
+---------------------+---------------------+---------------------+---------------------+