SQL query to find duplicate rows, in any table

后端 未结 4 1888
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 18:12

I\'m looking for a schema-independent query. That is, if I have a users table or a purchases table, the query should be equally capable of catchin

4条回答
  •  花落未央
    2021-01-18 18:50

    I recently was looking into the same issue and noticed this question. I managed to solve it using a stored procedure with some dynamic SQL. This way you only need to specify the table name. And it will get all the other relevant data from sys tables.

    /*
    This SP returns all duplicate rows (1 line for each duplicate) for any given table.
    
    to use the SP:
    exec [database].[dbo].[sp_duplicates] 
        @table = '[database].[schema].[table]'  
    
    */
    create proc dbo.sp_duplicates @table nvarchar(50) as
    
    declare @query nvarchar(max)
    declare @groupby nvarchar(max)
    
    set @groupby =  stuff((select ',' + [name]
                    FROM sys.columns
                    WHERE object_id = OBJECT_ID(@table)
                    FOR xml path('')), 1, 1, '')
    
    set @query = 'select *, count(*)
                    from '+@table+'
                    group by '+@groupby+'
                    having count(*) > 1'
    
    exec (@query)
    

提交回复
热议问题