Dynamic Condition Creation function
How about this?

set @sql = '(SELECT STUFF((
              SELECT space(2)+''and ''+space(2)+''B.''+name+'' = ''+''A.''+name 
              from tempdb.sys.columns 
              where object_id = object_id(''tempdb..'+quotename(@TempTableName)+''')
              FOR XML PATH ('''')),1, 5,''''))'