简体   繁体   English

SQL查询在SSMS中花费的时间不到1秒,而在代码中花费的时间则永远

[英]SQL Query takes less than 1 sec in SSMS and forever in code

I'm running this query against a quite big table (i guess, around 150-200 000 rows): 我在一个很大的表上运行此查询(我猜大概是150-200 000行):

select count(Distinct(eti.Email)) FROM table1 eti 
LEFT OUTER JOIN table2 ti on ti.Email = eti.Email and ti.SiteId = eti.Site_Id 
WHERE eti.Site_Id=1

In SMMS (SQL Server Management Studio) it takes less than 1 secound to execute but when I try to execute from my ASP.NET-site it times out. 在SMMS(SQL Server Management Studio)中,执行时间不到1秒,但是当我尝试从ASP.NET站点执行时,它超时了。

I'm using PetaPoco to fetch the data which "under the hood" executes this code: 我正在使用PetaPoco来获取“幕后”执行此代码的数据:

using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
    object val = cmd.ExecuteScalar();
    OnExecutedCommand(cmd);
    return (T)Convert.ChangeType(val, typeof(T));
}

I've been reading about that SSMS has som "special settings" when it executes the query? 我一直在阅读有关SSMS在执行查询时具有“特殊设置”的信息? I really need to get this up and running. 我真的需要启动并运行它。

Could the "MARS"-setting in the connection be have any impact on this? 连接中的“ MARS”设置是否对此有影响? How do i debug and find the problem? 如何调试和查找问题?

Thanks! 谢谢!

Thank you for the help! 感谢您的帮助!

I have finally found the issue (and it's a little embarrassing)... I found this blog question from msdn forums about sp_executesql being slow: and Dan Guzman who is SQL Server MVP answers: http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/3cb08860-49a0-432a-8605-0af6b374dded/ 我终于找到了这个问题(有点尴尬)...我发现来自msdn论坛的此博客问题有关sp_executesql的运行速度很慢:而SQL Server MVP的Dan Guzman回答: http : //social.msdn.microsoft.com /论坛/ zh-CN / transactsql / thread / 3cb08860-49a0-432a-8605-0af6b374dded /

Another possible issue is data type mismatches between the parameters and the column data types, resulting in non-sargable expressions and a bad plan. 另一个可能的问题是参数与列数据类型之间的数据类型不匹配,从而导致表达式无法精简和错误的计划。 Please post your query and table DDL if you need further help. 如果您需要进一步的帮助,请发布您的查询和表DDL。

So i doubled checked and it turned out that table2 had both the Email and the SiteId-fields set as "Nullable", changing them to match table1 fixed the issue. 所以我仔细检查了一下,结果发现table2的Email和SiteId字段都设置为“ Nullable”,更改它们以匹配table1可以解决此问题。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM