日期:2014-05-17  浏览次数:20554 次

问1个BOM(树形结构的问题)
pid cid
a          a1        
a          a2        
a          a3        
b          b1        
b          b2        
b          b3        
c          a1        
c          a2        
c          a3        

-----------------------
如上,pid (a,c) 这2个是重复的!

假设BOM已经有 n 万行,

问题1.怎样快速找出重复数据.
问题2.下次新增加的时候,如插入(a1,a2,a3)这样的数据,组成新BOM时候,系统能提示已经重复.

注: 因为BOM数据量较大,麻烦给1个速度快1些的方法,另外BOM是树形结构的,以上只列了1层.
------解决方案--------------------

----------------------------
-- Author  :TravyLee(物是人非事事休,欲语泪先流!)
-- Date    :2012-11-27 14:26:20
-- Version:

--      Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) 

-- Feb 10 2012 19:13:17 

-- Copyright (c) Microsoft Corporation

-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)

--
----------------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go 
create table [test]([pid] varchar(1),[cid] varchar(2))
insert [test]
select 'a','a1' union all
select 'a','a2' union all
select 'a','a3' union all
select 'b','b1' union all
select 'b','b2' union all
select 'b','b3' union all
select 'c','a1' union all
select 'c','a2' union all
select 'c','a3'
go

--问题二:

--写个存储过程:
create proc up_test
(
@pid varchar(2),
@cid varchar(2)
)
as
if exists(select 1 from test where pid<>@pid and cid=@cid)
begin
print '插入数据重复'
end
else
begin
insert test
select @pid,@cid
end
go


exec up_test 'd','a1'

/*
插入数据重复

*/

------解决方案--------------------
USE test
GO

-->生成表t1
if object_id('t1') is not null 
drop table t1
Go
Create table t1([pid] nvarchar(2),[cid] nvarchar(2))
Insert into t1
Select N'a',N'a1'
Union all Select N'a',N'a2'
Union all Select N'a',N'a3'
Union all Select N'b',N'b1'
Union all Select N'b',N'b2'
Union all Select N'b',N'b3'
--Union all Select N'a',N'c' -- 特殊情況