我在SQL Server 2008中有2个表(ChildrenRecordsTable和AllRecordsTable)
ChildrenRecordsTable (code varchar(20)) --
AllRecordsTable (code varchar(20), flag smallint)
ChildrenRecordsTable Data (Subset of the whole set) --
235,
2350 (Child of 235),
2351 (child of 235),
23500 (child of 2350),
23501 (child of 2350),
235011100 (child of 23501110),
100,
1001 (child of 100),
1002 (child of 100),
1003 (child of 100),
10010 (child of 1001),
10011 (child of 1001),
100111 (child of 10011),
100100 (child of 10010),
1001000 (child of 100100),
AllRecordsTable Data (Whole set) --
235,
2350 (Child of 235),
2351 (child of 235),
2352 (child of 235),
.....
23500 (child of 2350),
23501 (child of 2350),
....
235011100 (child of 23501110),
....
100,
1001 (child of 100),
1002 (child of 100),
....
10010 (child of 1001),
10011 (child of 1001),
100111 (child of 10011),
....
100100 (child of 10010),
1001000 (child of 100100),
....
我想编写一个查询来从ChildrenRecordsTable获取子代码 其中所有父母都在AllRecordsTable标志中> 3
我写了一个遍历子表的while循环,并检查所有父标志,其中flag> 3.查询运行速度很慢。是否有可能以不同的方式写出来?
下面的SQL逻辑: 1 - 检索ChildrenRecordsTable中与条件标记<匹配的每条记录的所有父项。 3 2 - 将记录数量与父母数量进行比较 3-如果不相等则删除子记录 4-对表ChildRecordsTable
中的每个子记录重复此过程 declare @TableID varchar(20)
declare @ChildrenFGCodes table (Id varchar(20) NOT NULL)
declare @ParentFGCs table (Id varchar(20) NOT NULL UNIQUE NONCLUSTERED)
declare @ParentCount smallint
declare @counter smallint
declare @numRecord smallint
insert into @ChildrenFGCodes SELECT FunctionalGroupCode from #ChildrenRecordsTable
while exists (select * from @ChildrenFGCodes)
begin
select top 1 @TableID = Id
from @ChildrenFGCodes
order by Id asc
SET @ParentCount = LEN(@TableID) - 4
SET @counter = 1
WHILE @counter <= @ParentCount
BEGIN
insert into @ParentFGCs values (LEFT(@TableID, LEN(@TableID) - @counter))
SET @counter = @counter + 1
END
SELECT @numRecord=COUNT(*)
from AllRecordsTable a, @ParentFGCs b
where ((a.code = b.Id) AND (a.flag < 3))
IF @numRecord <> @ParentCount
BEGIN
delete #ChildrenRecordsTable where Code = @TableID
END
delete FROM @ParentFGCs
delete @ChildrenFGCodes where Id = @TableID
end