我有一个凌乱的表,里面充满了有时有一个DateTime的事件,在其他地方有一个分配给Date字段的DateTimeOffset,与此类似(只要您生活在划分王国的经度之外足够远):
DECLARE @MY_LOG TABLE ([MOMENT] DATETIMEOFFSET, [PAYLOAD] NVARCHAR(200));
INSERT INTO @MY_LOG ([MOMENT],[PAYLOAD]) VALUES (GETDATE(),'first entry')
WAITFOR DELAY '00:00:00.100';
INSERT INTO @MY_LOG ([MOMENT],[PAYLOAD]) VALUES (SYSDATETIMEOFFSET(),'second entry')
WAITFOR DELAY '00:00:00.100';
INSERT INTO @MY_LOG ([MOMENT],[PAYLOAD]) VALUES (GETDATE(),'third entry')
WAITFOR DELAY '00:00:00.100';
INSERT INTO @MY_LOG ([MOMENT],[PAYLOAD]) VALUES (SYSDATETIMEOFFSET(),'forth entry')
SELECT [MOMENT],[PAYLOAD] FROM @MY_LOG ORDER BY [MOMENT] ASC;
最后一次选择的结果将是此示例:
2020-03-31 02:39:10.6779279 +02:00 second entry
2020-03-31 02:39:10.8809259 +02:00 forth entry
2020-03-31 02:39:10.5730000 +00:00 first entry
2020-03-31 02:39:10.7770000 +00:00 third entry
我试图通过使用SWITCHOFFSET来修复它,它添加了丢失的偏移量,但也对其进行了补偿:
SELECT [MOMENT],
[PAYLOAD],
CASE WHEN DATEPART(tz,[MOMENT])=0 THEN SWITCHOFFSET(MOMENT, '+02:00') ELSE MOMENT END AS FIXED
FROM @MY_LOG ORDER BY FIXED ASC;
结果是:
2020-03-31 02:39:10.6779279 +02:00 second entry 2020-03-31 02:39:10.6779279 +02:00
2020-03-31 02:39:10.8809259 +02:00 forth entry 2020-03-31 02:39:10.8809259 +02:00
2020-03-31 02:39:10.5730000 +00:00 first entry 2020-03-31 04:39:10.5730000 +02:00
2020-03-31 02:39:10.7770000 +00:00 third entry 2020-03-31 04:39:10.7770000 +02:00
我可能还需要考虑像This question中那样的切换时刻,但是现在我正在寻找一种非破坏性(只读)解决方案来按日期对行进行排序
datetime2(7)
去除偏移量: