Stored proc gives different result set than tsql, only on some servers

后端 未结 2 1041
南旧
南旧 2021-01-04 20:32

This is a followup to a question I asked yesterday:

Have you ever had SQL Server 2008 return a different result set than SQL Server 2000?

where I originally

相关标签:
2条回答
  • 2021-01-04 20:55

    OK, here is my fix - it absolutely doesn't not explain the original problem, but this is what I did:

    Whenever I have a "parameter sniffing" performance issue, in order to solve that I declare 'local' variables for all parameters, assign those parameters to those variables, and then use only the local variables in the rest of the proc, like this:

      ALTER Procedure [dbo].[rptDateIncomeStatementPlusCash]
            @PropertyID int = Null,
            @PortfolioID    int = Null,
            @StartDate  datetime = Null,
            @EndDate    datetime = Null,
            @AcctMethod tinyint = 1
        AS
          DECLARE   @xPropertyID    int 
          DECLARE   @xPortfolioID   int 
          DECLARE   @xStartDate datetime 
          DECLARE   @xEndDate   datetime 
          DECLARE   @xAcctMethod    tinyint 
    
          SET @xPropertyID= @PropertyId
          SET @xPortfolioId = @PortfolioId
          SET @xStartDate = @StartDate
          SET @xEndDate = @EndDate
          SET @xAcctMethod = @AcctMethod
    

    the similarity is that when parameter sniffing is an issue, you can run a stored proc thru MGMT studio and get better performance than running it as an SQL, and changes (like those above), usually fix it.

    In my case I was seeing a difference between straight TSQL versus executing the proc(although it was not performance related), I gave it a try - and presto it worked; I wish I had a better explanation, because quite honestly I find it scary to think that SQL server will on occassion give inconsistent results when running nearly identical code.

    I did find this bulletin from MS about a similar but different problem, that at least does confirm that under the right circumstances, SQL server may give you bad answers, and this related bug report with this key phrase:

    Description: Two sessions each make many calls to a procedure P with changing parameter values. The procedure P executes one query against static data, sometimes with OPTION (RECOMPILE) and sometimes without.

    Occasionally P gives incorrect results (for the repro below, this typically happens about 1/2% - 1% of the time). When P's results are wrong, P returns either 0 or twice the expected number of rows.

    Someone yesterday left a comment about parameter sniffing as a possibility but for whatever reason they deleted their comments (or answer) so I can't give credit to them for the tip.

    0 讨论(0)
  • 2021-01-04 21:09

    Here is the execution plan, for those interested - could figure out how do this as a comment

    0 讨论(0)
提交回复
热议问题