我有以下功能:
CREATE FUNCTION [dbo].[SuiviRupture](@CodeArticle [nvarchar](13),@CodeSite [nvarchar](5) ,@CodeStructure [nvarchar](13))
RETURNS @calcul TABLE
(
[Code Article] [nvarchar](13),
[Code Structure][nvarchar](13) NULL,
[Code Site][nvarchar](5) NULL,
CAMOY float,
QTEMOY float
)
AS
BEGIN
DECLARE @Temp TABLE
(
[datecol] date,
[Code Article] [nvarchar](13),
[Prix de vente TTC] [nvarchar](15) NULL,
[Code Site][nvarchar](5) NULL,
[Code Structure][nvarchar](13) NULL,
Quantité float ,
rn int
);
insert into @Temp
([datecol],[Code Article],[Prix de vente TTC],[Code Site],[Code Structure],Quantité,rn)
select t1.[datecol],t1.[Code Article],t1.[Prix de vente TTC],t1.[Code Site],t1.[Code Structure],t1.Quantité ,rn
from [Vente] t1
inner join (select distinct [datecol],[Code Article],[Code Structure],[Code Site],
row_number() over(Partition by [Code Article],[Code Structure],[Code Site] order by [datecol]desc ) as rn
from (select distinct [datecol],[Code Article],[Code Structure],[Code Site]
from [Vente] t2
where promo = 0
and ([Code Article] is not null) and ([Code Structure] is not null) and ([Prix de Revient] is not null )and [Code Article]= @CodeArticle and [Code Site]=@CodeSite and [Code Structure]=@CodeStructure
)g
) a
on a.datecol=t1.datecol
and t1.[Code Article] = a.[Code Article]
and t1.[Code Structure]=a.[Code Structure]
and t1.[Code Site]=a.[Code Site]
where promo = 0 --and t1.[Code Article]= ' 020130180'
and rn <= 28
INSERT @calcul
select
[Code Article]
,[Code Structure]
,[Code Site]
, sum(convert(float,Quantité))/count(distinct [datecol]) as QTEMOY
, sum(convert(float,[Prix de vente TTC])) / count(distinct [datecol]) AS CAMOY
from @Temp
where [Code Article]= @CodeArticle and [Code Site]=@CodeSite and [Code Structure]=@CodeStructure
group by
[Code Article],[Code Structure]
,[Code Site]
RETURN;
END;
GO
当我执行以下查询时,执行时间太长,需要几个小时 如何优化它?
select t1.[Code Article],t1.[Code Site],t1.[Code Structure], u.QTEMOY,u.CAMOY
from V_distinctVente t1 With(nolock)
Cross apply dbo.[SuiviRupture](t1.[Code Article],t1.[Code Site],t1.[Code Structure]) u
答案 0 :(得分:0)
在不知道实际背景的情况下很难复制。您可以将此查询放在sql analyzer中,并尝试在那里进行更改。
答案 1 :(得分:0)
实际上你正在使用永远不会像存储过程那样预编译的函数。使用存储过程然后你可以提升性能.Store过程编译查询并将结果保存在sql server中的执行计划中。此链接可能有助于link