我想一次更新两个表。如何在SQL Server 2005中做到这一点?
UPDATE
Table1,
Table2
SET
Table1.LastName='DR. XXXXXX',
Table2.WAprrs='start,stop'
FROM
Table1 T1,
Table2 T2
WHERE
T1.id = T2.id
AND
T1.id = '010008'
我想一次更新两个表。如何在SQL Server 2005中做到这一点?
UPDATE
Table1,
Table2
SET
Table1.LastName='DR. XXXXXX',
Table2.WAprrs='start,stop'
FROM
Table1 T1,
Table2 T2
WHERE
T1.id = T2.id
AND
T1.id = '010008'
当前回答
您应该在事务中放置两个更新语句
其他回答
这适用于MySQL,实际上只是一个隐式事务,但它应该是这样的:
UPDATE Table1 t1, Table2 t2 SET
t2.field = t2.field+2,
t1.field = t1.field+2
WHERE t1.id = t2.foreign_id and t2.id = '123414'
如果你要对多个表进行更新,需要多条语句,如果你先更新一个表,然后根据其他条件更新另一个表,这很可能是可能的,你应该使用事务。
您不能在一条语句中更新多个表,但是,您可以使用一个事务来确保两个update语句被原子地处理。您还可以批量处理它们以避免往返。
BEGIN TRANSACTION;
UPDATE Table1
SET Table1.LastName = 'DR. XXXXXX'
FROM Table1 T1, Table2 T2
WHERE T1.id = T2.id
and T1.id = '011008';
UPDATE Table2
SET Table2.WAprrs = 'start,stop'
FROM Table1 T1, Table2 T2
WHERE T1.id = T2.id
and T1.id = '011008';
COMMIT;
简短的回答是否定的。虽然可以在更新语句的from子句中输入多个表,但只能在update关键字后指定单个表。即使您确实编写了一个“可更新”视图(它只是一个遵循某些限制的视图),像这样的更新也会失败。以下是来自MSDN文档的相关片段(重点是我的)。
更新(transact - sql)
table_or_view_name引用的视图必须是可更新的,并且在视图的FROM子句中只引用一个基表。有关可更新视图的更多信息,请参见CREATE VIEW (Transact-SQL)。
创建视图(Transact-SQL)
You can modify the data of an underlying base table through a view, as long as the following conditions are true: Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table. The columns being modified in the view must directly reference the underlying data in the table columns. The columns cannot be derived in any other way, such as through the following: An aggregate function: AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR, and VARP. A computation. The column cannot be computed from an expression that uses other columns. Columns that are formed by using the set operators UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT amount to a computation and are also not updatable. The columns being modified are not affected by GROUP BY, HAVING, or DISTINCT clauses. TOP is not used anywhere in the select_statement of the view together with the WITH CHECK OPTION clause.
但是,坦率地说,您应该考虑在一个事务中使用两个不同的SQL语句,就像LBushkin的例子一样。
更新:我最初认为可以在可更新视图中更新多个表的断言是错误的。在SQL Server 2005 & 2012上,它将生成以下错误。为了反映这一点,我修改了我的回答。
编号4405,16层,状态1号线 视图或函数'updatable_view'是不可更新的,因为修改会影响多个基表。
对不起,afaik,你不能那样做。要更新两个不同表中的属性,需要执行两条单独的语句。但是它们可以是批处理的(在一次往返中发送给服务器的一组SQL)
对于基于Table2特定列的table1特定列的常规更新,这个查询工作完美:
UPDATE table 1
SET Col 2 = t2.Col2,
Col 3 = t2.Col3
FROM table1 t1
INNER JOIN table 2 t2 ON t1.Col1 = t2.col1