SQL查询在DB上工作但不与SQLCommand c#一起工作

时间:2017-02-22 02:30:24

标签: 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 * 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子句,它就像魅力一样。

1 个答案:

答案 0 :(得分:1)

尝试将'%'+@2+'%'替换为@2

然后试试这个:

 command.Parameters.Add(new SqlParameter("2", (searchstring == null) ? DBNull.Value : (object)("%"+searchstring.ToString()+"%")));