简体   繁体   中英

Dynamic T-sql compare column values

I need to compare Column A to Column B and so on...and flag out differences for eg

SELECT OL.ID
 ,OFT.ID
 ,CASE WHEN OL.ID <> OFT.ID THEN 'FALSE'
      ELSE 'TRUE'
  END AS DIFF_Flag
 ,OL.Fname
 ,OFT.Fname
 ,CASE WHEN OL.Fname <> OFT.Fname THEN 'FALSE'
      ELSE 'TRUE'
  END AS DIFF_Flag

FROM TABLE1 OL
INNER JOIN TABLE2 OFT ON OL.ID= OFT.ID

There are too many columns n tbles to be done this way...

My dynamic SQL query ->

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 + '<> '+@Table2ColumnList +' THEN '+'''FALSE'''
 +' ELSE '+'''TRUE'''
 +' END AS DIFF_flag'
 + ' FROM TABLE a
INNER JOIN TABLE b ON a.ID=b.ID'

How can I recursively loop through all the columns..

sample O/P

o / p

My problem is something similar to ref

I'm using SQL Server 2008

select 'SELECT '''' as dummy, ';

select replace(
    ', case when coalesce(t1.%c, ''!@#'') <> coalesce(t2.%c, ''!@#'') then ''ROW '' + t1.ID + '': Mismatch in %c ('' + coalesce(t1.%c, ''NULL'') + '', '' + coalesce(t2.%c, ''NULL'') + '')'' else null end as Compare%c',
    '%c',
    COLUMN_NAME
    )
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'TABLE1' AND COLUMN_NAME <> 'ID'
order by ORDINAL_POSITION;

select 'FROM Table1 as t1 INNER JOIN Table2 as t2 on t2.ID = t1.ID WHERE 0 = 1';

select replace(
    ' OR coalesce(t1.%c, ''!@#'') <> coalesce(t2.%c, ''!@#'')',
    '%c',
    COLUMN_NAME
    )
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'TABLE1' AND COLUMN_NAME <> 'ID'
order by ORDINAL_POSITION;

You can create the query dynamically. Something like this will get you a list of expressions for either filtering or generating output.

If you need to do this dynamically in code you'd either have to use one of the string concatenation tricks or use a cursor.

For a one-time thing and saving some typing you'd just grab the results and build another query from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM