C# SQL查询在数据库上工作,但不使用SQLC命令
我这里有一个问题,我得到了一个在SQL Server上工作的查询,但是当我尝试在C中通过SqlCommand执行它时,它不工作。你能帮我一下吗C# SQL查询在数据库上工作,但不使用SQLC命令,c#,sql,sql-server,C#,Sql,Sql Server,我这里有一个问题,我得到了一个在SQL Server上工作的查询,但是当我尝试在C中通过SqlCommand执行它时,它不工作。你能帮我一下吗 public List<Product> GetProductsByFilter(string category, string searchparam, string searchstring, string sortparam, string sort) { string stringcommand = "SELECT * FRO
public List<Product> GetProductsByFilter(string category, string searchparam, string searchstring, string sortparam, string sort)
{
string stringcommand = "SELECT * FROM Products WHERE (Category = @0 OR @0 IS NULL) AND(@1 = @2 OR @1 Like '%'+@2+'%' OR @1 IS NULL OR @2 IS NULL) ORDER BY Category,";
stringcommand += (string.IsNullOrWhiteSpace(sortparam)) ? "Name" : sortparam;
stringcommand += (string.IsNullOrWhiteSpace(sort)) ? " ASC" : " " + sort;
if (string.IsNullOrWhiteSpace(searchparam) && !string.IsNullOrWhiteSpace(searchstring))
searchparam = "Name";
List<Product> productlist = new List<Product>();
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
SqlCommand command = new SqlCommand(stringcommand, conn);
command.Parameters.Add(new SqlParameter("0", (category == null) ? DBNull.Value : (object)category));
command.Parameters.Add(new SqlParameter("1", (searchparam == null) ? DBNull.Value : (object)searchparam));
command.Parameters.Add(new SqlParameter("2", (searchstring == null) ? DBNull.Value : (object)searchstring.ToString()));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
productlist.Add(new Product()
{
ProductID = (int)reader[0],
Name = (string)reader[1],
Description = (string)reader[2],
Category = (string)reader[3],
ImagePath = (string)reader[4],
UnitsInStock = (int)reader[5],
Price = (decimal)reader[6],
Supplier = GetSupplierDataByID((int)reader[7])
});
}
}
}
return productlist;
}
此函数返回null,而在SQL中它返回一些行。如果我删除LIKE子句,它的作用就像一个符咒。尝试用@2替换“%+@2+'%”
然后试试这个:
command.Parameters.Add(new SqlParameter("2", (searchstring == null) ? DBNull.Value : (object)("%"+searchstring.ToString()+"%")));
由于某种原因,它不起作用。如果我尝试使用sql硬编码的查询,它会工作。。。但在sqlcommand中,很难让它正常工作。