SQL Like Statement C#

RecipeDan
RecipeDan used Ask the Experts™
on
Hello:

How do I use the SQL Like Statement in C#

adapter = new SqlDataAdapter("SELECT PName, FROM MID WHERE PName LIKE '%@PName%'", conn);
adapter.SelectCommand.Parameters.Add("@PName", System.Data.SqlDbType.NVarChar);
adapter.SelectCommand.Parameters["@PName"].Value = "Sm";

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
That should work, remove the comma after PName.
Billing Engineer
Most Valuable Expert 2014
Top Expert 2009
Commented:
this will work better:
adapter = new SqlDataAdapter("SELECT PName, FROM MID WHERE PName LIKE '%' + @PName + '%'",

Commented:
As suggested before, remove the comma after PName.
I would also suggest you to specify the length of your variable.
You can also set the value of your variable in the declaration line:

adapter = new SqlDataAdapter("SELECT PName FROM MID WHERE PName LIKE '%@PName%'", conn);
adapter.SelectCommand.Parameters.Add("@PName", System.Data.SqlDbType.NVarChar, 128) { value = "Sm" };

Open in new window


Then, it is just a way of work, I always try to avoid writing inline statement, but rather use Stored Procedures.
SP are easier to manage, from both the developer's and the dba's side. Also your SQL Server will thank you, because SP execution plans are likely to be cached, and inline statements not.

Regards.

Author

Commented:
Thanks everyone for your help.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial