不同数据库之间不匹配的记录

时间:2015-03-09 02:17:09

标签: sql sql-server sql-server-2008

我有以下查询,显示那些与另一个系统没有完全匹配的客户端:

select *
from CacheClients
Left Join CacheClientsOtherSystem on 
CacheClients.[Client Number] = CacheClientsOtherSystem.Resident and 
CacheClients.[First Name] = CacheClientsOtherSystem.[First name] and 
CacheClients.[Last Name] = CacheClientsOtherSystem.[Last name] and 
CacheClients.[DOB] = CacheClientsOtherSystem.[Date of Birth] and 
CacheClients.[Street Address] = CacheClientsOtherSystem.[Street name] and 
CacheClients.[Post Code] = CacheClientsOtherSystem.[Postcode] and
CacheClients.[Suburb] = CacheClientsOtherSystem.[City/Suburb] and 
CacheClients.[State] = CacheClientsOtherSystem.[State] and
CacheClients.[Export Code]  = CacheClientsOtherSystem.[Facility No] and
CacheClients.[Funding ID] = CacheClientsOtherSystem.[Accomodation History   No] and
CacheClients.[Export Code] = CacheClientsOtherSystem.[Facility No]  and
CacheClients.[Client Status] = CacheClientsOtherSystem.[Archived]
where [Export Code] = '420022' --412030
and ([Latest End Date] is null or [Latest End Date] > Convert(Date, GetDate()))

我需要解决的问题是有一个Message列,它列出了每个行不匹配的内容,即“DOB,Post Code,State上不匹配”作为示例。

我想知道是否有人有任何聪明的想法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

如果您在clientnumber上匹配且clientnumber在两个表中都是唯一的,那么您可以使用join来获取匹配的记录。 case语句可以识别列匹配的时间。以下是基本逻辑(尽管这不考虑NULL值):

select cc.clientnumber,
       stuff((case when cc.[First Name] = ccos.[First Name] then '' else ',First Name'
              end) +
             (case when cc.[Last Name] = ccos.[Last Name] then '' else ',Last Name'
              end) +
             . . .
             , 1, 1, '')
from CacheClients cc join
     CacheClientsOtherSystem ccos
     on cc.clientnumber = ccos.clientnumber;