SQL server join issue

怎甘沉沦 提交于 2019-12-13 15:16:48

问题


i have the following statement in a stored procedure that is returning strange results. Given two columns where one (RL) is less than 0 e.g -2, it should add 2 to another column (HD). If the negative value was -8 it should add 8 to the HD column.

In a test ive just done, the RL column had 0 and HD was 2. I changed the RL to -2 and run the code. I was EXPECTING : RL = 0 and HD = 4. INSTEAD the RESULT was RL = 0 and HD = 5.

I think the problem is due to the presence of the join. How would i write this to replace the join with a WHERE clause please.

UPDATE P
SET P.HD = P.HD + P.RL
    ,P.RL = 0
FROM Products P
INNER JOIN (
    SELECT id
        ,RL
    FROM Products
    WHERE id IN (
            SELECT ProductID
            FROM OrderDetails
            WHERE OrderID = @OrderId
            )
        AND RL < 0
    ) Q ON P.ID = Q.id

cheers


回答1:


Try this one -

UPDATE Products
SET HD = HD + RL,
    RL = 0
FROM P
WHERE RL < 0
    AND ID IN (
            SELECT ProductID
            FROM dbo.OrderDetails
            WHERE OrderID = @OrderId
        )

Small check -

DECLARE @t TABLE (a INT, b INT)

INSERT INTO @t (a, b)
VALUES (1, 2)

UPDATE @t
SET a = b, b = 0

SELECT * FROM @t


来源:https://stackoverflow.com/questions/34946367/sql-server-join-issue

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