Match 2 tables - then insert or modify to new table

霸气de小男生 提交于 2019-12-25 05:24:13

问题


I'm trying to find matches within two tables. first I'll compare the phone number then the last name etc. I'll insert the matches in a new table.

My question is first if it'll be faster and better if I do it directly in SQLServer or in my .net program?

If SQL is better I need some help;

I want to check if that record exist in the match table, if it does it should only modify this record t specify that there's an other match.

I could do a separate insert and modify query for each type of match. I just wonder if there's a nicer way of doing it.

I tried the merge, it worked to insert but on modify it gives me an error, please see below.

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());

Error:

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.

回答1:


You are looking for Merge

I will explain it using an example

Sample DDL

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


CREATE TABLE EmployeeSalary
(
    EmployeeID INTEGER ,
    EmployeeSalary INTEGER
)

Sample DML For Employee

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')

Sample DML For EmployeeDetails

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

Merge Query

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);

References

First Reference

Second Reference

Third Reference

Fourth Reference



来源:https://stackoverflow.com/questions/11489071/match-2-tables-then-insert-or-modify-to-new-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!