Search code examples
sqlsql-serversql-server-2014

SQL string replace based on WHERE clause


I have a memo field which may contain & and the HTML equivalent &. I need to write a script to ensure that all instances of ampersand are the HTML equivalent. Have the below script but the WHERE clause does not seem to factor the individual instances (strings) of & in the memo field, just the field as a whole... Any ideas on how to accomplish this? Thanks.

 UPDATE 
    STOCKMEM
 SET 
    INETFDESC = CAST(REPLACE(CAST(INETFDESC as NVarchar(MAX)),'&','&') AS NText)
 WHERE 
    INETFDESC LIKE '%&%' 
    AND INETFDESC NOT LIKE '%&%'

Solution

  • Try this instead:

     UPDATE STOCKMEM
     SET INETFDESC = CAST(
                          REPLACE(
                                  REPLACE(
                                          CAST(INETFDESC as NVarchar(MAX))
                                  ,'&','&')
                          , '&', ,'&')AS NText)
     WHERE INETFDESC LIKE '%&[^amp;]%' 
    

    The first replace will change & to &, and the second will replace all & back to &.

    BTW, Please note that NText data type is depricated and you should convert it to nvarchar(max). From MSDN:

    IMPORTANT! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.