我想优化存储过程。请提供如何改进的建议。
有4个左连接,需要花费太多时间。
t1
表中有超过1000万行。我想按月分组并过滤其他关系。
SET NOCOUNT ON;
declare @v1 datetime
declare @v2 datetime
declare @v3 int = null
declare @v4 varchar(max)
declare @v5 varchar(max)
declare @v6 varchar(max)
declare @v7 varchar(max)
declare @v8 varchar(max)
declare @v9 int
set @v1 = @iv1
set @v2 = @iv2
set @v3 = @iv3
set @v4 = @iv4
set @v5 = @iv5
set @v6 = @iv6
set @v7 = @iv7
set @v8 = @iv8
select
Month(a.c1) as 'Month',
sum(a.c2) as 'PaidAmount',
count(a.c3)*2.5 as 'TransactionFee'
from
t1 a
left join
t2 b on a.c1 = b.c1
left join
t3 f on b.c2 = f.c2
left join
t4 c on a.c3 = c.c3
left join
t5 g on a.c4 = g.c4
where
a.c4 >= @v1
and a.c5 <= @v2
and a.c6 > 0
and a.c7 is not null
and a.c8 is not null
and a.c9 is not null
and (@v3 is null or b.c10 = @v3)
and (@v4 is null or CHARINDEX(','+CAST(c.c7 as varchar(max))+',',@v4) > 0)
and (@v5 is null or CHARINDEX(','+CAST(a.c8 as varchar(max))+',',@v5) > 0)
and (@v6 is null or CHARINDEX(','+CAST(a.c9 as varchar(max))+',',@v6) > 0)
and (@v7 is null or CHARINDEX(','+CAST(c.c11 as varchar(max))+',',@v7) > 0)
and (@v8 is null or CHARINDEX(','+CAST(g.c12 as varchar(max))+',',@v8) > 0)
group by
Month(a.c1)
答案 0 :(得分:0)
declare @v1 datetime
declare @v2 datetime
declare @v3 int = null
declare @v4 varchar(max)
declare @v5 varchar(max)
declare @v6 varchar(max)
declare @v7 varchar(max)
declare @v8 varchar(max)
declare @v9 int
set @v1 = @iv1
set @v2 = @iv2
set @v3 = @iv3
set @v4 = @iv4
set @v5 = @iv5
set @v6 = @iv6
set @v7 = @iv7
set @v8 = @iv8
select Month(a.c1) as 'Month',
sum(a.c2) as 'PaidAmount',
count(a.c3)*2.5 as 'TransactionFee'
from
t1 a WITH(NOLOCK)
FULL join t2 b WITH(NOLOCK) on a.c1 = b.c1
INNER join t4 c WITH(NOLOCK) on a.c3 = c.c3
INNER join t5 g WITH(NOLOCK) on a.c4 = g.c4
INNER join t3 f WITH(NOLOCK) on b.c2 = f.c2
where a.c4 >= @v1
and a.c5 <= @v2
and a.c6 > 0
and a.c7 is not null
and a.c8 is not null
and a.c9 is not null
and (@v3 is null or b.c10 = @v3)
and (@v4 is null or CHARINDEX(','+CAST(c.c7 as varchar(max))+',',@v4) > 0)
and (@v5 is null or CHARINDEX(','+CAST(a.c8 as varchar(max))+',',@v5) > 0)
and (@v6 is null or CHARINDEX(','+CAST(a.c9 as varchar(max))+',',@v6) > 0)
and (@v7 is null or CHARINDEX(','+CAST(c.c11 as varchar(max))+',',@v7) > 0)
and (@v8 is null or CHARINDEX(','+CAST(g.c12 as varchar(max))+',',@v8) > 0)
group by Month(a.c1)