如何将 BST 和 GMT 格式的字符串日期转换为 SQL 服务器格式作为日期类型

How to convert string date in BST and GMT format to SQL Server format as date type

我将 table 导入到 SQL Server 2014 中,发现日期格式为 BSTGST 格式。我想创建一个视图并将整个列更改为 SQL 服务器日期类型以执行操作。我不介意截断时间部分。

Wed Apr 07 00:00:00 BST 1943
Tue Jan 08 00:00:00 GMT 1985

我能够在 Excel 中使用以下公式完成,但想在 SQL 服务器中完成:

=IFERROR(DATEVALUE(MID(E2,9,2)&"-"&MID(E2,5,3)&"-"&RIGHT(E2,4)), "")

我要找的是

1943-04-07
1985-01-08

此解决方案假定源数据中的每一行都遵循相同的格式。如果有任何边缘情况,这些将失败。

使用 SQL Server 2012 及更高版本,您可以方便地使用源字符串中的 DATEFROMPARTS function. This function returns a date when passed a year, month and day. These can be extracted with SUBSTRING and RIGHT

提取月份数(1~12)是通过构建任意日期字符串(01-mmm-2000)实现的。这被转换成一个日期,从中提取月份数。一般来说,我不建议使用 YYYY-MM-DD 以外的任何格式的日期字符串。但是,这避免了使用 OP 热衷于使用的 CTE。

示例

/* Let's create some sample values to 
 * experiment with.
 */
DECLARE @Sample TABLE
    (
        DateVal VARCHAR(50) 
    )
;

INSERT INTO @Sample
    (
        DateVal
    )
VALUES
    ('Wed Apr 07 00:00:00 BST 1943'),
    ('Tue Jan 08 00:00:00 GMT 1985')
;


/* Extracting the month number is achieved by first casting the 3 character month
 * name as a full date, by appended a day and year.  Then the month number is 
 * extracted from this.
 */
SELECT
    s.DateVal,
    SUBSTRING(s.DateVal, 9, 2)                                               AS [Day],
    MONTH(CAST('01-' + SUBSTRING(s.DateVal, 5, 3) + '-2000' AS DATE))        AS [Month],
    RIGHT(s.DateVal, 4)                                                      AS [Year],

    -- Reuse the values shown above.
    DATEFROMPARTS(
        RIGHT(s.DateVal, 4), 
        MONTH(CAST('01-' + SUBSTRING(s.DateVal, 5, 3) + '-2000' AS DATE)),
        SUBSTRING(s.DateVal, 9, 2)
    )                                AS [Date]
FROM
    @Sample AS s
;

编辑: 原始解决方案包含一个 CTE,用于从 3 个字符的月份名称中查找月份编号。这已被替换。

您的示例输出与您的输入数据不匹配。我想你的意思是 1985-01-08.

对于更短的解决方案,您可以将 CAST or CONVERT 与样式 107 一起使用。它希望字符串采用 Mon dd, yyyy 格式:

SELECT  CONVERT(datetime, SUBSTRING(DateColumn, 5, 6) + ', ' + RIGHT(DateColumn, 4), 107)
FROM    MyTable
SELECT  CONVERT(date, RIGHT(DateColumn, 4)+ '-' + RIGHT('0' + Convert(nvarchar, (Month(SUBSTRING(DateColumn, 5, 3) + '2016'))), 2) + '-' + SUBSTRING(DateColumn, 9, 2))   as dob
FROM    MyTable