Search code examples
c#sql-serversyntax-errorsqldatareadersingle-quotes

How to execute sql query to match column value which contains single quote(')


My C# code to find a data row with column name CustomerAccountNumber which contains a value KKL'M"/ (single quote ' in value) return nothing

here is my C# code:

matchingid = "KKL'M\"/";
bool foundCustomer = false;
SqlConnection cnn;
connetionString = "Server=" + config.serverName + ";Database=" + config.companyName + ";Trusted_Connection=true";
cnn = new SqlConnection(connetionString);
cnn.Open();

var queryString = "SELECT CustomerAccountNumber, CustomerAccountName FROM [" + config.companyName + "].[dbo].[SLCustomerAccount] WHERE CustomerAccountNumber = @matchingAccountName";
SqlCommand command = new SqlCommand(queryString, cnn);
command.Parameters.Add(new SqlParameter("@matchingAccountName", System.Data.SqlDbType.NChar) { Value = matchingid });
using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
       foundCustomer = true;
    }
}
cnn.Close();

screenshot of the database where value contains enter image description here


Solution

  • Use parameters instead of constructing your query like that, and also put all objects that are disposable in a using.

    This example can get you on the correct way

    using (SqlConnection cnn = new SqlConnection(connetionString))
    {
        cnn.Open();
    
        var queryString = "SELECT CustomerAccountNumber, CustomerAccountName FROM dbo.SLCustomerAccount WHERE CustomerAccountNumber = @matchingid";
    
        using (SqlCommand command = new SqlCommand(queryString, cnn))
        {
            command.Parameters.Add("@matchingID", SqlDbType.VarChar, 50).Value = matchingID;  // specify correct length
    
            using (SqlDataReader reader = command.ExecuteReader())
            {
                 while (reader.Read())
                 {
                     foundCustomer = true;
                 }
            }
        }
    }
    

    EDIT

    As mentioned in the comments, you cant parameterize the company name, but it is not needed in your query so just leave it out.
    The use of 3 part names will get deprecated, read all about that here

    I would also like to mention that by using parameters, you don't have to worry about sql injection anymore. Not sure if your case has a problem with that, but it's best to always use parameters because you never have problems with formats, quotes ', and whatever you can find in your values, and you be safe against sql injection

    EDIT 2

    As also mentioned by @NicholasHunter, be careful with

    matchingid = "kkl'm\"/n";
    

    If a string can contain special characters, you can either escape them all, or simply use this

    matchingid = @"kkl'm\"/n";