查询重复记录

博客给出了一个查询重复记录的通用存储过程代码。该存储过程可查询表中除主键外重复的记录,若表无主键会临时添加。还给出了调用示例,包括创建测试数据、调用存储过程及删除测试环境,最后展示了测试结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_qry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_qry]
GO

/*--查询重复记录的通用存储过程

可以查询出表中那些数据是重复的,这里的重复,是指除主键外重复的记录
如果表中有主键,请指定主键.
如果表中有标识字段,而且标识字段无重复,请在调用时,将主键指定为标识字段
如果标识字段重复,不能用此存储过程

-- 2004.4--*/

create proc p_qry
@tbname sysname, --要查询的表名
@keyfdname sysname=null --表中的主键,如果未指定,则表中无主键
as
declare @nokey bit,@fd varchar(8000),@tj varchar(8000)
set nocount on
if isnull(@keyfdname,'')=''
begin
select @keyfdname=cast(newid() as char(36)),@nokey=1
exec('alter table ['+@tbname+'] add ['+@keyfdname+'] decimal(38,0) identity(1,1)')
end
select @fd='',@tj=''
select @fd=@fd+',['+name+']'
,@tj=@tj+'['+name+']=a.['+name+'] and '
from syscolumns
where object_name(id)=@tbname and name<>@keyfdname
set @fd=substring(@fd,2,8000)
exec('select '+@fd+' from ['+@tbname+'] a
where exists(select 1 from ['+@tbname
+'] where '+@tj+'['+@keyfdname+']<>a.['+@keyfdname+'])')
if @nokey=1
exec('alter table ['+@tbname+'] drop column ['+@keyfdname+']')
set nocount off
go

--调用示例
--创建测试数据
create table 表(f1 int,f2 int,f3 int,f4 int,f5 int)
insert into 表
select 1,1,1,1,1
union all select 2,1,1,1,1
union all select 3,2,1,23,1
union all select 4,2,3,1,3
union all select 5,1,1,1,1
go

--调用通用存储过程实现楼主的查询
exec p_qry '表','f1'

--删除测试环境
drop table 表


/*--测试结果

f2 f3 f4 f5
----------- ----------- ----------- -----------
1 1 1 1
1 1 1 1
1 1 1 1
--*/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值