Tuesday, December 21, 2010

about a list and sql

Here i see how to pass a paremeter that I want in a query like this.

cmd.CommandText = "Select price from products where ProductCode in @productCode";
cmd.Connection = conn;
cmd.Parameters.Add(new SqlParameter("@productCode", settingList));
reader = cmd.ExecuteReader();


so the way to handle it might seem a bit like this.
string sql = "Select price from products where ProductCode in ({0})";
string[] paramArray = settingList.Select((x, i) => "@productCode" + i).ToArray();
cmd.CommandText = string.Format(sql, string.Join(",", paramArray));

for (int i = 0; i <>
{
cmd.Parameters.Add(new SqlParameter("@productCode" + i, settingList[i]));
}

No comments:

Post a Comment