从SMSS运行的存储过程是Lightning Fast,ADO.NET慢了20倍

时间:2018-05-24 19:06:38

标签: c# sql sql-server ado.net

希望有人可以为我照亮一点点。我一直在尝试使用Slow in the Application, Fast in the SMSS尝试在最后一天左右尝试解决问题,但无济于事。

我有一个试图从自定义构建视图中检索值的存储过程:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ARITHABORT ON
GO

CREATE PROCEDURE [dbo].[GetProcesses]
    @SessionId INT,
    @LastUpdate DATETIME2(7)
AS
    DECLARE @MySessionId INT
    SET @MySessionId = @SessionId

    DECLARE @MyLastUpdate DATETIME2(7)
    SET @MyLastUpdate = @LastUpdate
BEGIN

    SELECT * 
    FROM [GetProcessesView]
    WHERE SessionId = @MySessionId 
      AND (StartTime >= @MyLastUpdate OR 
           LastModified >= @MyLastUpdate OR 
           ProcessStepViewLastModified >= @MyLastUpdate)
END
GO

我可以使用我的应用程序提供的相同参数从SQL Server Management Studio运行此命令,这将在1-2秒内完成。但是,当我尝试从我的数据访问层运行它时,它需要超过40.数据集相对较小(可能大约5 mbs)。

using (var connection = new SqlConnection(GetConnectionString()))
{
    var dataSet = new DataSet("ProcessUpdates");

    SqlCommand command = new SqlCommand("GetProcesses", connection);
    command.Parameters.AddWithValue("@SessionId", sessionId);
    command.Parameters.AddWithValue("@LastUpdate", lastUpdate);
    command.CommandType = CommandType.StoredProcedure;

    SqlDataAdapter dataAdapter = new SqlDataAdapter()
    {
        SelectCommand = command
    };

    dataAdapter.Fill(dataSet);
}

以下是我的观点列表:SQL Management Studio中此视图中的查询非常快。

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create view [dbo].[GetProcessesView]
as
select P.Id as ProcessViewId, P.[Name], P.StartTime, P.CompletedTime, P.IsFailed, P.UnitId, P.ProcedureId, P.SessionId, P.LastModified, P.AutomationId,
       PS.Id as ProcessStepViewId, PS.[Status], PS.ProcessId, PS.StepNum, PS.Description, PS.LastModified as ProcessStepViewLastModified,
       [U].Id as UnitViewId, [U].Number, [U].[Grouping], [U].EnumValue,
       PR.Id as ProcedureViewId, PR.Title as ProcedureViewTitle, PR.Steps, PR.SystemId as ProcedureViewSystemId, PR.VisionId, PR.[Grouping] as ProcedureViewGrouping,
       A.Id as AutomationViewId, A.Title as AutomationViewTitle, A.UserControl, A.InProgressUserControl, A.SystemId as AutomationViewSystemId,
       SY.Id as SystemViewId, SY.FullName as SystemViewFullName, SY.Acronym as SystemViewAcronym,
       S.Id as SystemTwoViewId, S.FullName as SystemTwoViewFullName, S.Acronym as SystemTwoViewAcronym,
       P.[UID]

from [Process] P
left join [ProcessSteps] PS on P.Id = PS.ProcessId 
left join [Unit] U on P.UnitId = U.Id
left join [Procedure] PR on P.ProcedureId = PR.Id
left join [Automation] A on P.AutomationId = A.Id
left join [PlantSystem] S on  PR.SystemId = S.Id
left join [PlantSystem] SY on  A.SystemId = SY.Id

GO

0 个答案:

没有答案