Wednesday, March 21, 2012

Failed searching records by using SQLCommand Parameter "LIKE %@keywords%"

I use SQL Server 2005 Developer. I failed to search the records by using SQLCommand Paramater. Please find the code below.

However, when I hardcode like LIKE '%sudoku%' , it works. Could aynone help?

Thanks,

Andy.

privatebool searchProducts(string keywords)

{

......

command.CommandText ="SELECT Product.ProductID, Product.Name, Product.Image, ProductPrice.Price, ISNULL(SpecialProduct.PromoDiscount,0) as PromoDiscount FROM Product INNER JOIN ProductPrice ON Product.ProductID = ProductPrice.ProductID LEFT OUTER JOIN SpecialProduct ON Product.ProductID = SpecialProduct.ProductID WHERE Product.Name LIKE '%@.keywords%' ";

command.Parameters.Add("@.keywords",SqlDbType.VarChar, 100);

command.Parameters["@.keywords"].Value = keywords;

..........

}

Your keyword parameter will be treated as literal text as it is within quotes and hence it will not be treated as parameter.

The following shoud work:

command.CommandText ="SELECT Product.ProductID, Product.Name, Product.Image, ProductPrice.Price, ISNULL(SpecialProduct.PromoDiscount,0) as PromoDiscount FROM Product INNER JOIN ProductPrice ON Product.ProductID = ProductPrice.ProductID LEFT OUTER JOIN SpecialProduct ON Product.ProductID = SpecialProduct.ProductID WHERE Product.Name LIKE @.keywords";

command.Parameters.Add("@.keywords",SqlDbType.VarChar, 100);

command.Parameters["@.keywords"].Value = "%" + keywords + "%";

|||

Yes Many thanks. It works now.

Andy.

No comments:

Post a Comment