Search code examples
sqlsql-servert-sqlsql-server-2012string-comparison

Compare two string char by char and highlight the different ones


I need a function that will take 2 strings and return the second one with highlighted mismatched characters with html code. For example:

dbo.function('Jack', 'jake')

will return a string:

'ja<font color=red>k</font><font color=red>e</font>'

Solution

  • Here is a working sample that you can turn into a function

    Declare @S1 varchar(max) = 'Jack'
    Declare @S2 varchar(max) = 'jake'
    
    Declare @Return varchar(max) = ''
    
    Select @Return = @Return + case when S2=S1 then S2
                           else '<font color=red>'+S2+'</font>'
                      end
     From (
            Select N
                  ,S1 = substring(@S1,N,1)
                  ,S2 = substring(@S2,N,1)
             From ( Select Top 1000 N=Row_Number() Over (Order By (Select NULL)) 
                     From master..spt_values n1, master..spt_values n2
                  ) A
             Where N<=len(@S1) or N<=len(@S2)
          ) A
     Order by N
    
    Select @Return
    

    Results

    ja<font color=red>k</font><font color=red>e</font>