简体   繁体   English

在SSMS中运行良好的SQL查询在ASP.NET中运行非常慢

[英]SQL Query that runs fine in SSMS runs very slow in ASP.NET

I have an asp.net page that loads a query which we know to run fine (within 1 to 2 seconds) when executed from SQL Server Management Studio, however when executed from ASP.NET in a SQLCommand the query takes substantially longer, I cannot seem to figure out what is happening other than one line has been added to the query since the problem started, however I cannot locate what the issue is. 我有一个asp.net页,它加载了一个查询,该查询在SQL Server Management Studio中执行时可以正常运行(在1到2秒钟之内),但是在SQLCommand中从ASP.NET执行时,该查询花费的时间更长,我无法似乎弄清楚自问题开始以来,除了向查询添加一行以外,正在发生什么事情,但是我无法找到问题所在。

The offending line of code that was added is line 6: bi.INGR_CODE != 0 已添加的有害代码行是第6行: bi.INGR_CODE != 0

SQL Statement SQL语句

    SELECT  bh.JOB_NUMBER, j.DESCRIPTION, SUM(bi.INGR_ACTUAL) AS TOTAL
    FROM    BATCH_HEADER AS bh LEFT OUTER JOIN 
        BATCH_INGR AS bi
            ON bh.BATCH_ID = bi.BATCH_ID AND
            bh.FACTORY = bi.FACTORY AND
            bi.INGR_CODE <> 0 LEFT OUTER JOIN
    ServerNameReplaced.man_prod.dbo.JOBS AS j
        ON bh.JOB_NUMBER = j.JOB_NUMBER COLLATE database_default AND
           bh.FACTORY = j.FACTORY COLLATE database_default
    WHERE   ( bh.FACTORY = @Factory ) AND
            ( bh.DATETIME_DUMP >= @StartDate ) AND
            ( bh.DATETIME_DUMP < @EndDate )
    GROUP BY bh.JOB_NUMBER, j.DESCRIPTION
    ORDER BY bh.JOB_NUMBER

ASP.NET Code Behind File 文件后面的ASP.NET代码

//Temporary List
List<BatchItem> data = new List<BatchItem>();

string SQLCommand = DBHelper.LoadSQLStatement( "batchdescription.sql" );

System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringNameReplaced"].ConnectionString);
System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand(SQLCommand, sqlConnection );

try
{
    sqlCommand.Parameters.Add( "@StartDate", System.Data.SqlDbType.DateTime ).Value = StartDate;
    sqlCommand.Parameters.Add( "@EndDate ", System.Data.SqlDbType.DateTime ).Value = EndDate;
    sqlCommand.Parameters.Add( "@Factory", System.Data.SqlDbType.VarChar, 2 ).Value = Factory;

    sqlConnection.Open();

    SqlDataReader DataReader = sqlCommand.ExecuteReader();

    while ( DataReader.Read() )
    {
        data.Add(
            new BatchItem()
            {
                JobNumber = DataReader[0].ToString(),
                Description = DataReader[1].ToString(),
                Total = decimal.Parse( DataReader[2].ToString() )
            } );
    }
}
catch ( Exception ex )
{
    //handle exceptions
}
finally
{
    sqlConnection.Close();
}

There are all kinds of things that could be going on. 可能会发生各种各样的事情。

First, Ivan G. is right that connection parameters and SET options might be different between SSMS and your ASP.NET client. 首先,Ivan G.是正确的,SSMS和ASP.NET客户端之间的连接参数和SET选项可能有所不同。 That's something worth looking into in Profiler, if you have access to it. 如果可以访问,那是值得在Profiler中研究的东西。

Second, if you've run your query multiple times in a row in SSMS, it's possible the results are being cached and that's why it runs so fast in SSMS. 其次,如果您已在SSMS中连续运行查询多次,则结果可能会被缓存,这就是为什么它在SSMS中运行如此之快的原因。 If it runs slowly the first time you open up SSMS and try to run it, but then speeds up, that's a sign there's caching going on. 如果它在您第一次打开SSMS并尝试运行时运行缓慢,但随后又加快了速度,则表明正在进行缓存。

