0

我试图在两个表中找到匹配项。首先我将比较电话号码,然后是姓氏等。我将在新表中插入匹配项。

我的问题首先是如果我直接在 SQLServer 或我的 .net 程序中执行它会更快更好吗?

如果 SQL 更好,我需要一些帮助;

我想检查匹配表中是否存在该记录,如果存在,则只应修改此记录以指定存在其他匹配项。

我可以为每种类型的匹配做一个单独的插入和修改查询。我只是想知道是否有更好的方法。

我尝试了合并,它可以插入,但是在修改时它给了我一个错误,请参见下文。

MERGE Matches AS M
USING (SELECT DOE.REG, sl.id FROM DOE INNER JOIN SL ON DOE.TEL = sl.phone) AS DOE
On M.doeid = DOE.reg
WHEN MATCHED THEN 
UPDATE SET m.Phonematch = 1, datemodified = getdate()
WHEN NOT MATCHED THEN
INSERT(DoeID, SatmarID, PhoneMatch , Verified, DateCreated)
VALUES(DOE.REG, id, 1, (SELECT ID FROM MatchStatus where Status = 'Not Verified'), GETDATE());

错误:

Msg 8672, Level 16, State 1, Line 1
The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.
4

1 回答 1

2

您正在寻找合并

我将用一个例子来解释它

示例DDL

CREATE TABLE Employee
(
   EmployeeID INTEGER PRIMARY KEY,
   EmployeeName VARCHAR(15)
)


CREATE TABLE EmployeeSalary
(
    EmployeeID INTEGER ,
    EmployeeSalary INTEGER
)

员工 DML 示例

INSERT INTO Employee
VALUES(1,'SMITH')
INSERT INTO Employee
VALUES(2,'ALLEN')
INSERT INTO Employee
VALUES(3,'JONES')
INSERT INTO Employee
VALUES(4,'MARTIN')
INSERT INTO Employee
VALUES(5,'JAMES')

EmployeeDetails 的示例 DML

INSERT INTO EmployeeSalary
VALUES(1,23000)
INSERT INTO EmployeeSalary
VALUES(2,25500)
INSERT INTO EmployeeSalary
VALUES(3,20000)

合并查询

MERGE EmployeeSalary AS stm
USING (SELECT EmployeeID,EmployeeName FROM Employee) AS sd
ON stm.EmployeeID = sd.EmployeeID
WHEN MATCHED THEN UPDATE SET stm.EmployeeSalary = stm.EmployeeSalary + 12
WHEN NOT MATCHED THEN
INSERT(EmployeeID,EmployeeSalary)
VALUES(sd.EmployeeID,25000);

参考

第一参考

第二参考

第三参考

第四参考

于 2012-07-15T06:57:47.560 回答