我一直在用来自CTE的数据更新Persons2的整行(让我们说)。什么是最简单的方法来执行此操作?
我正在使用的代码如下,我从CTE获取了一些使用Persons1
和Persons2
表的数据。获得结果后,我想将整个数据(行)插入Persons2
(不需要Persons2中的先前数据)。
案例1:如果我这样做,重复数据会添加到Persons2(它只是插入新数据而不执行删除,删除命令不允许我在这里)
您的解决方案对我来说最有价值,谢谢。
;WITH tabtemp AS
(
SELECT
COALESCE(p1.id, p2.id) AS ID,
COALESCE(p1.name, p2.name) AS Name,
COALESCE(p1.phnumber, p2.phnumber) AS PHNumber,
CASE
WHEN p1.name IS NULL THEN 0
ELSE 1
END AS IsActive
FROM
Persons1 p1
FULL JOIN
Persons2 p2 ON p1.name = p2.name
AND p1.phnumber = p2.phnumber)
INSERT INTO Persons2 (ID, Name, PHNumber, IsActive)
SELECT *
FROM tabtemp

答案 0 :(得分:0)
实际上,您需要在P1中添加尚未包含在p2中的新数据。 添加Where条件自爆:
;WITH tabtemp AS (SELECT
COALESCE(p1.id, p2.id) AS ID,
COALESCE(p1.name, p2.name) AS Name,
COALESCE(p1.phnumber, p2.phnumber) AS PHNumber,
CASE WHEN p1.name IS NULL THEN 0 ELSE 1 END AS IsActive
FROM Persons1 p1
FULL JOIN persons2 p2
ON p1.name = p2.name
AND p1.phnumber = p2.phnumber)
Insert Into Persons2(ID,Name,PHNumber,IsActive)
SELECT * FROM tab temp
where p2.id is null -- Added
您也可以使用MERGE声明。