我有以下 sql 语句从存储的视图中提取数据:
foreach (var id in insert_idlist[0])
{
mssql_con.Open();
//top 1 for duplicate removal
//slowdown?
var mssql_select = "SELECT * FROM dbo.export_to_web WHERE SKU = '" + id + "'";
}
我想重写 sql 语句以使用 IN 子句或类似的子句将所有 id 插入单个查询以加快执行速度。但是我知道 IN 是一个相对较慢的操作,所以我希望获得一些专家建议,以最快的方式检索我的数据。
速度是我在这个问题上唯一关心的问题。
请注意,安全性不是问题,因为此应用程序从内部数据库中提取所有变量,没有直接的 Web 访问权限。
更新代码:
try
{
//foreach (var id in insert_idlist[0])
//{
mssql_con.Open();
//top 1 for duplicate removal
//slowdown?
//var mssql_select = "SELECT * FROM dbo.export_to_web WHERE SKU = '" + id + "'";
var mssql_select = "SELECT * FROM dbo.export_to_web WHERE SKU IN (" + insert_idlist .Select(x => "'" + x + "'") .Aggregate((x, y) => x + "," + y) + ")";
//var mssql_select = "SELECT * FROM dbo.Book5 WHERE SKU = '"+id+"'";
SqlCommand cmd = new SqlCommand(mssql_select, mssql_con);
cmd.CommandTimeout = 0;
lbl_dev.Text += "teest";
//Create a data reader and Execute the command
try
{
SqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
insert_idlist[1].Add(dataReader["supplier name"] + " " + dataReader["range description"] + " " + dataReader["item description"]);
insert_idlist[3].Add(dataReader["Sale Price"] + "");
insert_idlist[2].Add(dataReader["WebDesc"] + "");
//insert_idlist[3].Add(dataReader["id"] + "");removed
insert_idlist[4].Add(dataReader["WebDimensions"] + "");
insert_idlist[5].Add(dataReader["RRP"] + "");
insert_idlist[6].Add(dataReader["Normal Price"] + "");
insert_idlist[7].Add("482"); //add me
insert_idlist[8].Add(dataReader["ID"] + "");
lbl_dev.Text += dataReader["supplier name"] + " " + dataReader["range description"] + " " + dataReader["item description"];
lbl_dev.Text += mssql_select;
about_to_insert = about_to_insert + 1;
}
lbl_dyn_status.Text = "Record 0 of " + about_to_insert + "updated.";
dataReader.Close();
mssql_con.Close();
}
catch (Exception e)
{
lbl_dev.Text = "" + e.Message;
}
// }
}
catch (Exception e)
{
lbl_dev.Text = "" + e.Message;
}