Click here to Skip to main content
15,906,569 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello everyone,

i have a question for the C# SQLCommand.

this is my SQL query to be run :

C#
string s = "Select * from Country where Countrycode like @Code"

Sqlcommand cmd = new sqlcommand(s,sqlcon);
cmd.parameters.addwithvalue(@Code,value);
cmd.executenonquery();


here i cant get the result, i think is the parameter problem.
so i change the @code by using
C#
string s = "Select * from Country where Countrycode like '%"+ Code +"%'"


it is working.
can tell me where is my mistake for the parameter?
Posted
Updated 18-Aug-11 0:19am
v3

You can use this while using Like clause

C#
command.Parameters.AddWithValue("@Code","%" + value + "%");
 
Share this answer
 
cmd.executenonquery(); will not return you the result set. Try to use data reader or data adapter.
 
Share this answer
 
Check for any leading or trailing blank spaces in your data. If that is the case, using LTrim(RTrim(Countrycode)) like @Code will work fine.
 
Share this answer
 
C#
SqlConnection objConnection = new SqlConnection("Connection String");
System.Data.DataSet objDataSet = new System.Data.DataSet();
SqlCommand objCommand = new SqlCommand(strQuery);
objCommand.Connection = objConnection;
objCommand.CommandType=System.Data.CommandType.Text;
//Initializing the adapter
SqlDataAdapter objDataAdapter = new SqlDataAdapter(objCommand);
//Creating the DataSet
objDataSet = new System.Data.DataSet();
//Filling the DataSet
objDataAdapter.Fill(objDataSet);
objCommand.Dispose();
objConnection.Close();
 
Share this answer
 
simple way to pass the parameters is to embed them to commandstring.
like

string s = "Select * from Country where Countrycode like '%"+ Code +"%'"

and in query u r selecting multiple values so u had to use SqlDataReader.
SqlDataReader stores multiple columns and rows. and to read the data write code like this one

C#
while(reader.read())
{
value1=reader[0]//u can use column name instead of index number.
value2=reader["Name"]//like i used it here
// use arrays  to store the data.
}
 
Share this answer
 
Try this,

var SQL = string.format("SELECT * FROM {0} WHERE {1} LIKE ?", TABLE, NAME);
Cmd.Parameters.AddWithValue(@code, "%" + value + "%");
 
Share this answer
 
Comments
Suresh Suthar 18-Aug-11 6:43am    
I have already provided this in Solution 3.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900