简体   繁体   English

动态T-sql比较列值

[英]Dynamic T-sql compare column values

I need to compare Column A to Column B and so on...and flag out differences for eg 我需要将A列与B列进行比较,依此类推...并找出例如的差异

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... 用这种方法无法完成n列的太多列...

My dynamic SQL query -> 我的动态SQL查询->

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

o / p

My problem is something similar to ref 我的问题类似于ref

I'm using SQL Server 2008 我正在使用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. 对于一次性的事情并保存一些键入内容,您只需获取结果并从中构建另一个查询即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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