如何优化这个SQL 难度挺大的阿!1
运行下面的存储过程 需要两分多钟 严重超时(系统2000 SERVER,SQLSERVER2000)请高人看看如何修改,主要是哪个函数如何修该 才能搞定
CREATE PROCEDURE WHM_ProductStat
@starttime datetime,
@endtime datetime,
@CategoryId int
AS
select
O.ModelName,
pa.attributename,
O.Spec,
a.CategoryName,
d.CategoryName ParentCategory,
sum(O.Quantity) TotalQuantity,
sum(O.UnitCost*O.Quantity) TotalMoney
from
CMRC_Categories a,
CMRC_Categories d,
ProductStatfun(@CategoryId) b ,//问题主要出现在这个函数,他的作用是选出@CategoryId和它下一级产品类别的ID,具体见下面的代码
CMRC_Products P,
CMRC_ProductAttribute pa,
WHM_OutBill OB,//这张有30万条
WHM_OutBillDetails O//这张表有90万记录
where
a.CategoryId=b.id//如果我把这里把b.id改成一个具体的ID 则时间为11秒
and p.Attributeid=pa.attributeid
and a.ParentCategoryid=d.Categoryid
and O.BillCode=OB.BILLCODE
AND O.PRODUCTID=P.PRODUCTID
AND P.CATEGORYID=a.CATEGORYID
and ob.OutMode='1'
and ob.PostTag='1'
and OB.POSTDATE>=@starttime
and OB.POSTDATE<=@endtime
group by
pa.attributename,
O.ModelName,
a.CategoryName,
d.CategoryName,
O.Spec
函数
CREATE FUNCTION ProductStatfun
(@id int)
RETURNS @re table(id int,level int)
AS
BEGIN
declare @l int
set @l=0
insert @re select @id,@l
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.Categoryid,@l
from CMRC_Categories a,@re b
where a.ParentCategoryID=b.id and b.level=@l-1
end
return
end
问题点数:20、回复次数:6Top
1 楼freedom1980(力促)回复于 2005-08-01 09:53:48 得分 0
该建的索引已近建好了 但是还是没什么效果Top
2 楼enhydraboy(乱舞的浮尘)回复于 2005-08-01 16:25:55 得分 0
using temp table to split your join operation. First insert the result of two huge tables joining into a temp table.
I think the execute plan base on cost opertimizer is not good at multi-table join.
Top
3 楼freedom1980(力促)回复于 2005-08-01 16:54:38 得分 0
sorry i'm not sure waht your means, can you show me a simple code please?Top
4 楼btut2004(养鱼炒股)回复于 2005-08-06 15:57:40 得分 0
俺只能学西了Top
5 楼soaringsouth(栈桥捉鳖)回复于 2005-08-06 16:07:28 得分 0
你把业务流程描述一下吧
这么多表,感觉你的语句好乱
建议你用left outer join
Top
6 楼mpshun(苦行僧)回复于 2005-08-07 19:33:07 得分 0
好像有点晕,大概是看帖子看的。Top




