Update

如果其中一列匹配,如何用另一列的值更新一列

  • November 1, 2018

我發現了很多類似的問題,但不完全是我需要的。我想創建一個 SQL 命令來查找所有重複的電子郵件行,並用“不要發送電子郵件”來更新它們的註釋,如果它寫在其中一個的註釋中。

在下面的範例中,我想在註釋中使用“請勿發送電子郵件”來更新第 2,4 和 6 行。

ID | email | note
--------------------
1 | A | do not email
2 | B |
3 | C |
4 | A |
5 | D |
6 | A |
7 | B | do not email

有沒有人有任何提示?

這將更新目標表中與同一表中已標記為“不發送電子郵件”的電子郵件地址匹配的所有行

update a
  set a.note = 'do not email'
 from tbl as a
 join (select distinct email
         from tbl 
        where note = 'do not email'
      ) as b 
   on a.email = b.email
where a.note <> 'do not email' 
   or a.note is null;

我認為這將解決您的問題。

DECLARE @table TABLE
(
   Id INT IDENTITY(1,1)
   , Email VARCHAR(500)
   , Note VARCHAR(200) NULL
);

INSERT INTO @table
       (Email, Note)
VALUES  ('A', 'do not email'), ('B', NULL), ('C', NULL), ('A', NULL), ('D',NULL), ('A',NULL), ('B','do not email');

SELECT * FROM @table;

-- Actual Data
--------------------
-- Id | Email | Note
--------------------
--  1       A   do not email
--  2       B   NULL
--  3       C   NULL
--  4       A   NULL
--  5       D   NULL
--  6       A   NULL
--  7       B   do not email

MERGE INTO @table AS Target
USING (SELECT DISTINCT      
   Email ,
   Note 
FROM @table 
WHERE Note = 'do not email'
) AS Source 
   ON Target.[Email] = Source.[Email]          
WHEN MATCHED THEN
UPDATE  
SET 
   Target.[Note] = Source.[Note];


SELECT * FROM @table        

-- After Update
--------------------
-- Id | Email | Note
--------------------
--  1       A   do not email
--  2       B   do not email
--  3       C   NULL
--  4       A   do not email
--  5       D   NULL
--  6       A   do not email
--  7       B   do not email

引用自:https://dba.stackexchange.com/questions/123035