查询重复记录

None.gif if exists ( select * from dbo.sysobjects where id = object_id(N ' [dbo].[p_qry] ') and OBJECTPROPERTY(id, N ' IsProcedure ') = 1)
None.gif drop procedure [ dbo ]. [ p_qry ]
None.gif GO
None.gif
ExpandedBlockStart.gif ContractedBlock.gif /**/ /*--查询重复记录的通用存储过程
InBlock.gif
InBlock.gif 可以查询出表中那些数据是重复的,这里的重复,是指除主键外重复的记录
InBlock.gif 如果表中有主键,请指定主键.
InBlock.gif 如果表中有标识字段,而且标识字段无重复,请在调用时,将主键指定为标识字段
InBlock.gif 如果标识字段重复,不能用此存储过程
InBlock.gif
ExpandedBlockEnd.gif-- 2004.4--
*/
None.gif
None.gif create proc p_qry
None.gif @tbname sysname, -- 要查询的表名
None.gif
@keyfdname sysname = null -- 表中的主键,如果未指定,则表中无主键
None.gif
as
None.gif declare @nokey bit, @fd varchar( 8000), @tj varchar( 8000)
None.gif set nocount on
None.gif if isnull( @keyfdname, '') = ''
None.gif begin
None.gif select @keyfdname = cast( newid() as char( 36)), @nokey = 1
None.gif exec( ' alter table [ ' + @tbname + ' ] add [ ' + @keyfdname + ' ] decimal(38,0) identity(1,1) ')
None.gif end
None.gif select @fd = '', @tj = ''
None.gif select @fd = @fd + ' ,[ ' +name + ' ] '
None.gif , @tj = @tj + ' [ ' +name + ' ]=a.[ ' +name + ' ] and '
None.gif from syscolumns
None.gif where object_name(id) = @tbname and name <> @keyfdname
None.gif set @fd = substring( @fd, 2, 8000)
None.gif exec( ' select ' + @fd + ' from [ ' + @tbname + ' ] a
None.gif where exists(select 1 from [
' + @tbname
None.gif + ' ] where ' + @tj + ' [ ' + @keyfdname + ' ]<>a.[ ' + @keyfdname + ' ]) ')
None.gif if @nokey = 1
None.gif exec( ' alter table [ ' + @tbname + ' ] drop column [ ' + @keyfdname + ' ] ')
None.gif set nocount off
None.gif go
None.gif
None.gif -- 调用示例
None.gif--
创建测试数据
None.gif
create table 表(f1 int,f2 int,f3 int,f4 int,f5 int)
None.gif insert into
None.gif select 1, 1, 1, 1, 1
None.gif union all select 2, 1, 1, 1, 1
None.gif union all select 3, 2, 1, 23, 1
None.gif union all select 4, 2, 3, 1, 3
None.gif union all select 5, 1, 1, 1, 1
None.gif go
None.gif
None.gif -- 调用通用存储过程实现楼主的查询
None.gif
exec p_qry ' ', ' f1 '
None.gif
None.gif -- 删除测试环境
None.gif
drop table
None.gif
None.gif
ExpandedBlockStart.gif ContractedBlock.gif /**/ /*--测试结果
InBlock.gif
InBlock.giff2 f3 f4 f5
InBlock.gif----------- ----------- ----------- -----------
InBlock.gif1 1 1 1
InBlock.gif1 1 1 1
InBlock.gif1 1 1 1
ExpandedBlockEnd.gif--
*/
None.gif



本文转自高海东博客园博客,原文链接http://www.cnblogs.com/ghd258/archive/2005/10/24/260769.html,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值