C# SQL SELECT命令在C程序中使用时会减慢速度
我直接在SQLServerManagementStudio中执行SQL语句,速度非常快,但在C程序中尝试执行同样的操作时,速度非常慢!我对查询使用完全相同的参数,但它的反应似乎不同 代码如下:C# SQL SELECT命令在C程序中使用时会减慢速度,c#,sql-server,C#,Sql Server,我直接在SQLServerManagementStudio中执行SQL语句,速度非常快,但在C程序中尝试执行同样的操作时,速度非常慢!我对查询使用完全相同的参数,但它的反应似乎不同 代码如下: public static DataTable GetInfosPrepa(String activite, String depot, String cle_prepa, int sortie, int waiting) { String connectionString = Confi
public static DataTable GetInfosPrepa(String activite, String depot, String cle_prepa, int sortie, int waiting)
{
String connectionString = ConfigurationManager.ConnectionStrings["SQLProd"].ToString(); //Récupération de la chaîne de connexion
SqlConnection myConnection = new SqlConnection(connectionString); //Nouvelle connexion à la base de donnée
myConnection.Open(); //On ouvre la connexion
String query = "";
if (waiting == 0)
{
query = @"Select * from reflex.hlprenp
where pecact = @activite
and pecdpo = @depot
and cast(penann as varchar) + cast(penpre as varchar) = @numero ";
}
else
{
query = @"Select *
from reflex.hlprenp, reflex.hlprplp, reflex.hlodpep
left join reflex.hlvaicp on oenobj = vcnobj
where pecact = p1cact
and pecdpo = p1cdpo
and penpre = p1npre
and penann = p1nann
and p1cact = oecact
and p1cdpo = oecdpo
and p1nano = oenann
and p1nodp = oenodp
and vccicm = 'STATUT'
and vcvaic = 'WAITING'
and pecact = @activite
and pecdpo = @depot
and cast(penann as varchar) + cast(penpre as varchar) = @numero ";
}
if (sortie < 2)
{
query += "and petsop=@sortie";
}
SqlDataAdapter source = new SqlDataAdapter(query, myConnection);
source.SelectCommand.Parameters.AddWithValue("@activite", activite);
source.SelectCommand.Parameters.AddWithValue("@depot", depot);
source.SelectCommand.Parameters.AddWithValue("@numero", cle_prepa);
source.SelectCommand.Parameters.AddWithValue("@sortie", sortie);
DataTable data = new DataTable();
source.Fill(data);
myConnection.Close();
return data;
}
等待时请求速度减慢!=0
谢谢你的帮助
但是,当我尝试在C程序中执行同样的操作时,速度非常慢!我
对查询使用完全相同的参数
要使用完全相同的参数,应使用SSMS中的sp_executesql,
但我猜你在SSM中使用了变量
您的问题称为参数嗅探,这意味着当您真正使用参数时,会在第一次执行时嗅探它们,并为这些嗅探值构建计划
当您在SSM中使用变量时,除非指定了重新编译选项,否则不会对其进行嗅探。在这种情况下,无法使用分布统计信息,并且您会得到不同的执行计划。它的反应似乎有所不同。您是否有实际的性能数据,或者您只是觉得速度较慢?您必须测量性能,而不是猜测性能。开始删除AddWithValue并使用适当的Add指定参数的大小。这将允许查询优化器重用相同的查询,而无需重新编译。此问题称为参数嗅探。你可以在这里阅读,并在那里查看提供的解决方案。-25年前,在ANSI-92 SQL标准中,旧样式的逗号分隔表列表样式被正确的ANSI连接语法所取代!不鼓励使用它-您应该始终为您使用的任何varchar变量和参数提供长度,只是缺少他应该做什么来防止参数嗅探Add而不是AddWithValue。@SQL代码中的Tim Schmelter optimize for unknown将防止参数嗅探;我只是不知道C和AddWithValue/Add,请随意给出答案,我在看到关于AddWithValue/Add的评论之前写了它,我想第一个只是把常量而不是使用参数作为参数