As for why adding one extra clause to a join could slow things down, it's hard to say why without knowing more about your tables, but it's not impossible that that could have done it. 至于为什么要在联接中添加一个额外的子句会减慢速度,很难说为什么不了解更多有关表的信息,但是这样做并非不可能。 Is there an index over BATCH_INGR that includes both FACTORY and INGR_CODE ? 是否在BATCH_INGR上同时包含FACTORYINGR_CODE You might need one now that you're including INGR_CODE in your join conditions. 现在可能需要一个,因为您要在INGR_CODE条件中包括INGR_CODE

The best way to find out is to look at the query plan with and without the INGR_CODE clause and see how it differs. 找出INGR_CODE的最佳方法是查看有无INGR_CODE子句的查询计划,并了解它的不同之处。 Is the cost figure for one query bigger than for the other? 一个查询的费用数字是否比另一个查询大? Are there table scans where there weren't before? 有没有以前没有的表扫描? Has an index seek turned into an index scan? 索引搜索是否已变成索引扫描?

I've had to trouble shoot these before, and they're not fun, but in my experience what I've seen is different execution plans between ASP.NET & running the query in SSMS. 我以前很难解决这些问题,而且它们并不有趣,但是以我的经验,我发现ASP.NET与在SSMS中运行查询之间存在不同的执行计划。 ASP.NET doesn't cache the query, SSMS does, but sometimes the execution plan is actually different. ASP.NET不会像SSMS那样缓存查询,但是有时执行计划实际上是不同的。 The culprit often times is a bad index that is being accessed out of order, here's the guide I tend to use: 造成这种情况的罪魁祸首通常是一个坏索引,该索引被乱序访问,这是我倾向于使用的指南:

http://www.sommarskog.se/query-plan-mysteries.html http://www.sommarskog.se/query-plan-mysteries.html

It's because the query plan cache is not the same. 这是因为查询计划缓存不同。

This is because your code and SSMS does not use the same settings and because of parameter spoofing (ie Sql Server creates the plan cache depending on the first sp execution and the parameters you sended this time) => when you execute via code and via SSMS you don't have the same query execution plan. 这是因为您的代码和SSMS使用的设置不同,并且是由于参数欺骗(即Sql Server根据第一次执行sp和这次发送的参数创建计划缓存)=>当您通过代码和通过SSMS执行时您没有相同的查询执行计划。

To be sure that you're using the same plan : tool -> Query Execution -> SQL Server -> Advance -> uncheck "SET ARITHABORT" 为了确保您使用的是相同的计划:工具->查询执行-> SQL Server->高级->取消选中“ SET ARITHABORT”

Avoid calling another stored procedure inside a stroredprocedure you mentioned. 避免在您提到的strededprocedure内部调用另一个存储过程。 This will solve your issue 这将解决您的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure数据库中的存储过程在ASP.NET中运行很快,但在SSMS中运行缓慢 - Stored procedure in Azure database runs fast in ASP.NET but slow in SSMS SQL在Access中运行,但不在ASP.NET Web窗体中运行 - SQL runs in Access but not in ASP.NET webform ASP.NET和EF非常慢 - ASP.NET and EF are very very slow ASP.Net 页面第一次运行缓慢如果我使用 System.Web.Ui 命名空间 - ASP.Net Page runs slow at first time If i used System.Web.Ui Namespace SQL权限在SSMS和ASP.NET中不同吗? - SQL Permissions differ in SSMS and ASP.NET? 我是 sql 的新手。没有得到查询结果。 运行良好,没有错误 - i am new to sql .Not Getting query result . Runs fine with no error ASP.NET Core 2.0 Web 应用程序在将项目部署到 Azure Web 服务时失败并出现 SQLite 错误,但在本地环境中运行良好 - ASP.NET Core 2.0 Web Application fails with a SQLite error when deploying the project to Azure Web Service but runs fine in local environment ASP.NET Core 1.1 在本地运行良好,但在发布到 Azure 时显示“启动应用程序时出错”。 - ASP.NET Core 1.1 runs fine locally but when publishing to Azure says “An error occurred while starting the application.” 如果ASP.NET 5应用程序在Ubuntu上运行,它可以与MS SQL Server进行通信吗? - Can an ASP.NET 5 app communicate to MS SQL Server if it runs on Ubuntu? C# 和 ASP.NET 定时器 function 每周仅运行一次 sql - C# and ASP.NET timer function that runs sql only once a week
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM