将数据从访问数据库插入/更新到SQL Server数据库

我有一个ms访问数据库文件和一个sql server数据库 . 我需要在php中编写一些东西,以便能够使用访问数据库数据更新sql数据库 . 更新意味着更新现有条目并插入新条目 .

从访问db文件连接和获取的脚本:

<?php
$connStr = 'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .'Dbq=C:\\myfile.accdb;';
$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT ID, `LAST NAME` AS lm, `FIRST NAME` AS fm,  FROM OLD";
$sql .= " UNION ALL SELECT ID, `Last Name` AS lm, `First Name` AS fm,  FROM NEW) ";
$sql .= " ORDER BY lm";

$sth = $dbh->prepare($sql);
$params = array();
$sth->execute($params);

while ($row = $sth->fetch()) {
//do something with $row['lm'] and $row['fm']
}
?>

从sql db文件连接和获取的脚本:

<?php
$sql = "SELECT * FROM MYTABLE";
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false) {
    echo 'Error. Could not execute query!';  
}

while ($rowsec = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
     //do something with $rowsec['MYTABLE_COLUMN']
?>

那么,我如何组合这两个查询以从访问文件中获取数据并从sql表中插入/更新记录?

假设当我在更新/插入sql表之前从访问文件中读取数据时,我需要检查访问文件中的列并修改如下:

<?php 
if($row['fm'].indexOf('am') > -1) {$id = 'am'.$row['ID']}
?>

然后我应该在$ row ['lm']和$ row ['fm']值中使用$ id来插入/更新到sql数据库 .

先感谢您

回答(1)

3 years ago

如上所述,如果允许用户使用ad-hoc分布式查询权限,并考虑使用相同的ODBC连接驱动程序在结果集之间进行任何循环,请考虑SQL Server的OPENROWSET

INSERT QUERY

INSERT INTO MYTABLE (ID, LM, FM)
SELECT t.*
FROM (SELECT ID, [LAST NAME] AS lm, [FIRST NAME] AS fm  
      FROM OPENROWSET('MSDASQL',
                      'Driver={Microsoft Access Driver (*.mdb, *.accdb)};
                       DBQ=C:\\myfile.accdb', 'SELECT * FROM [OLD]')

      UNION ALL 

      SELECT ID, [LAST NAME] AS lm, [FIRST NAME] AS fm  
      FROM OPENROWSET('MSDASQL',
                      'Driver={Microsoft Access Driver (*.mdb, *.accdb)};
                       DBQ=C:\\myfile.accdb', 'SELECT * FROM [New]')
     ) t
WHERE NOT EXISTS (SELECT 1 FROM MYTABLE s WHERE s.ID = t.ID)
ORDER BY t.LM

UPDATE QUERY

UPDATE t
SET t.Lm = n.lm, t.Fm = n.fm
FROM MYTABLE t
INNER JOIN 
    (SELECT ID, [LAST NAME] AS lm, [FIRST NAME] AS fm  
     FROM OPENROWSET('MSDASQL',
                     'Driver={Microsoft Access Driver (*.mdb, *.accdb)};
                      DBQ=C:\\myfile.accdb', 'SELECT * FROM [OLD]')

     UNION ALL 

     SELECT ID, [LAST NAME] AS lm, [FIRST NAME] AS fm  
     FROM OPENROWSET('MSDASQL',
                     'Driver={Microsoft Access Driver (*.mdb, *.accdb)};
                      DBQ=C:\\myfile.accdb', 'SELECT * FROM [New]')
    ) n
ON t.ID = n.ID

或者,使用ACE OLEDB Provider:

FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',   
   'C:\\myfile.accdb';'admin';'', Old)

一定要在PHP查询字符串中加倍单引号(类似于加倍 \ ) .