更新临时表中的所有值都无法正常工作

时间:2014-01-05 08:41:49

标签: sql sql-server sql-server-2012

我有一个简单的产品表,

产品

ID Name Price
-----------
1  ABC  12

现在我有一个临时表正在尝试更新Products表。

DECLARE @TempProducts TABLE (
    ID int,
    Name varchar(20),
    Price varchar(20)
);

INSERT INTO @TempProducts
    VALUES (1, 'p1', NULL), (1, NULL, 123)

UPDATE [dbo].[Products]
SET Name = ISNULL(t.Name, P.Name),
    Price = ISNULL(t.Price, P.Price)
FROM [dbo].[Products] P
INNER JOIN @TempProducts t
    ON (P.ID = CAST(t.ID AS int))

但是只在产品表中更新了临时表的第一行。请注意,这是简化的大查询。请不要建议光标

1 个答案:

答案 0 :(得分:1)

编辑2:

试试这个:

DECLARE @TempProducts TABLE (
    ID int,
    Name varchar(20),
    Price varchar(20),
    ImportID INT UNIQUE
);

INSERT INTO @TempProducts VALUES (1, 'p1', NULL, 101), (1, NULL, 123,102),(1, 'abc', 1, 103),(1, NULL, 11, 104);

UPDATE [dbo].[Products]
SET Name = ISNULL(t.LastNotNullName, P.Name),
    Price = ISNULL(t.LastNotNullPrice, P.Price)
FROM [dbo].[Products] P
INNER JOIN (
    SELECT  y.ID,
            MAX(CASE WHEN y.RowNumName=1 THEn y.Name END) AS LastNotNullName,
            MAX(CASE WHEN y.RowNumPrice=1 THEn y.Price END) AS LastNotNullPrice
    FROM (
        SELECT  x.ID, x.Name, x.Price, x.ImportID,
                ROW_NUMBER() OVER(PARTITION BY x.ID ORDER BY CASE WHEN x.Name IS NOT NULL THEN x.ImportID END DESC) AS RowNumName,
                ROW_NUMBER() OVER(PARTITION BY x.ID ORDER BY CASE WHEN x.Price IS NOT NULL THEN x.ImportID END DESC) AS RowNumPrice
        FROM    @TempProducts x
    ) y
    GROUP BY y.ID
) t ON (P.ID = t.ID) -- There is not need for CAST because @TempProducts.ID is INT