title: What is the best way to save string data to SQL Server that contains single quote
body: <p>I have a C# program that needs to process data and store it in SQL Server. The issue I am having is that some of the data being saved legitimately contains a single quote. When saving the data I need to locate the items that have single quotes in them and actively replace the single quote with two single quotes together so that I don't get a truncated string.</p>
  
  <p>At present whereever I am adding data that might contain a single quote I am passing it through the following routine which I have in a static module called FSQ (Fix Single Quote), this is the routine:</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Fix Single Quote - Used to remove Double quotes from strings that would confuse Access database by replacing with Single Quotes.
  /// &lt;/summary&gt;
  /// &lt;param name="s"&gt;String text to be fixed by removing double quotes.&lt;/param&gt;
  /// &lt;returns&gt;The original string with any double-quotes removed and replaced with single quotes. If an error occurs will return an empty string.&lt;/returns&gt;
  public static string FSQ(string s)
  {
      string tmp ="";
  
      try
      {
          if (s == null)
              return "";
  
          s = s.Trim();
  
          if (s == "")
              return s;
  
          if(s.Contains("'"))
          {
              if(!s.Contains("''"))//Already been fixed previously so skip here
                  tmp = s.Replace("'", "''");
  
                  s = tmp;
          }
  
          return s;
  
  
      }
      catch (Exception ex)
      {
          PEH("FDQ", "Common Module", ex.Message);
          return "";
      }
  } //public static String FDQ(String s)
  </code></pre>
  
  <p>This works and my strings get saved OK to SQL but because there are a lot of calls to this routine, the performance sucks as the program loops through thousands of rows of data whilst it's processing.</p>
  
  <p>Is there a more efficient routine that would negate the need to call this function?  Mostly I am just building update or insert queries that contain these items. </p>
  
  <p>Any help appreciated.</p>