title: Dynamic T-sql compare column values
body: <p>I need to compare Column A to Column B and so on...and flag out differences
   for e.g.</p>
  
  <pre><code>SELECT OL.ID
   ,OFT.ID
   ,CASE WHEN OL.ID &lt;&gt; OFT.ID THEN 'FALSE'
        ELSE 'TRUE'
    END AS DIFF_Flag
   ,OL.Fname
   ,OFT.Fname
   ,CASE WHEN OL.Fname &lt;&gt; OFT.Fname THEN 'FALSE'
        ELSE 'TRUE'
    END AS DIFF_Flag
  
  FROM TABLE1 OL
  INNER JOIN TABLE2 OFT ON OL.ID= OFT.ID
  </code></pre>
  
  <p>There are too many columns n tbles to be done this way...</p>
  
  <p>My dynamic SQL query -></p>
  
  <pre><code>declare @Table1ColumnList varchar(1000)='a.ID, a.Fname'
  declare @Table2ColumnList varchar(1000)='b.ID, a.Fname'
  
  declare @sql nvarchar(2000) 
  
  set @sql= 'SELECT '+ @Table1ColumnList +' ,'+ @Table2ColumnList
   +', CASE WHEN ' + @Table1ColumnList + '&lt;&gt; '+@Table2ColumnList +' THEN '+'''FALSE'''
   +' ELSE '+'''TRUE'''
   +' END AS DIFF_flag'
   + ' FROM TABLE a
  INNER JOIN TABLE b ON a.ID=b.ID'
  </code></pre>
  
  <p>How can I recursively loop through all the columns.. </p>
  
  <p>sample O/P</p>
  
  <p><img src="https://i.stack.imgur.com/XHsdd.png" alt="o/p"></p>
  
  <p>My problem is something similar to <a href="https://stackoverflow.com/questions/25532098/t-sql-compare-2-columns-with-unknown-values">ref</a> </p>
  
  <p>I'm using SQL Server 2008</p>