title: T-SQL Algorithm to Encode Unsafe HTML Characters as HTML Character Entity References
body: <p>I need to create an <strong>after insert trigger</strong> in my SQL Server 2008 R2 database.</p>
  
  <p>The trigger needs to take some fields from INSERTED, process them and put them in different fields in the same row which was inserted.</p>
  
  <p>Re. processing:</p>
  
  <p>I need help coming up with an <strong>algorithm</strong> in T-SQL code, which <strong>encodes unsafe HTML characters</strong> such as &lt; (less than) and > (greater than) as <strong>HTML character references</strong>.</p>
  
  <p>Ideally, I would like to do this in a manner similar to ASP.NET Server.HtmlEncode(myUnsafeHtml), and ideally without using literals all over the place or extra tables i.e. a clever algorithm.</p>
  
  <p><strong>Just asking for help.</strong></p>
  
  <p>So in summary, the after insert trigger takes the value in <strong>UnsafeHtml column</strong>, processes it and puts it in <strong>SafeHtml column</strong> in the row which was inserted.</p>
  
  <p>Both columns are of type <strong>NVARCHAR</strong>.</p>
  
  <p>Thanks in advance.</p>
  
  <p>P.S. Having thought about it a <strong>UDF</strong> would be more appropriate which I could use in many places.</p>