首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

SQL Server 遷移 MySQL 實戰:腳本導入法避開數據類型陷阱

     編輯:MySQL 資料庫相關知識

為什麼不推薦 ODBC 直接導出

SQL Server 的 ntext、image 類型無法直接寫入 MySQL;時間戳字段(SQL Server datetime vs MySQL int)類型衝突;導出表結構字段類型往往不匹配業務需求。

推薦方案:PHP/ASP 腳本可控導入

核心思路:先在 MySQL 建好目標表結構,再用腳本逐行讀取 SQL Server 數據,轉換後寫入 MySQL。完全掌握類型轉換、異常處理、批次提交。

PHP 版本實現

<?php
// 連接 SQL Server (ODBC)
$cnx = odbc_connect('web', 'admin', '123456');
$cur = odbc_exec($cnx, 'SELECT * FROM user');

// 連接 MySQL
$conn = mysql_pconnect('localhost', 'root', '123456');
mysql_select_db('mydb', $conn);

while (odbc_fetch_row($cur)) {
    $f1 = odbc_result($cur, 1);  // id
    $f2 = odbc_result($cur, 2);  // name
    $f3 = odbc_result($cur, 3);  // username
    $f4 = odbc_result($cur, 4);  // password
    $f5 = odbc_result($cur, 5);  // recdate (datetime)

    // datetime → Unix 時間戳
    $f5 = strtotime($f5);

    $sql = "INSERT INTO user (id, name, username, password, recdate)
            VALUES ('$f1', '$f2', '$f3', '$f4', '$f5')";
    mysql_query($sql, $conn);
}

function strtotime($dt) {
    // 簡化版,實際建議用 DateTime 類
    list($date, $time) = explode(' ', $dt);
    list($y, $m, $d) = explode('-', $date);
    list($h, $i, $s) = explode(':', $time);
    return mktime($h, $i, $s, $m, $d, $y);
}
?>

ASP 版本實現

<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "web", "admin", "123456"
Set rs = Server.CreateObject("ADODB.Recordset")
' SQL Server 直接轉 Unix 時間戳
sql = "SELECT ID, name, username, password, 
       DATEDIFF(s, '1970-01-01 00:00:00', recdate) - 8*3600 AS recdate_ts
       FROM senddate"
rs.Open sql, conn, 1, 3

Set conn1 = Server.CreateObject("ADODB.Connection")
conn1.Open "myoa", "root", "q1-d6=7?"

Do While Not rs.EOF
    f1 = rs(0): f2 = rs(1): f3 = rs(2): f4 = rs(3): f5 = rs(4)
    sql1 = "INSERT INTO user (ID, name, username, password, recdate) " & _
           "VALUES (" & f1 & ", '" & f2 & "', '" & f3 & "', '" & f4 & "', " & f5 & ")"
    conn1.Execute sql1
    rs.MoveNext
Loop
%>

大字段特殊處理

  • ntext → nvarchar(4000):若實際長度 < 4000,直接轉換無截斷風險
  • image → 文件系統:按 Content-Type 確定副名,用 ADODB.Stream 寫入磁盤,庫中存路徑
Function MakeAttach(contentType, binaryData, idx)
    Select Case contentType
        Case "application/msword": ext = "doc"
        Case "image/jpeg": ext = "jpg"
        ' ... 其他類型
    End Select
    If ext <> "x" Then
        fname = "attach" & idx & "." & ext
        Set fso = Server.CreateObject("Scripting.FileSystemObject")
        Set strm = Server.CreateObject("ADODB.Stream")
        strm.Type = 1: strm.Open: strm.Write binaryData
        strm.SaveToFile "d:\attach\" & fname, 2
        MakeAttach = fname
    End If
End Function

經驗總結

  1. 腳本法雖繁瑣但可控,適合異構遷移
  2. 時間類型統一用 Unix 時間戳(INT)存儲,跨庫無痛
  3. 大對象落地文件,庫存路徑,性能與擴展性雙贏
  4. 遷移前務必做數據質量檢查(唯一鍵、外鍵、非空)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved