I want to write a dynamic script that removes duplicates. I want to try and avoid a CURSOR so I've been looking into writing strings instead that will have table in one column and corresponding table attributes in another. I have also tried dynamic SQL using WITH. But this is what I have so far. This I intend to use as parameters in dynamic SQL later on
STUFF example. However this results in repeating the same column names for every row:
select name as table_name,
stuff(( select ', ' +char(10)+ ac.[name] FROM DW.sys.columns ac
inner join DW.sys.tables t on ac.object_id=t.object_id
where ac.name not in ('ModifiedOn','ValidFrom','ValidTo')
FOR XML PATH('')
), 1, 1, '')
from sys.tables
What I want is this output:
TableName || ColumnName
table1 || aa,ab,ac
table2 || ba,bb,bc
table3 || ca,cb,cc
My idea is to use this to this effect or similair:
'WITH DELETEDUPLICATE AS (
SELECT '+@ColumnName+',
ROW_NUMBER() OVER(PARTITION BY '+@ColumnName+' ORDER BY '+@ColumnName+') AS Duplicate_Row_Count
FROM '+@TableName+'
)
DELETE
FROM DELETEDUPLICATE
WHERE Duplicate_Row_Count > 1
Any ideas appreciated!
UPDATE: With satishcse's suggestion i get the table I wanted. I had problem with getting multiple rows in the dynamic WITH step so I just removed that part as a varaible (removed away 'SET @WITH =' ). But how to execute every row? what i get now is:
WITH DELETEDUPLICATE AS(....
For every table per row