Question

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) 
Was it helpful?

Solution

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.

OTHER TIPS

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) 

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top