program tip

SQL Server에서 JOIN을 사용하여 테이블을 업데이트 하시겠습니까?

radiobox 2020. 9. 29. 07:32
반응형

SQL Server에서 JOIN을 사용하여 테이블을 업데이트 하시겠습니까?


다른 테이블에 조인을 만드는 테이블의 열을 업데이트하고 싶습니다.

UPDATE table1 a 
INNER JOIN table2 b ON a.commonfield = b.[common field] 
SET a.CalculatedColumn= b.[Calculated Column]
WHERE 
    b.[common field]= a.commonfield
AND a.BatchNO = '110'

그러나 불평하고 있습니다.

메시지 170, 수준 15, 상태 1, 줄 2
줄 2 : 'a'근처에 잘못된 구문이 있습니다.

여기서 무엇이 잘못 되었습니까?


SQL Server의 독점 UPDATE FROM구문 이 완전히 다운 되지 않았습니다 . 또한에 가입 CommonField하고 나중에 필터링 해야하는 이유도 확실하지 않습니다 . 이 시도:

UPDATE t1
  SET t1.CalculatedColumn = t2.[Calculated Column]
  FROM dbo.Table1 AS t1
  INNER JOIN dbo.Table2 AS t2
  ON t1.CommonField = t2.[Common Field]
  WHERE t1.BatchNo = '110';

한 열의 값을 다른 열의 집계로 계속 설정하려고하는 것처럼 (중복 데이터 저장 방지 원칙을 위반하는) 정말 어리석은 작업을 수행하는 경우 CTE (공통 테이블 식)를 사용할 수 있습니다. 여기를 참조 하세요. 그리고 여기 자세한 내용은 :

;WITH t2 AS
(
  SELECT [key], CalculatedColumn = SUM(some_column)
    FROM dbo.table2
    GROUP BY [key]
)
UPDATE t1
  SET t1.CalculatedColumn = t2.CalculatedColumn
  FROM dbo.table1 AS t1
  INNER JOIN t2
  ON t1.[key] = t2.[key];

이것이 정말 어리석은 이유는 table2변경 사항이 있을 때마다이 전체 업데이트를 다시 실행해야하기 때문 입니다. A SUM는 런타임에 항상 계산할 수있는 것이므로 결과가 부실하다고 걱정할 필요가 없습니다.


다음과 같이 시도하십시오.

begin tran
    UPDATE a 
    SET a.CalculatedColumn= b.[Calculated Column]
    FROM table1 a INNER JOIN table2 b ON a.commonfield = b.[common field] 
    WHERE a.BatchNO = '110'
commit tran

Aaron이 위에 제시 한 답변은 완벽합니다.

UPDATE a
  SET a.CalculatedColumn = b.[Calculated Column]
  FROM Table1 AS a
  INNER JOIN Table2 AS b
  ON a.CommonField = b.[Common Field]
  WHERE a.BatchNo = '110';

테이블을 업데이트하는 동안 테이블 별칭을 사용하려고 할 때 SQL Server에서이 문제가 발생하는 이유를 추가하고 싶습니다. 아래 구문은 항상 오류를 발생시킵니다.

update tableName t 
set t.name = 'books new' 
where t.id = 1

단일 테이블을 업데이트하거나 조인을 사용하는 동안 업데이트하는 경우 case는 any 일 수 있습니다.

위의 쿼리는 PL / SQL에서는 잘 작동하지만 SQL Server에서는 작동하지 않습니다.

SQL Server에서 테이블 별칭을 사용하는 동안 테이블을 업데이트하는 올바른 방법은 다음과 같습니다.

update t 
set t.name = 'books new' 
from tableName t 
where t.id = 1

왜 오류가 여기에 왔는지 모두에게 도움이되기를 바랍니다.


MERGE table1 T
   USING table2 S
      ON T.CommonField = S."Common Field"
         AND T.BatchNo = '110'
WHEN MATCHED THEN
   UPDATE
      SET CalculatedColumn = S."Calculated Column";

I find it useful to turn an UPDATE into a SELECT to get the rows I want to update as a test before updating. If I can select the exact rows I want, I can update just those rows I want to update.

DECLARE @expense_report_id AS INT
SET @expense_report_id = 1027

--UPDATE expense_report_detail_distribution
--SET service_bill_id = 9

SELECT *
FROM expense_report_detail_distribution erdd
INNER JOIN expense_report_detail erd
INNER JOIN expense_report er 
    ON er.expense_report_id = erd.expense_report_id 
    ON erdd.expense_report_detail_id = erd.expense_report_detail_id
WHERE er.expense_report_id = @expense_report_id

Seems like SQL Server 2012 can handle the old update syntax of Teradata too:

UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a, table2 b 
WHERE 
    b.[common field]= a.commonfield
AND a.BatchNO = '110'

If I remember correctly, 2008R2 was giving error when I tried similar query.


    UPDATE mytable
         SET myfield = CASE other_field
             WHEN 1 THEN 'value'
             WHEN 2 THEN 'value'
             WHEN 3 THEN 'value'
         END
    From mytable
    Join otherTable on otherTable.id = mytable.id
    Where othertable.somecolumn = '1234'

More alternatives here: http://www.karlrixon.co.uk/writing/update-multiple-rows-with-different-values-and-a-single-sql-query/


Another approach would be to use MERGE

  ;WITH cteTable1(CalculatedColumn, CommonField)
  AS
  (
    select CalculatedColumn, CommonField from Table1 Where BatchNo = '110'
  )
  MERGE cteTable1 AS target
    USING (select "Calculated Column", "Common Field" FROM dbo.Table2) AS source ("Calculated Column", "Common Field")
    ON (target.CommonField = source."Common Field")
    WHEN MATCHED THEN 
        UPDATE SET target.CalculatedColumn = source."Calculated Column";

-Merge is part of the SQL Standard

-Also I'm pretty sure inner join updates are non deterministic.. Similar question here where the answer talks about that http://ask.sqlservercentral.com/questions/19089/updating-two-tables-using-single-query.html


I had the same issue.. and you don't need to add a physical column.. cuz now you will have to maintain it.. what you can do is add a generic column in the select query:

EX:

select tb1.col1, tb1.col2, tb1.col3 ,
( 
select 'Match' from table2 as tbl2
where tbl1.col1 = tbl2.col1 and tab1.col2 = tbl2.col2
)  
from myTable as tbl1

Try:

UPDATE table1
SET CalculatedColumn = ( SELECT [Calculated Column] 
                         FROM table2 
                         WHERE table1.commonfield = [common field])
WHERE  BatchNO = '110'

참고URL : https://stackoverflow.com/questions/1604091/update-a-table-using-join-in-sql-server

반응형