我有一个SQL查询,使用SQL Management Studio时执行的时间不到一秒钟,但是当我的代码执行该查询时,要花费30秒以上的时间才能从数据库服务器获取结果。结果包含1700行。另一个返回900行的类似查询需要花费几毫秒的时间才能执行。这种奇怪行为的原因可能是什么?
public SqlDataReader ExecuteReader(string strSQL, ArrayList arParams) { OpenConnection(); SqlCommand myCommand = new SqlCommand(strSQL, myConnection); myCommand.CommandTimeout = intTimeout; foreach (SqlParameter myParameter in arParams) myCommand.Parameters.Add(myParameter); return myCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection); }
strSQL:
SELECT [Group].[Id] ,[Group].[intCustomerId] ,[Group].[strName] ,[Permission].[dtmCreated] ,[Permission].[intPermissionTypeId] ,[Permission].[intObjectTypeId] ,[Permission].[intObjectId] ,[Permission].[blnActive] ,[Permission].[blnHaveAccess] ,[Permission].[intLevelTypeId] FROM [Group] LEFT JOIN Permission ON [Group].[Id] = intGroupId AND intObjectId = @ObjectId AND intObjectTypeId = @ObjectTypeId AND intLevelTypeId = @LevelType AND intPermissionTypeId = @PermissionTypeId AND blnActive = 1 WHERE [Group].[intCustomerId] = @CustomerId AND [Group].[blnDeleted] = 0 ORDER BY strName, blnActive DESC
arParams:
arParams.Add(DatabaseHandler.MakeSqlParameter("@CustomerId", customer.Id)); arParams.Add(DatabaseHandler.MakeSqlParameter("@ObjectId", masterprocess.Id)); arParams.Add(DatabaseHandler.MakeSqlParameter("@ObjectTypeId", Convert.ToInt32(ObjectType.MasterProcess))); arParams.Add(DatabaseHandler.MakeSqlParameter("@PermissionTypeId", Convert.ToInt32(permissiontype))); arParams.Add(DatabaseHandler.MakeSqlParameter("@LevelType", Convert.ToInt32(leveltype)));
DatabaseHandler.MakeSqlParameter:
public static SqlParameter MakeSqlParameter(String strName, int intInput) { return new SqlParameter(strName, intInput); }
根据您对评论的答复,我会说正确的解决方案是索引。
最简单的方法是在运行常规查询时先运行sql日志记录,然后再运行sql profiler。
根据其建议,它可能发现了缺失的索引。