I have the following stored procedure:
x
ALTER PROCEDURE [dbo].[sp_ImportSurveys]
@surveys udtSurveys readonly
AS
BEGIN
INSERT INTO Surveys
(Funzione,
Id_Intervento,
Titolo_Intervento,
Titolo_Rilievo,
ImportDownloadDate,
Oggetto_Valutato,
Id_Oggetto_Valutato,
Id,
Id_Banca,
Cod_ABI,
Legal_Entity,
Title,
Descrizione_Rilievo,
Azione_di_Mitigazione,
Owner_Azione_di_Mitigazione,
Utente_Censimento,
Severita_Rilievo,
Data_Scadenza,
Anno,
StatusId)
SELECT Funzione,
Id_Intervento,
Titolo_Intervento,
Titolo_Rilievo,
DataDownload,
Oggetto_Valutato,
Id_Oggetto_Valutato,
CONVERT(nvarchar(450), Id) + Funzione,
Id_Banca,
Cod_ABI,
Legal_Entity,
Titolo_Rilievo,
Descrizione_Rilievo,
Azione_di_Mitigazione,
Owner_Azione_di_Mitigazione,
Utente_Censimento,
Severita_Rilievo,
Data_Scadenza,
Anno,
2
FROM @surveys sur
WHERE NOT EXISTS (Select * from dbo.Surveys WHERE dbo.Surveys.Id = (CONVERT(nvarchar(450), sur.Id) + Funzione))
END
udtSurveys is used like params by stored procedure.
Before inserting records into table surveys
I need to remove all duplicate column with Id from udtSurveys.
Would you please show me an example of how use group by
or another way to remove duplicated records before inserting to table?
Advertisement
Answer
You can simply use a CTE to filter all the duplicate rows from @surveys parameter.
I’ve updated your query with a cte_tbl
by assuming you want to keep the original rows and remove its duplicates.
ALTER PROCEDURE [dbo].[sp_ImportSurveys]
@surveys udtSurveys readonly
AS
BEGIN
;WITH cte_tbl AS (
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Funzione)
FROM @surveys sur
WHERE NOT EXISTS ( SELECT 1
FROM dbo.Surveys
WHERE dbo.Surveys.Id = (CONVERT(nvarchar(450), sur.Id) + Funzione))
)
INSERT INTO Surveys
(Funzione,
Id_Intervento,
Titolo_Intervento,
Titolo_Rilievo,
ImportDownloadDate,
Oggetto_Valutato,
Id_Oggetto_Valutato,
Id,
Id_Banca,
Cod_ABI,
Legal_Entity,
Title,
Descrizione_Rilievo,
Azione_di_Mitigazione,
Owner_Azione_di_Mitigazione,
Utente_Censimento,
Severita_Rilievo,
Data_Scadenza,
Anno,
StatusId)
SELECT Funzione,
Id_Intervento,
Titolo_Intervento,
Titolo_Rilievo,
DataDownload,
Oggetto_Valutato,
Id_Oggetto_Valutato,
CONVERT(nvarchar(450), Id) + Funzione,
Id_Banca,
Cod_ABI,
Legal_Entity,
Titolo_Rilievo,
Descrizione_Rilievo,
Azione_di_Mitigazione,
Owner_Azione_di_Mitigazione,
Utente_Censimento,
Severita_Rilievo,
Data_Scadenza,
Anno,
2
FROM cte_tbl
WHERE RN = 1 -- will only fetch the distinct id-rows
END