简体   繁体   English

T-SQL中来自一个源列表的多个表更新

[英]Multiple table updates from one source list in T-SQL

I have 3 tables that I wish to UPDATE data against (lets call them PROCESS , DIARY and HISTORY ) 我有3个表,希望对这些表进行数据UPDATE (将它们称为PROCESSDIARYHISTORY

The 3 tables all have an ID column and the subset of data I wish to update is retrieved from a SELECT statement against the PROCESS table 3个表都具有一个ID列,并且我希望更新的数据子集是从针对PROCESS表的SELECT语句中检索的

SELECT ID FROM PROCESS WHERE STATUS = 1 AND COMPANY = 'XYZ'

Using T-SQL, I was planning to do 3 UPDATE statements (with the PROCESS table being last as it is the reference list) like so 使用T-SQL,我打算做3条UPDATE语句( PROCESS表位于最后,因为它是引用列表),像这样

UPDATE HISTORY ... WHERE ID IN (SELECT ID FROM PROCESS WHERE STATUS = 1 AND COMPANY = 'XYZ')
UPDATE DIARY ... WHERE ID IN (SELECT ID FROM PROCESS WHERE STATUS = 1 AND COMPANY = 'XYZ'
)
UPDATE PROCESS ... WHERE STATUS = 1 AND COMPANY = 'XYZ'

My question is: is this the most efficient way to do this within T-SQL - or should I be creating some sort of CTE to reference only once? 我的问题是:这是在T-SQL中执行此操作的最有效方法吗?还是我应该创建某种CTE来仅引用一次? (The number of documents/performance are not a problem, I'm just trying to find out if as an ex OO developer coming to SQL, I'm slipping into bad habits or missing a trick somewhere (文档/性能的数量不是问题,我只是想了解一下,作为一名前OO开发人员使用SQL,我是否陷入了不良习惯或在某处缺少窍门?

I don't think you will be able to use CTE as CTE can be referenced only once. 我认为您将无法使用CTE,因为CTE只能被引用一次。 Updating 3 tables requires 3 separate queries to be run. 更新3个表需要运行3个独立的查询。

If obtaining the ID's in your inner query is expensive, you may consider running the query to get them only once and storing the results in a temporary table or table variable. 如果在内部查询中获取ID的成本很高,则可以考虑运行查询以仅获取一次并将结果存储在临时表或表变量中。 This way you will be able to reference that temporary table or table variable in all update statements. 这样,您将能够在所有更新语句中引用该临时表或表变量。

If the inner query is inexpensive to run, I would leave it as is to not complicate things unnecessarily. 如果内部查询的运行成本不高,我会保留它,以免不必要地使事情复杂化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM