2017-02-22 104 views
1

我這裏有一個問題,我得到的SQL Server上工作的查詢,但是當我嘗試通過SqlCommand在C#中執行它,這是行不通的。你可以試着幫我嗎?SQL查詢的數據庫工作,但不能與SqlCommand的C#

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 '%'[email protected]+'%' 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

嘗試用@2

更換'%'[email protected]+'%'然後試試這個:

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

出於某種原因,它不工作。如果我用sql中的某些硬編碼來嘗試這個查詢,它可以工作......但在sqlcommand中很難得到這個工作。 – Exprove