Good day I am working on an ASP.NET C# application that searches a sql table and brings back the results in a gridview. I got it to work using the like operator but I realise that if I search a character it brings back any record with that character in it, what I want is if I search with a character I want all records starting with that character. It should also allow me to search normally, Here is what I did previously
//I have a connection manager class in my app code folder
SqlConnection connection = connectionManager.GetConnection();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = connection;
String str = "select PR_NAME_GN, PR_NAME_SURN, EVENT_PARISH, EVENT_YEAR, EVENT_TYPE, FS_IMAGE_ID from Jam01 where (PR_NAME_GN like '%' + @deceasedFirstName + '%' AND PR_NAME_SURN like '%' + @deceasedLastName + '%' AND EVENT_PARISH like '%' + @ParishOfDeath+ '%' AND EVENT_YEAR like '%' + @YearOfDeath+ '%' AND EVENT_TYPE like '%' + @TypeDeath+ '%' AND FS_IMAGE_ID like '%' + @ImgLocation+ '%')";
SqlCommand command = new SqlCommand(str, connection);
command.Parameters.Add("@deceasedFirstName", SqlDbType.NVarChar).Value = DeathFirstNametbox.Text;
command.Parameters.Add("@deceasedLastName", SqlDbType.NVarChar).Value = DeathLastNametbox.Text;
command.Parameters.Add("@ParishOfDeath", SqlDbType.NVarChar).Value = ParishoDeathtbox.Text;
command.Parameters.Add("@YearOfDeath", SqlDbType.NVarChar).Value = YearofDeathtbox.Text;
command.Parameters.Add("@TypeDeath", SqlDbType.NVarChar).Value = type_Death.Text;
command.Parameters.Add("@ImgLocation", SqlDbType.NVarChar).Value = "";
command.ExecuteNonQuery();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = command;
DataSet ds = new DataSet();
sda.Fill(ds, "PR_NAME_GN");
sda.Fill(ds, "PR_NAME_SURN");
sda.Fill(ds, "EVENT_PARISH");
sda.Fill(ds, "EVENT_YEAR");
sda.Fill(ds, "EVENT_TYPE");
sda.Fill(ds, "FS_IMAGE_ID");
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
I need recommendation on how to rework the sql statement. I am kinda new to this so please bear with me.
删除LIKE
关键字之后的前导%
通配符,以便仅返回以指定值开头的值:
String str = "SELECT PR_NAME_GN, PR_NAME_SURN, EVENT_PARISH, EVENT_YEAR, EVENT_TYPE, FS_IMAGE_ID FROM Jam01 WHERE (PR_NAME_GN LIKE @deceasedFirstName + '%' AND PR_NAME_SURN LIKE @deceasedLastName + '%' AND EVENT_PARISH like @ParishOfDeath + '%' AND EVENT_YEAR LIKE @YearOfDeath+ '%' AND EVENT_TYPE LIKE @TypeDeath+ '%' AND FS_IMAGE_ID LIKE @ImgLocation + '%');";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.