1

After query optimization I got results that are ok and I wanted to alter stored procedure, but got much worst results after SP execution, than it was after query execution!

Firstly, I think at number of reads. What can be reason for so different results?

Query is identical like in SP, only difference is that in query I declared parameter, but in SP that was input parameter. Value that is set to parameter is also same. To avoid 'recorded data' first I recompiled SP and after that done DROP and CREATE, but results were also much different.

Query is like this (table and column names are changed because of simplification, and number of columns is reduced):

DECLARE @Var1 varchar(20)    
SET @Var1 = @Var1 + '%'       

DECLARE @Var2 TIMESTAMP    
SELECT @Var2 = CONVERT(TIMESTAMP, ID, 0)    
FROM    
 X_TIMESTAMPS (NOLOCK)    
WHERE    
 TABLE = 'T1'     


declare @Var3 varbinary(8)    
SELECT @Var3 = max(IdTimeStamps)    
FROM    
 T1 (NOLOCK)     

SELECT o.c1  
  , o.c2   
  , o.c3    
  , v.c4    
  , v.c5   
  , p.c6    
  , p.c7    
  , va.c8    
  , isnull(s.c9, '') AS c9    
  , CASE o.c10    
     WHEN 1 THEN    
      0    
     ELSE    
      1    
    END c10   
  , o.c11    
FROM    
 T1 o (NOLOCK)    
 JOIN T2 p (NOLOCK)    
  ON o.c1 = p.c12    
 JOIN T3 i (NOLOCK)    
  ON (o.c13 = i.c14)    
 JOIN T4 v (NOLOCK)    
  ON (v.c4 = i.c15)    
 LEFT JOIN T5 s (NOLOCK)    
  ON (o.c16 = s.c17)    
 JOIN T6 va (NOLOCK)    
  ON o.c11 = va.c18    
WHERE    
 o.c1 LIKE @Var1    
 AND o.c2 > @Var2 

And procedure is like this:

CREATE PROCEDURE [dbo].[SP1] @Var1 varchar(20) ='' 
WITH RECOMPILE  
AS        
BEGIN

    PREVIOUS QUERY WITHOUT DECLARATION FOR @Var1

END

TnX in advance!

Nemanja

4

2 回答 2

2

这几乎可以肯定是参数嗅探问题。就个人而言,我喜欢使用虚拟变量选项来解决此问题,并且(仅当我遇到此问题时)创建设置为传入参数值的变量。

于 2012-10-22T12:19:18.127 回答
2

这是因为不同的执行计划用于带常量的查询和带参数的 sp。你可以尝试一些技巧

创建内联表函数并尝试

create function sf_test
(
    @param1 int
)
returns table
as
return
    your query using @in_param1

或者

像这样在您的过程中声明其他参数

create procedure sp_test
(
    @param1 int
)
as
begin
    declare @in_param1 int

    select @in_param1 = @param1

    your query using @in_param1
end

您也可以尝试with recompile在您的过程中使用选项,或使用动态 SQL

于 2012-10-22T11:26:30.957 回答