不存在其他行时更新行

时间:2019-09-10 10:20:51

标签: sql sql-server

显示的代码不起作用,但是显示了我要执行的操作。 我想将存在的行的ID更改为不存在的ID。

(
    SELECT
    [ClientID],
    [TypeID],
    [Text]
    FROM [ClientTable]
    WHERE
        [TypeID] = 18
    AND [Text] <> ''
) toMove

IF NOT EXISTS
(
    SELECT *
    FROM [ClientTable]
    WHERE
        [ClientID] = toMove.[ClientID]
    AND [TypeID] = 17
)
BEGIN
    UPDATE [ClientTable]
    SET [TypeID] = 17
    WHERE
        [ClientID] = toMove.[ClientID]
    AND [TypeID] = toMove.[TypeID]
END

如果每个ClientID都没有这样的行,我希望将TypeID = 18的任何行更改为TypeID = 17。我期望执行后会有许多更改的行。 使用SQL Server

编辑: 样本数据和预期结果

Original Data
ClientID    TypeID  Text
123         18      some text
123         17  
456         18      more text
789         18  

Expected Output
ClientID    TypeID  Text
123         18      some text
123         17  
456         17      more text
789         18  

3 个答案:

答案 0 :(得分:1)

首先根据下面的选择脚本获得计数,然后在下面的更新脚本中应用。两条记录计数应匹配。 (例如,更新语句中的选择脚本中有10个计数)

SELECT COUNT(1) TotalRecordsFound
FROM [ClientTable] AS C1
WHERE C1.[TypeID] = 18
AND C1.[Text] <> ''
AND NOT EXISTS
(
SELECT 1 FROM ClientTable AS C2
WHERE C2.ClientID = C1.ClientID
AND C2.TypeID = 17
)

您正尝试将TypeID更新为17,将TypeID更新为18,并且“文本”列不为空,其中该cleintId的TypeID不是17。 只需使用以下更新脚本即可。

UPDATE C1
SET C1.[TypeID] = 17
-- You can add below two columns while updating records
--,UpdatedBy = 100
--,UpdatedDateTime = GETDATE()
FROM [ClientTable] AS C1
WHERE C1.[TypeID] = 18
AND C1.[Text] <> ''
AND NOT EXISTS
(
SELECT 1 FROM ClientTable AS C2
WHERE C2.ClientID = C1.ClientID
AND C2.TypeID = 17
)

答案 1 :(得分:0)

您可以将UPDATE语句与SELECT合并的EXISTS结合起来:

UPDATE [ClientTable] c
   SET [TypeID] = 17
 WHERE EXISTS 
       (
        SELECT [ClientID]
          FROM [ClientTable]
         WHERE [TypeID] = 18
           AND [Text] <> ''
           AND [ClientID] = c.[ClientID]
       )

答案 2 :(得分:0)

您可以通过多种方式执行此操作。一种方法使用窗口函数:

WITH toupdate AS (
      SELECT ct.*,
             SUM(CASE WHEN TypeId = 17 THEN 1 ELSE 0 END) OVER (PARTITION BY ClientId) as num_17s             
      FROM ClientTable t
      WHERE Text <> ''
     )
UPDATE toupdate
    SET TypeId = 17
    WHERE TypeId = 18 AND Text <> '' AND num_17s = 0;