Question

I use this dynamicSQL piece of code.

Problem is, the @ID_USER and @SEARCH stays raw in the SQL query when I check the cmd.CommandText value at runtime, it reads

"SELECT Comment FROM Comments WHERE UserId = @ID_USER AND Comment like '% @SEARCH %'" 

so the syntax is correct and the cmd.Parameters ResultView .SqlValuein VS2012 gives me the correct input values for @USER_ID and @SEARCH Thanks.

 {
        List<string> searchResults = new List<string>();

        //Get current user from default membership provider
        MembershipUser user = Membership.Provider.GetUser(HttpContext.User.Identity.Name, true);
        if (user != null)
        {
            if (!string.IsNullOrEmpty(searchData))
            {
               // SqlCommand cmd = new SqlCommand("Select Comment from Comments where UserId = '" + user.ProviderUserKey + "' and Comment like '%" + searchData + "%'", _dbConnection);

                /**********************************************/
                _dbConnection.Open();

                const string QUERY =
                    @"SELECT Comment" +
                    @" FROM Comments" +
                    @" WHERE UserId = @ID_USER" +
                    @" AND Comment like '% @SEARCH %'";


                var cmd = new SqlCommand(QUERY, _dbConnection);


                    cmd.Parameters.AddWithValue("@ID_USER", user.ProviderUserKey.ToString());
                    cmd.Parameters.AddWithValue("@SEARCH", searchData.ToString());

                    /**********************************************/
                SqlDataReader rd = cmd.ExecuteReader();


                while (rd.Read())
                {
                    searchResults.Add(rd.GetString(0));
                }

                rd.Close();
                _dbConnection.Close();
            }
        }
        return View(searchResults);
    }
Was it helpful?

Solution

No, it is correct that the parameters remain in the command text.

This is because what is actually passed to the server is something like the below:

exec sp_executesql N'SELECT Comment FROM Comments WHERE UserId = @ID_USER AND Comment like ''% + @SEARCH %''',
                    N'@ID_USER int,@SEARCH nvarchar(max)',
                    @ID_USER=1,
                    @SEARCH=N'some search text';

So your parameters remain in place even when it is passed to the server. This is why you can still see them in your command text.

As an aside your query will not work as expected, in this line:

AND Comment like '% @SEARCH %'

You are looking for where Comment actually contains "@Search" rather than the value assigned to the parameter. What you need is:

AND Comment like '%' + @SEARCH + '%'

Another, slightly unrelated point is that there is no need to, nor is it useful to reuse SqlConnections. Define a new one for each connection. .NET is smart enough to reuse connections by pooling them, don't reinvent the wheel. Also use using blocks to ensure your disposable class are disposed of:

So I would make your whole reader block as follows:

string sql = "SELECT Comment FROM Comments WHERE UserID = @ID_USER AND Comment LIKE '%' + @Search + '%'";
using (var connection = new SqlConnection(YourConnectionString))
using (var command = new SqlCommand(sql, connection))
{
    command.Parameters.AddWithValue("@ID_USER", user.ProviderUserKey.ToString());
    command.Parameters.AddWithValue("@SEARCH", searchData.ToString());
    connection.Open();

    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            searchResults.Add(rd.GetString(0));
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top