Programing

SQL Server 2005의 한 명령문에서 두 개의 테이블을 업데이트하는 방법은 무엇입니까?

lottogame 2020. 5. 18. 08:01
반응형

SQL Server 2005의 한 명령문에서 두 개의 테이블을 업데이트하는 방법은 무엇입니까?


한 번에 두 개의 테이블을 업데이트하고 싶습니다. 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'

한 명령문에서 여러 테이블을 업데이트 할 수 없지만 트랜잭션을 사용하여 두 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;

한 번에 두 개의 테이블을 업데이트 할 수 없지만 OUTPUT INTO를 사용하여 업데이트를 삽입에 연결할 수 있으며이 출력을 두 번째 업데이트의 조인으로 사용할 수 있습니다.

DECLARE @ids TABLE (id int);
BEGIN TRANSACTION

UPDATE Table1 
SET Table1.LastName = 'DR. XXXXXX'  
OUTPUT INSERTED.id INTO @ids
WHERE T1.field = '010008';

UPDATE Table2 
SET Table2.WAprrs = 'start,stop' 
FROM Table2 
JOIN @ids i on i.id = Table2.id;

COMMIT;

예제에서 WHERE 조건을 id보다 일부 필드로 변경했습니다. id가이 멋진 OUTPUT을 필요로하지 않으면 동일한 id = '010008'에 대한 두 번째 테이블을 업데이트 할 수 있습니다.


죄송합니다, 당신은 그렇게 할 수 없습니다. 두 개의 다른 테이블에서 속성을 업데이트하려면 두 개의 별도 명령문을 실행해야합니다. 그러나 배치에있을 수 있습니다 (한 번의 왕복으로 서버에 전송 된 SQL 세트)


그것에 대한 짧은 대답은 아니오입니다. from업데이트 문의 절에 여러 테이블을 입력 할 수 있지만 update키워드 다음에 단일 테이블 만 지정할 수 있습니다 . "업데이트 가능한"보기 (단순히 특정 제한 사항을 따르는보기)를 작성하더라도 이와 같은 업데이트는 실패합니다. 다음은 MSDN 설명서의 관련 클립입니다 (강조 표시).

업데이트 (Transact-SQL)

The view referenced by table_or_view_name must be updatable and reference exactly one base table in the FROM clause of the view. For more information about updatable views, see CREATE VIEW (Transact-SQL).

CREATE VIEW (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.

In all honesty, though, you should consider using two different SQL statements within a transaction as per LBushkin's example.

UPDATE: My original assertion that you could update multiple tables in an updatable view was wrong. On SQL Server 2005 & 2012, it will generate the following error. I have corrected my answer to reflect this.

Msg 4405, Level 16, State 1, Line 1

View or function 'updatable_view' is not updatable because the modification affects multiple base tables.


You should place two update statements inside a transaction


This works for MySQL and is really just an implicit transaction but it should go something like this:

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'

if you are doing updates to multi tables that require multi statements… which is likely possible if you update one, then another based on other conditions… you should use a transaction. 


You can write update statement for one table and then a trigger on first table update, which update second table


It is as simple as this query shown below.

UPDATE 
  Table1 T1 join Table2 T2 on T1.id = T2.id
SET 
  T1.LastName='DR. XXXXXX', 
  T2.WAprrs='start,stop'
WHERE 
  T1.id = '010008'

참고URL : https://stackoverflow.com/questions/2044467/how-to-update-two-tables-in-one-statement-in-sql-server-2005

반응형