Search code examples
c#sqlc#-4.0parameterssqlparameter

SqlCommand parameters are not substituting correctly


private SqlCommand createSQLQuery(SqlCommand command)
{
    string[] allTheseWords;
    if (textBoxAllTheseWords.Text.Length > 0)
    {
        allTheseWords = textBoxAllTheseWords.Text.Split(' ');
        string SQLQuery = "SELECT distinct [skullbase].[dbo].[patients].[name], [skullbase].[dbo].[patients].[dos], [skullbase].[dbo].[patients].[ACC2], [SKULLbase].[dbo].[fullreport].[mrn1], [SKULLbase].[dbo].[fullreport].[ACC], [skullbase].[dbo].[fullreport].[fullreport] FROM [skullbase].[dbo].[fullreport], [skullbase].[dbo].[patients] WHERE ";
        int i = 1;
        foreach (string word in allTheseWords)
        {
            command.Parameters.Add("@word" + i.ToString(), SqlDbType.Text).Value = word;
            SQLQuery = SQLQuery + " [skullbase].[dbo].[fullreport].[fullreport] LIKE @word" + i.ToString() + " AND ";
            i++;
        }
        SQLQuery = SQLQuery + " skullbase.dbo.patients.ACC2 = skullbase.dbo.fullreport.ACC";
        command.CommandText = SQLQuery;
    }
    MessageBox.Show(command.CommandText.ToString());
    return command;
}

The above is my query. The word "word" is not being substituted for the actual value.


allTheseWords = textBoxAllTheseWords.Text.Split(' ');

Solution

  • For starters, when you quote your parameter reference in your SQL CommandText (e.g. ...[fullreport] = '@word'...) you are actually just using the literal value '@word'. It is not being interpreted as a parameterized query. To do that you would just use ...[fullreport] = @word...)

    Secondly, I do not -think- you can assign multiple parameters with the same parameter name as you are doing in the loop. Each parameter you add should have a unique name.