检索与sql server中的条件匹配的子代码
我在SQL server 2008中有两个表(ChildrenRecordsTable和AllRecordsTable)检索与sql server中的条件匹配的子代码,sql,sql-server,Sql,Sql Server,我在SQL server 2008中有两个表(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
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获取children代码
其中AllRecordsTable标志中的所有父项>3
我编写了一个while循环,它遍历children表并检查flag>3的所有父记录。查询运行得非常慢。有可能写得不同吗
SQL逻辑如下所示:
1-检索ChildrenRecordsTable中符合条件标志<3的每条记录的所有父项
2-将记录数的计数与父记录数的计数进行比较
3-如果它们不相等,则删除子记录
4-对表ChildrenRecordsTable中的每个子记录重复此过程
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
declare@TableID varchar(20)
声明@ChildrenFGCodes表(Id varchar(20)不为空)
声明@ParentFGCs表(Id varchar(20)非NULL唯一非聚集)
声明@ParentCount smallint
声明@counter smallint
声明@numRecord smallint
在@ChildrenFGCodes中插入从#ChildrenRecordsTable中选择FunctionalGroupCode
存在时(从@ChildrenFGCodes中选择*)
开始
选择top 1@TableID=Id
来自@ChildrenFGCodes
按Id订购asc
设置@ParentCount=LEN(@TableID)-4
设置@counter=1
当@counter听说CTE时?如果您发布原始数据和表结构,也很有用PostOk中包含的原始数据和表结构。。。goodluck@ibrahim请为您的示例数据发布CREATE
和INSERT
脚本。