日期:2014-05-17 浏览次数:20579 次
INSERT INTO tbC(id,value,GUID)
SELECT t1.id,ABS(ISNULL(t1.VALUE,0)-ISNULL(t2.VALUE,0) AS VALUE, NEWID()
FROM tbA t1
INNER JOIN tbB t2 ON t1.id=t2.id AND ISNULL(t1.VALUE,0)<>ISNULL(t2.VALUE,0)
WHERE NOT EXISTS(SELECT 1 FROM tbC WHERE id=t1.id)
--C表已经存在的ID,则更新
UPDATE C
SET C.VALUE = ABS(ISNULL(a.VALUE, 0) - ISNULL(b.VALUE, 0)),
gid = NEWID()
FROM 表A a
INNER JOIN 表b b
ON a.id = b.id
INNER JOIN 表c C
ON a.id = c.id
WHERE ISNULL(a.VALUE, 0) <> ISNULL(b.VALUE, 0)
AND NOT EXISTS
(
SELECT 1
FROM dbo.表c C
WHERE c.id = a.id
)
--C表不存在的ID,则插入
INSERT INTO 表c(id, value, gid)
SELECT
a.id,
ABS(ISNULL(a.VALUE, 0) - ISNULL(b.VALUE, 0)),
NEWID()
FROM 表A a
INNER JOIN 表b b
ON a.id = b.id
WHERE ISNULL(a.VALUE, 0) <> ISNULL(b.VALUE, 0)
AND NOT EXISTS
(
SELECT 1
FROM dbo.表c C
WHERE c.id = a.id
)
--如果是SQL SERVER 2008,还可以用MERGER语法来实现