program story

T-SQL : UPDATE 문에서 CASE를 사용하여 조건에 따라 특정 열 업데이트

inputbox 2020. 9. 5. 09:54
반응형

T-SQL : UPDATE 문에서 CASE를 사용하여 조건에 따라 특정 열 업데이트


이것이 가능한지 궁금합니다. 조건이 참이면 x 열을 업데이트하고, 그렇지 않으면 y 열이 업데이트됩니다.

UPDATE table SET
     (CASE (CONDITION) WHEN TRUE THEN columnx
                       ELSE columny
      END)
= 25

나는 모든 것을 검색하고 몇 가지 시도했지만 해결책을 찾을 수 없습니다. 가능하지 않다고 생각하지만 여기에서 물어보고 누군가가 전에 해본 적이 있는지 알아 보겠습니다. 미리 감사드립니다.


조건을 사용하여 쿼리 구조를 변경할 수 없으며 관련된 데이터 만 변경할 수 있습니다. 다음과 같이 할 수 있습니다.

update table set
    columnx = (case when condition then 25 else columnx end),
    columny = (case when condition then columny else 25 end)

이것은 의미 상 동일하지만 두 열이 항상 업데이트 된다는 점을 명심하십시오 . 이것은 아마 당신에게 어떤 문제가 발생하지 않습니다,하지만 당신은 높은 트랜잭션 볼륨이있는 경우, 다음이 동시성 문제가 발생할 수 있습니다.

구체적 으로 요구하는 작업을 수행하는 유일한 방법 은 동적 SQL을 사용하는 것입니다. 그러나 이것은 당신이 멀리 떨어져 있기를 권장합니다. 위의 솔루션은 거의 확실하게 당신이 추구하는 것에 충분할 것입니다.


UPDATE  table
SET     columnx = CASE WHEN condition THEN 25 ELSE columnx END,
        columny = CASE WHEN condition THEN columny ELSE 25 END

나는 이것이 매우 오래된 질문이라는 것을 알고 있지만 이것은 나를 위해 일했습니다.

UPDATE TABLE SET FIELD1 =
CASE 
WHEN FIELD1 = Condition1 THEN 'Result1'
WHEN FIELD1 = Condition2 THEN 'Result2'
WHEN FIELD1 = Condition3 THEN 'Result3'
END;

문안 인사


여기에 이미지 설명 입력

Case 문을 사용하여 8018070777이있는 경우 ContactNo를 8018070999로 변경하거나 업데이트하고 싶습니다.

update [Contacts] set contactNo=(case 
when contactNo=8018070777 then 8018070999
else
contactNo
end)

여기에 이미지 설명 입력


나는 이것이 매우 오래된 질문이며 문제가 해결 된 것으로 표시된다는 것을 알고 있습니다. 그러나 테이블에 업데이트 이벤트에 대한 데이터 로깅 트리거가있는 경우와 같은 경우에 문제가 발생합니다. 두 열 모두 업데이트를 받고 로그는 쓸모없는 항목을 만듭니다. 내가 한 방식

IF (CONDITION) IS TRUE
BEGIN
    UPDATE table SET columnx = 25
END
ELSE
BEGIN
    UPDATE table SET columny = 25
END

이제 이것은 위의 솔루션과 같이 테이블에 불필요한 쓰기가 없다는 또 다른 이점이 있습니다.


I believe that you can omit updating the "non-desired" columns by adjusting the other answers as follows:
update table set columnx = (case when condition1 then 25 end), columny = (case when condition2 then 25 end)

As I understand it, this will update only when the condition is met.

After reading all the comments, this is the most efficient:
Update table set ColumnX = 25 where Condition1 Update table set ColumnY = 25 where Condition1

Sample Table:
CREATE TABLE [dbo].[tblTest]( [ColX] [int] NULL, [ColY] [int] NULL, [ColConditional] [bit] NULL, [id] [int] IDENTITY(1,1) NOT NULL ) ON [PRIMARY]
Sample Data:
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0) Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0) Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1) Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1) Insert into tblTest (ColX, ColY, ColConditional) values (1, null, null) Insert into tblTest (ColX, ColY, ColConditional) values (2, null, null) Insert into tblTest (ColX, ColY, ColConditional) values (null, 1, null) Insert into tblTest (ColX, ColY, ColConditional) values (null, 2, null)

Now I assume you can write a conditional that handles nulls. For my example, I am assuming you have written such a conditional that evaluates to True, False or Null. If you need help with this, let me know and I will do my best.

Now running these two lines of code does infact change X to 25 if and only if ColConditional is True(1) and Y to 25 if and only if ColConditional is False(0)

Update tblTest set ColX = 25 where ColConditional = 1 Update tblTest set ColY = 25 where ColConditional = 0

P.S. The null case was never mentioned in the original question or any updates to the question, but as you can see, this very simple answer handles them anyway.

참고 URL : https://stackoverflow.com/questions/4830191/t-sql-using-a-case-in-an-update-statement-to-update-certain-columns-depending-o

반응형