0

I have a script from an SQL Server database that includes statements such as this:

INSERT SPECIAL_DAYS_TABLE (Date, Description) VALUES (CAST(0xB5330B00 AS Date), 'Christmas')

My question: how can I convert this into valid MySQL syntax? The cast part returns a null date value...

Unfortunately, I have no access to the SQLServer database, do direct data import is impossible - the script is the only thing that I can work with.

Note: there are hundreds of such statements, so I need to programmatically convert the cast part either in MySQL or outside MySQL (C/Java/Matlab/VB).

EDIT: answer closed as per how to cast the hexadecimal to varchar(datetime)? and the correction by Martin in the comment below

Apparently, the 0xB5330B00 should be interpreted as 0x000B33B5 (i.e., reverse the bytes) = 734133 (days since 0001-Jan-01)

CAST('0001-01-01 00:00:00' + INTERVAL CAST(0x000B33B5 AS SIGNED) DAY as date) => 2010-12-28
4

1 回答 1

1

根据如何将十六进制转换为 varchar(datetime)?以及 Martin 在下面的评论中的更正,显然,0xB5330B00 应解释为 0x000B33B5(即反转字节)= 734133(自 0001 年 1 月 1 日以来的天数)

所以完整的答案是:

INSERT SPECIAL_DAYS_TABLE (Date, Description) VALUES (CAST('0001-01-01' + INTERVAL 0x000B33B5 DAY as date), 'Christmas')

请注意此问题/解决方案与上面引用的问题/解决方案之间的差异:

  • 对于datetime,基准 SQLServer 日期是 1900-01-01;因为date它是 0001-01-01
  • 对于datetime,十六进制格式有 8 个字节不能颠倒(最左边 4 个字节是日期,最右边 4 个字节是时间);因为date只有 4 个字节需要反转

总之,这是一个将 SQLServerdatedatetime对象转换为等效 MySql 语法的示例 Matlab 代码:

% Convert dates in MATLAB from SQLServer => MySQL

% Datetime: byte order is NOT reversed & start date is 1/1/1900
str = regexprep(str, 'CAST\(0x(........)(........) AS DateTime\)', ...
                     'CAST(''1900-01-01'' + INTERVAL 0x$1 DAY + INTERVAL 0x$2/300 second as datetime)');

% Date: byte order is reversed & start date is 1/1/0001
str = regexprep(str, 'CAST\(0x(..)(..)(..)(..) AS Date\)', ...
                     'CAST(''0001-01-01'' + INTERVAL 0x$4$3$2$1 DAY as date)');

这个片段可以很容易地适应其他编程语言。

于 2013-04-12T12:57:23.377 回答