How can I update multiple tables with one query using Access ODBC?

随声附和 提交于 2019-12-11 09:47:48

问题


I've done a thorough search but can't find an answer to this question. I connect with Access ODBC and need to run a query which updates many tables at the same time based on one value.

Here's what I'm doing at the moment:

$DSN="accessodbc";
$DSN_User="myusername";
$DSN_Passwd="mypassword";
$objConnect = odbc_connect( $DSN, $DSN_User, $DSN_Passwd );

$strSQL1="UPDATE table1 SET column1='dup' WHERE User=" . $user;
$strSQL2="UPDATE table2 SET column1='dup' WHERE User=" . $user;
$strSQL3="UPDATE table3 SET column1='dup' WHERE User=" . $user;

$objExec1 = odbc_exec($objConnect, $strSQL1);
$objExec2 = odbc_exec($objConnect, $strSQL2);
$objExec3 = odbc_exec($objConnect, $strSQL3);

...and so on for about 50 tables.

This works but is obviously not the best solution resource-wise. Is there a way to update all the tables with one query?

Thanks in advance.


回答1:


While it is fairly unusual to UPDATE more than one table with a single SQL statement, in this particular case you probably can (although implementing this for ~50 tables might be more trouble than it's worth).

For the record, I just tested the following in Access 2010 and for the test tables

[table1]
User  column1
----  -------
Gord
Bob          

[table2]
User   column1
-----  -------
Gord
Homer         

[table3]
User      column1
--------  -------
Gord
Quagmire         

the query

UPDATE
    (
        table1
        INNER JOIN
        table2
            ON table1.User = table2.User
    )
    INNER JOIN
    table3
        ON table2.User = table3.User
SET
    table1.column1 = 'dup',
    table2.column1 = 'dup',
    table3.column1 = 'dup'
WHERE table1.User = 'Gord'

resulted in

[table1]
User  column1
----  -------
Gord  dup    
Bob          

[table2]
User   column1
-----  -------
Gord   dup    
Homer         

[table3]
User      column1
--------  -------
Gord      dup    
Quagmire         



回答2:


No. You can't update more than 1 table in a single query. You can, however, put all the updates into a transaction, and commit the transaction at the end of all the updates.

BEGIN TRANSACTION
   Do all your update statements.
COMMIT TRANSACTION

or, if something goes wrong: 

ROLLBACK TRANSACTION



回答3:


how about

For I = 1 to 50
   $strSQL = "Update table" & I & " set column1 = 'dubp' WHERE User=" & $user
   Odb_exec($objContact,$strSQL)
Next i


来源:https://stackoverflow.com/questions/20528709/how-can-i-update-multiple-tables-with-one-query-using-access-odbc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!