加入2个表并用匹配的列数据替换坏数据

时间:2013-05-06 18:51:48

标签: sql

我有一个要求,我需要在一个表中匹配一个字符串,并获得该表的匹配记录。请参阅下文。

表A

Column Address      
12333
W.Main  
street      
Apt     
402     

表B

Column Bad value , good value
Street              St

当我同时加入左外连接表时,我希望表A中的Street在表B中查找之后被表B中的Mainvalue替换。

截至目前,左连接显示所有空值并添加一组额外的列,主输出应如下所示。 然后将下面的列数据集中在一行中。 像12333 W.Main St Apt 402

12333    W.Main    圣    易于    402

到目前为止,我能够做到这一点。

   declare @id int
   declare @value varchar(1000)

   --select dbo.fnNumbersFromStr ('Richmond Plaza - Hwy. 74 E.')
   IF OBJECT_ID('TempDB..#TEMP') IS NOT NULL
    BEGIN
        DROP TABLE #TEMP
    END 

   create table #Temp 
   (ID  int,
    Value varchar(max))

   insert into #Temp 
   SELECT * from MASTER.dbo.SplitWords('12333 W.Main street Apt 402')

   select * from #Temp

   select * from dbo.tStreetNameAbbrevations


   SELECT A.VALUE,B.strLookUpValue FROM #Temp AS A
   LEFT JOIN tStreetNameAbbrevations AS B
   ON A.Value = B.strBadValue
   where B.strLookupvalue is not null

    UPDATE #Temp
    set value = (SELECT B.strLookUpValue FROM #Temp AS A
    LEFT JOIN tStreetNameAbbrevations AS B
    ON A.Value = B.strBadValue
    where B.strLookupvalue is not null)
    where value in (SELECT A.VALUE FROM #Temp AS A
    LEFT JOIN tStreetNameAbbrevations AS B
    ON A.Value = B.strBadValue
    where B.strLookupvalue is not null)

1 个答案:

答案 0 :(得分:0)

将您的UPDATE语句更改为:

UPDATE #Temp
    SET Value = (SELECT strLookupValue 
                 FROM tStreetNameAbbrevations 
                 WHERE tStreetNameAbbrevations.strBadValue = #Temp.Value)
WHERE #Temp.ID IN (SELECT ID 
                   FROM #Temp 
                       INNER JOIN tStreetNameAbbrevations ON
                           tStreetNameAbbrevations.strBadValue = #Temp.Value)