3

I have following function in my DataAcess class, but it is not showing any result.
My code is as follow:

public List<Products> GetProduct(string productName)
 {
    System.Data.DataSet ds = null;
    db = DBWrapper.GetSqlClientWrapper();
    db.ClearParameters();
    db.AddParameter(db.MakeInParam("@ProductName", DbType.String, 30, productName));
    string query = @"SELECT ProductId   
                     FROM [Products]   
                     WHERE Name LIKE '%@ProductName%'";
    ds = db.GetDataSet(query);
    db.ClearParameters();
        // Rest of Code
 }

I also tried:

string query = @"SELECT ProductId    
                 FROM [Products]   
                 WHERE Name LIKE '%"+"@ProductName"+"%'";

But it runs fine without parameterized like:

string query = @"SELECT ProductId  
                 FROM [Products]   
                 WHERE Name LIKE '%"+productName+"%'";

How to write this with parameterized using @ProductName???

3 Answers 3

7

You should use

LIKE '%' + @ProductName + '%'

instead of

LIKE '%@ProductName%'

Why? Because in query, your parameter is inside quotes. In quotes, SQL will recognize it as a string literal and never sees it as a parameter.

As an alternative, you can use your % % part in your AddParameter method as Damien_The_Unbeliever mentioned.

Sign up to request clarification or add additional context in comments.

Comments

3

Try, instead:

db.AddParameter(db.MakeInParam("@ProductName", DbType.String, 30, "%" + productName + "%"));
string query = @"SELECT ProductId   
                 FROM [Products]   
                 WHERE Name LIKE @ProductName";

SQL doesn't look for parameters inside of literal strings. So you can make the parameter be the entire string argument for the LIKE operator.

1 Comment

Thanx Damien, It also works but I like Soner's way easy (somehow) :)
0

Rather than adding a parameter, you can also use:

string query = String.Format("Select ProductId FROM Products where Name LIKE '{0}'", productName);

1 Comment

@Sohail - okay Soner came to your rescue :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.