简体   繁体   中英

updating a SQL table based on results from a Sub-Select

When I run this SQL code I get the following error message:

Msg 116, Level 16, State 1, Line 17
Only one expression can be specified in the select list when the subquery 
is not introduced with EXISTS.

What I want is whenever anything is returned from my update query which has the same AgreementNo, ElementStartDate and DateSeqNo , it updates one of those duplicate records with an ElementStartDate of + 1 which will remove the duplicate.

Update [WASP_Mart_EmbassyActuarial].[dbo].[tblARM_OmegaSource]  
SET ElementStartDate = ElementStartDate + 1  
WHERE AgreementNo IN   
    (SELECT
        count(*) as [Count],
        [AgreementNo],
        [ElementStartDate],
        [DateSeqNo],
        getdate() as Today  
     FROM [WASP_Mart_EmbassyActuarial].[dbo].[tblARM_OmegaSource]   
     GROUP BY  
         [AgreementNo],
         [ElementStartDate],
         [DateSeqNo]  
     HAVING COUNT(*) = 2) 

The Sub query returning more than one column. You can't compare More than one column using in Operator.

Try below query:

Update [WASP_Mart_EmbassyActuarial].[dbo].[tblARM_OmegaSource]  
SET ElementStartDate = ElementStartDate + 1  
WHERE AgreementNo IN   
 ( SELECT [AgreementNo] 
   FROM [WASP_Mart_EmbassyActuarial].[dbo].[tblARM_OmegaSource]   
   GROUP BY  [AgreementNo] -- OR [AgreementNo],[ElementStartDate],[DateSeqNo]
   HAVING COUNT(*) = 2) 

Assign row numbers in partitions of AgreementNo, ElementStartDate, DateSeqNo and update those rows where the row number is greater than 1:

WITH ranked AS (
  SELECT
    ElementStartDate,
    rn = ROW_NUMBER() OVER (PARTITION BY AgreementNo, ElementStartDate, DateSeqNo
                                ORDER BY (SELECT 1))  -- actual order probably
                                                      -- doesn't matter here
  FROM WASP_Mart_EmbassyActuarial.dbo.tblARM_OmegaSource
)
UPDATE ranked
SET ElementStartDate = ElementStartDate + rn - 1
WHERE rn > 1
;

This method can handle cases with more than two duplicates in a group, although, of course, with very many duplicates it may start producing new ones instead.

Maybe try this:

Update [WASP_Mart_EmbassyActuarial].[dbo].[tblARM_OmegaSource]  
SET ElementStartDate = ElementStartDate + 1  
WHERE AgreementNo IN   
 (SELECT 
      AgreementNo 
  FROM [WASP_Mart_EmbassyActuarial].[dbo].[tblARM_OmegaSource]   
  GROUP BY 
      [AgreementNo],
      [ElementStartDate],
      [DateSeqNo]
  HAVING COUNT(*) = 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM