简单的参数化选择查询在c#中需要花费时间来执行
本文关键字:费时间 执行 参数 选择 查询 简单 | 更新日期: 2023-09-27 18:07:54
我有一个表结构,如下所示:
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
这个查询在SSMS中执行了5秒,但是在通过c#代码执行时,大约需要5分钟以上。
我的c#代码接受查询大小写no。在"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;
}
传递参数时的以下更改提高了查询的性能,并且在几秒钟内再次执行。
sqlCommand.Parameters.Add("@TrnDate", SqlDbType.VarChar).Value = TrnDate;
sqlCommand.Parameters.Add("@TxtID", SqlDbType.VarChar).Value = TxtID;
sqlCommand.Parameters.Add("@TxtKey", SqlDbType.VarChar).Value = TxtKey;
感谢大家的建议!
您似乎没有任何索引来优化查询。创建一个多字段索引(ElemName, TxtID, TxtKey, ActiveStatus, TrnDate)