简体   繁体   中英

How to search through sql database with multiple words

I have SQL Server database for users, and now I want to make simple search algorithm for this table. My goal is to make algorithm that can combine search of multiple words, so I tried with this strategy: when search button is pressed, method first extracts individual words from search string and then inserts them as a parameters in SqlCommand CommandText .

It works for one word but it gets stuck when I type more than one word. Here is the code sample:

private void btnSearchUsers_Click(object sender, EventArgs e)
{
             command = new SqlCommand();
             adapter = new SqlDataAdapter();
             dataset = new DataSet();
            try
            {
                User.connection.Open();
                command.CommandText = "SELECT * FROM tbl_Users WHERE userActive = 1";
                if (!String.Empty.Equals(tboxInputUsers.Text))
                {
                    command.CommandText += " AND";
                    string[] words = tboxInputUsers.Text.Split(' ');
                    string id = "id";

                    foreach (string word in words)
                    {
                        id += "a";
                        command.CommandText += String.Format(" userUsername LIKE @{0} OR userName LIKE @{0} OR userSurname LIKE @{0}", id);
                        command.Parameters.AddWithValue(String.Format("@{0}", id), word);
                    }
                }
                command.Connection = User.connection;
                adapter.SelectCommand = command;

                adapter.Fill(dataset);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                if (ConnectionState.Open.Equals(User.connection.State)) Korisnik.connection.Close();
            }
            DataTable table = new DataTable();
            table = dataset.Tables[0];

            dgvUsers.DataSource = table;
            dgvUsers.Columns[0].Visible = false;
}

When I go to debug mode and type in two words, command.Parameters shows it has 2 parameters, but it cracks nevertheless. Any insights what is wrong?

Thanks!

== EDIT ==

I get this type of

SqlException: Incorrect syntax near 'userUsername'

Print the command just before executing it and then try executing it manually. This usually highlights syntax problems with SQL commands.

I have yet to fully understand your code, but at first sight I say:
You need parenthesis around your command text and you need to add the OR logical operator

command.CommandText += String.Format(" (userUsername LIKE @{0} OR userName LIKE @{0} OR userSurname LIKE @{0}) OR ", id); 

of course exiting from the loop you need to remove the final OR

command.CommandText = command.CommandText.Substring(0, command.CommandText.Length - 4);

I will try to rewrite your code using a simple string

string sqlText = "SELECT * FROM tbl_Users WHERE userActive = 1"; 
if (!String.Empty.Equals(tboxInputUsers.Text)) 
{ 
    // It's important to add an open parenthesis here to get a correct logic
    // All activeusers with names like words
    sqlText += " AND ("; 
    string[] words = tboxInputUsers.Text.Split(' '); 
    string id = "id"; 

    foreach (string word in words) 
    { 
        id += "a"; 
        sqlText += String.Format(" (userUsername LIKE @{0} OR " + 
                                   "userName LIKE @{0} OR " + 
                                   "userSurname LIKE @{0}) OR ", id); 
        command.Parameters.AddWithValue(String.Format("@{0}", id), word); 
    } 
    // We are sure that there is at least one word, so we can  remove the excess OR and close
    // the opening parenthesis following the AND
    sqlText = sqlText(0, sqlText.Length - 4);
    sqlText += ")";
}
command.CommandText = sqlText;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM