我的光标可以被其他方法取代吗?

时间:2014-03-09 22:33:18

标签: sql sql-server tsql

我正在进行一项任务,我必须在两个表中比较近50万行数据。 表的结构类似,数据也是如此(ID列大约99%匹配,但我需要比较其余列,大约15列)

例如,在表A中,空值由“N / A”表示,但在表B中,它只是空值。表A中的布尔列显示为' True'并且'错误'但是' 0' 0和' 1'在表B中。

我接近这个问题的方法是编写一个游标,它将逐行处理表A中的数据,并使用' IF EXISTS'进行比较。

如果所有数据都匹配,那么我将该行插入一个名为“匹配”的表中。如果数据不匹配,则插入其他名为“无与伦比”的表格

我的光标目前仍在运行,现在已经快3个小时了。

想知道是否有其他方法可以解决我的问题。

所以这是两个表的样本

create table A (ID int, Name varchar(20), Address varchar(40), City varchar(20), 
State varchar(20), Country varchar(20))
create table B (ID int, Name varchar(20), Address varchar(40), City varchar(20), 
State varchar(20), Country varchar(20))
Insert into A values(1,'Daniel','12345 marion way', 'Sunnyvale', 'CA', 'USA'),
(2,'Chloe','38660 Hastings Street', 'Fremont', 'CA', 'USA'), 
(3,'Charles', '24980 willimet way', 'Hayward', 'CA', 'USA'),
(4,'Tommy', '98765 washington street', 'Fremont', 'CA', 'USA')
Insert into B values(1,'Daniel','12345 marion way', 'Santa Clara', 'CA', 'USA'),
(2,'Chloe',38660 Hastings Street', 'Fremont', 'CA', 'USA'), 
(3,'Charles', '24980 willimet way', 'Hayward', 'CA', 'USA')

所以我为表A创建了一个游标,并尝试匹配表B,ID:1城市值错误,ID:4不存在于表B中。

Declare compare Cursor for 
    Select ID, Name, Address, City, State, Country from A
Open Compare
    Declare @ID int, @Name varchar(20), @Address varchar(50), @City varchar(20)
    ,@State varchar(20), @Country varchar(20)
Fetch next from compare into @ID, @Name, @Address, @City, @State, @Country
While @@Fetch_Status = 0
Begin
    Begin
    IF EXISTS (Select ID, Name, Address, City, State, Country from B
               where ID = @ID and Name = @Name and Address = @Address and
               City = @City and State = @State and Country = @country)
    Insert into Match values (@ID, @Name, @Address, @City, @State, @Country)
    Else
    Insert into Unmatched values(@ID, @Name, @Address, @City, @State, @Country)
    End
Fetch Next from compare into @ID, @Name, @Address, @City, @State, @Country
End
Close compare
deallocate compare 

1 个答案:

答案 0 :(得分:1)

为什么要在游标中逐行执行此操作?为什么不直接执行批量插入?

INSERT INTO Match (ID, Name, Address, City, State, Country)
SELECT ID, Name, Address, City, State, Country
FROM A
WHERE Exists (
    SELECT 1 FROM B WHERE 
    A.ID = B.ID and A.Name = B.Name and A.Address = B.Address and
           A.City = B.City and A.State = B.State and A.Country = B.country
    )


INSERT INTO UnMatched (ID, Name, Address, City, State, Country)
SELECT ID, Name, Address, City, State, Country
FROM A
WHERE NOT EXISTS (
    SELECT 1 FROM B WHERE 
    A.ID = B.ID and A.Name = B.Name and A.Address = B.Address and
           A.City = B.City and A.State = B.State and A.Country = B.country
    )

您的匹配逻辑需要改进,但丢失光标至少会让解决方案在第一次迭代时执行。如果可能,请确保索引字段。