how to search name by giving a single letter

Posted by Chaithragm under C# on 5/15/2013 | Points: 10 | Views : 1203 | Status : [Member] | Replies : 4
I have to select the names eg:if i give a it has to list the names starting from 'a' or 'A'

but it is selecting all the names which contains a or A
I have used this query
string sql = "SELECT * where name like'%" + name +'%' + "';";




Responses

Posted by: Ankitsrist on: 5/15/2013 [Member] Starter | Points: 25

Up
0
Down
your query should be like
SELECT * where name like '"+name+"%'

Chaithragm, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Satyapriyanayak on: 5/15/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
string sql = "select * from table where name like '" + name + "%'";

If this post helps you mark it as answer
Thanks

Chaithragm, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rasik on: 5/15/2013 [Member] Starter | Points: 25

Up
0
Down
string sql = SELECT * FROM TableName WHERE Name LIKE ' " + name + "%' ".

Also above query could be a candidate for sql injection. Use command with parameters while forming query which needs runtime inputs as shown below:

string name = txtName.Text + " %";
string connectionString = ConsoleApplication1.Properties.Settings.Default.ConnectionString;

using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM TableName WHERE Name LIKE @Name", connection))
{
command.Parameters.Add(new SqlParameter("Name", name));

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
int column1 = reader.GetInt32(0);
------------------------------------
}
}
}


Chaithragm, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Chaithragm on: 5/16/2013 [Member] Starter | Points: 25

Up
0
Down
Thank u all

Chaithragm, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response