I have a SQL query that takes less than a second to execute when I’m using SQL Management Studio, but when my code executes it, it takes over 30 seconds to get the result from the database server. The result contains 1700 rows. Another similar query, that returns 900 rows, takes a few ms to execute. What can be the reason for this odd behaviour?
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);
}
Based on your reply on comments i would say the correct solution is indexes.
Simplest way would be to run the sql logging for a bit when you run the normal queries, and then afterward run the run the sql profiler.
Based on its recommendations it could have spottet a missing indexes.