使用自联接基于SQL Server中的条件进行更新

时间:2014-10-29 07:04:02

标签: sql-server

我在SQL Server 2008中有一个如下表所示。

ID| ParentID| InvID |IsIntTr|   IsTR
1 |   NULL  |     1 |  NULL |   NULL
2 |      1  |     2 |  NULL |   NULL
3 |      1  |     1 |  NULL |   NULL

我的要求是:
如果填充了ParentID 将父级的InvID与子级的InvID进行比较。如果它们已填充且值相同,则设置IsIntTr = 1且IsTr = 0。否则,设置IsIntTr = NULL且IsTr = 1

否则(即ParentID为空)

 设置IsIntTr = NULL并且IsTr = NULL

我编写了以下SQL更新查询,但是它没有按预期工作:

UPDATE child SET

IsIntTr =   
   CASE WHEN child.ParentID IS NULL THEN NULL
        WHEN child.InvID = parent.InvID AND child.ParentID IS NOT NULL
                THEN 1 ELSE NULL END,
IsTr     =  
    CASE WHEN child.ParentID IS NULL THEN NULL  
        WHEN child.InvID = parent.InvID AND child.ParentID IS NOT NULL
                THEN 0 ELSE 1 END
    from    MyTable child (NOLOCK),     
            MyTable parent (NOLOCK)

非常感谢任何帮助!

谢谢

2 个答案:

答案 0 :(得分:2)

最后你遗失了Where

试试这个:

UPDATE child SET
IsIntTr =   
   CASE WHEN child.InvID = parent.InvID THEN 1
        ELSE NULL
   END,

IsTr     =  
   CASE WHEN child.InvID = parent.InvID THEN 0
        ELSE 1
   END
from    MyTable child (NOLOCK),     
        MyTable parent (NOLOCK)
WHERE
  child.ParentId = Parent.Id

SqlFiddle

答案 1 :(得分:0)

尝试使用此

CREATE TABLE #temp
(
    ID INT IDENTITY(1,1),
    ParentID INT,
    InvID INT,
    IsIntTr INT,
    IsTR INT
)

INSERT INTO #temp
SELECT NULL, 1, NULL, NULL
UNION ALL
SELECT 1, 2, NULL, NULL
UNION ALL
SELECT 1, 1, NULL, NULL

UPDATE #temp SET #temp.IsIntTr = 
    CASE WHEN tbl.InvID_A = tbl.InvID_B THEN 1 ELSE NULL END,
    #temp.IsTR = CASE WHEN tbl.InvID_A = tbl.InvID_B THEN 0 ELSE 1 END 
FROM (SELECT A.ID, A.ParentID, A.InvID AS InvID_A, B.InvID AS InvID_B, A.IsIntTr, A.IsTR FROM #temp A
INNER Join #temp B
ON A.ParentID = B.ID) AS tbl
WHERE #temp.id = tbl.ID