我正在尝试在两个表中找到匹配项。首先,我将比较电话号码,然后比较姓氏等。我会将匹配项插入新表中。
我的问题是,如果我直接在SQLServer或我的.net程序中执行它会更快更好吗?
如果SQL更好,我需要一些帮助;
我想检查匹配表中是否存在该记录,如果存在,则只应修改此记录t指定还有其他匹配。
我可以为每种匹配类型单独插入和修改查询。我只是想知道是否有更好的方法。
我尝试了合并,它可以插入但是在修改它会给我一个错误,请看下面。
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.
答案 0 :(得分:2)
您正在寻找 Merge
我将使用示例
解释它示例 DDL
CREATE TABLE Employee
(
EmployeeID INTEGER PRIMARY KEY,
EmployeeName VARCHAR(15)
)
CREATE TABLE EmployeeSalary
(
EmployeeID INTEGER ,
EmployeeSalary INTEGER
)
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')
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);
<强>参考强>
<强> Second Reference 强>
<强> Third Reference 强>
<强> Fourth Reference 强>