我有一个存储过程,可以检查重复项上的任何表。它返回一个结果集,其中包含给定表中的所有重复行。
我现在想要的是计算重复数量,得到表格名称& rundate查询并将其插入表中。
我目前面临的问题是SP返回一个具有可变列数的集合。因此,我无法在预定义的临时表中插入SP的结果。
有没有人知道(聪明的)方法呢?
预期结果
| TABLENAME |日期| sumDupRows |
SP我正在使用:
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(*) as duplicates
from '+@table+'
group by '+@groupby+'
having count(*) > 1'
exec (@query)
GO
答案 0 :(得分:1)
您已找到重复记录。使用其他select
汇总它们。
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 ' +
@table + ' AS tableName,
GETDATE() AS MaxDate,
SUM(duplicates) AS TotalDuplicates
FROM
(
select count(*) as duplicates
from '+@table+'
group by '+@groupby+'
having count(*) > 1
) A'
exec (@query)
GO