SQL Server 的 ntext、image 類型無法直接寫入 MySQL;時間戳字段(SQL Server datetime vs MySQL int)類型衝突;導出表結構字段類型往往不匹配業務需求。
核心思路:先在 MySQL 建好目標表結構,再用腳本逐行讀取 SQL Server 數據,轉換後寫入 MySQL。完全掌握類型轉換、異常處理、批次提交。
<?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);
}
?>
<%
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
%>
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