SQL Update a table from another table

大城市里の小女人 提交于 2019-12-02 04:28:41

问题


I am a complete beginner to SQL Server, and I have reached my limit.

Currently I am using a script to update a table from another table using a column. Since both databases are assigned to 2 different 3rd party software, I created a .bat script to use for task manager in windows server, that way it can update every 10 minutes.

While this is tested and works, I feel there has to be a way to create a relationship between the two databases without having to use the task.

UPDATE therefore.dbo.thecat51
SET num_factura = 
 (SELECT therefore.dbo.documentos.num_factura
 FROM therefore.dbo.Documentos
 WHERE therefore.dbo.thecat51.num_albaran=therefore.dbo.documentos.num_albaran)
WHERE therefore.dbo.thecat51.num_albaran = 
 ( SELECT therefore.dbo.documentos.num_albaran
 FROM therefore.dbo.Documentos
 WHERE therefore.dbo.thecat51.num_Albaran = therefore.dbo.documentos.num_albaran)

Also, we are using SQL Server Express, so I don't have the option to create a scheduled job.


回答1:


You can do the UPDATE with an INNER JOIN to perform the update you need:

UPDATE A SET
    num_factura = B.num_factura
FROM therefore.dbo.thecat51 A
    INNER JOIN therefore.dbo.Documentos B
        ON A.num_albaran = B.num_albaran



回答2:


Use an INNER JOIN between your two tables. At the time I posted this, you had not told us which RDBMS you are using so I will give answers for SQL Server and MySQL:

SQL Server:

UPDATE t1 
SET t1.num_factura = t2.num_factura
FROM therefore.dbo.thecat51 AS t1
INNER JOIN therefore.dbo.Documentos AS t2
    ON t1.num_albaran = t2.num_albaran

MySQL:

UPDATE therefore.dbo.thecat51 AS t1
INNER JOIN therefore.dbo.Documentos AS t2
    ON t1.num_albaran = t2.num_albaran
SET t1.num_factura = t2.num_factura


来源:https://stackoverflow.com/questions/37484487/sql-update-a-table-from-another-table

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