将列值与相应的主表值匹配的有效方法

时间:2013-05-14 19:12:40

标签: sql-server sql-server-2008

我正在存储过程中导入Excel数据并将记录存储在临时表中。我想验证几个列的值以及主表中的相应值。

我在这个临时表中添加了一个列,即:Status,它将NULL或SKIP保存为值。

例如,临时表包含一列,即Location。客户向我们发送预填充的Excel表格,并填写所有列。在此列上是此“位置”列。通常拼写的位置不正确。如果任何位置说新泽西州,Excel表格可能包含拼写为New Jarsey。

我有一个Location Master表,它也存储了正确的位置和ID名称。我想将临时表中的位置名称与主表中的相应位置名称相匹配。如果位置不匹配,我将状态列标记为临时表中的SKIP。

临时表中有几列需要与其对应的主表值匹配。

有没有办法以更有效,更快速的方式验证这些列值?我希望逐行匹配Locations,同样匹配其他列值。

1 个答案:

答案 0 :(得分:0)

如果我理解正确(实际显示一些测试数据和预期结果会有很大帮助),您可以使用一系列EXISTS表达式或一系列外连接。这是一个使用2个不同列的示例,每个列都有一个对应的“主表”:

-- set up test data
declare @RawData table  (Location varchar(100) not null primary key, Country varchar(100) not null, Status char(4) null)
declare @LocationMaster table (Location varchar(100) not null primary key)
declare @CountryMaster table (Country varchar(100) not null primary key)

insert into @RawData (Location, Country) values ('New Jersey', 'USA'), ('New Jarsey', 'USA'), ('New York', 'USAA'), ('New Yoik', 'United States')
insert into @LocationMaster (Location) values ('New Jersey'), ('New York')
insert into @CountryMaster (Country) values ('USA')

-- option 1: EXISTS

update @RawData
set Status = 'SKIP'
from @RawData r
where 
    not exists (select * from @LocationMaster where Location = r.Location)
    or not exists (select * from @CountryMaster where Country = r.Country)

select * from @RawData

-- reset status
update @RawData set Status = null

-- option 2: OUTER JOIN

update @RawData
set Status = 'SKIP'
from 
    @RawData r
    left outer join @LocationMaster lm on lm.Location = r.Location
    left outer join @CountryMaster cm on cm.Country = r.Country
where
    lm.Location is null 
    or cm.Country is null

select * from @RawData

您可以在SSMS中分析这两个计划,以确定哪个计划对您的数据集更有效。