我有一个如下表结构:
CREATE TABLE [dbo].[MainTbl](
[RowNum] [int] IDENTITY(1,1) NOT NULL,
[TxtID] [varchar](20) NOT NULL,
[TxtKey] [varchar](20) NOT NULL,
[TrnDate] [datetime] NOT NULL,
[SrcID] [varchar](20) NOT NULL DEFAULT (''),
[ElemName] [varchar](20) NOT NULL,
[TblXml] [varchar](max) NOT NULL,
[ActiveStatus] [varchar](20) NOT NULL DEFAULT (''),
[DevLvl] [int] NOT NULL DEFAULT ((0)),
[Archive] [bit] NULL CONSTRAINT [DF_MainTbl_Archive] DEFAULT ((0)),
CONSTRAINT [pkMainTbl] PRIMARY KEY CLUSTERED
([RowNum] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
并执行以下查询以获取xml:
select TblXml from MainTbl with (nolock)
where TrnDate < @TrnDate and TxtID = @TxtID and TxtKey = @TxtKey
and ActiveStatus != 'NonActive' and ElemName = 'xyz' order by TrnDate desc
此查询在5秒内在SSMS中执行,但在通过C#代码执行时, 大约需要5分钟以上。
我的C#代码接受查询案例号。在“BuildQuery”中准备上述语句和 返回一个sqlcommand,我传递参数并执行它,但是“sqlCommand.ExecuteReader();”花了很多时间。
private bool MainFunction(parameters)
{
CheckXMLDate(4,'9/6/2016 1:00:00 PM','ABC','123' );
}
________________________________
public bool CheckXMLDate(bldqry,TrnDate,TxtID,TxtKey )
{
SqlCommand sqlCommand = BuildQuery(bldqry);
sqlCommand.Parameters.AddWithValue("@TrnDate", TrnDate);
sqlCommand.Parameters.AddWithValue("@TxtID", TxtID);
sqlCommand.Parameters.AddWithValue("@TxtKey", TxtKey);
SqlDataReader dataReader = sqlCommand.ExecuteReader();
//Some statements like below...
if (check == success)
{ dataReader.Close();
return true;}
dataReader.Close();
return false;
}
_______________________________________
public SqlCommand BuildQuery(int caseNum)
{
string QryString = string.Empty;
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Connection = con;
switch (caseNum)
{
case 4:
{
QryString = "select TblXml from MainTbl with (nolock) "+
"where TrnDate < @TrnDate "+
"and TxtID = @TxtID "+
"and TxtKey = @TxtKey " +
"and ActiveStatus != 'NonActive' and ElemName = 'xyz' order by TrnDate desc";
break;
}
default:
{ break; }
}
sqlCommand.CommandText = QryString;
sqlCommand.CommandTimeout = 800;
return sqlCommand;
}
这里所有参数都是字符串类型。
答案 0 :(得分:2)
传递参数时的下方更改提高了查询的性能,并在几秒钟后再次执行。
sqlCommand.Parameters.Add("@TrnDate", SqlDbType.VarChar).Value = TrnDate;
sqlCommand.Parameters.Add("@TxtID", SqlDbType.VarChar).Value = TxtID;
sqlCommand.Parameters.Add("@TxtKey", SqlDbType.VarChar).Value = TxtKey;
感谢大家提出的所有建议!
答案 1 :(得分:0)
您似乎没有任何索引来优化查询。在(ElemName,TxtID,TxtKey,ActiveStatus,TrnDate)上创建多字段索引