虽然' CASE WHEN'更新,其他列变为null

时间:2015-05-11 10:00:19

标签: sql-server stored-procedures case-when

我在tmy数据库中使用用户定义的表类型来通过数据表更新多个列。

所以,我编写了以下存储过程并且它运行良好。但是在更新相应列时,这会使所有其他列都为空。

我的存储过程

ALTER PROCEDURE [dbo].[UpdateAbcdItemsByVendorPrice]
      @tblItemUpdate AbcdItemsUpdate READONLY
AS
BEGIN
    SET NOCOUNT ON;

    MERGE INTO AbcdItems abcdTable
    USING @tblItemUpdate tempTable
    ON abcdTable.ItemPartNumber = tempTable.ItemPartNumber
    WHEN MATCHED THEN
    UPDATE SET
        abcdTable.InpostPrice = CASE WHEN tempTable.VendorName = 'Inpost' THEN tempTable.Price END,
        abcdTable.InpostUpdatedDate = CASE WHEN tempTable.VendorName = 'Inpost' THEN GETUTCDATE() END,
        abcdTable.InpostAbsoluteItem = CASE WHEN tempTable.VendorName = 'Inpost' THEN 0 END,

        abcdTable.HRCPrice = CASE WHEN tempTable.VendorName = 'HRC' THEN tempTable.Price END,
        abcdTable.HRCUpdatedDate = CASE WHEN tempTable.VendorName = 'HRC' THEN GETUTCDATE() END,
        abcdTable.HRCAbsoluteItem = CASE WHEN tempTable.VendorName = 'HRC' THEN 0 END,

        abcdTable.AnnecyPrice = CASE WHEN tempTable.VendorName = 'Annecy' THEN tempTable.Price END,
        abcdTable.AnnecyUpdatedDate = CASE WHEN tempTable.VendorName = 'Annecy' THEN GETUTCDATE() END,
        abcdTable.AnnecyAbsoluteItem = CASE WHEN tempTable.VendorName = 'Annecy' THEN 0 END,

        abcdTable.SydneyPrice = CASE WHEN tempTable.VendorName = 'Sydney' THEN tempTable.Price END,
        abcdTable.SydneyUpdatedDate = CASE WHEN tempTable.VendorName = 'Sydney' THEN GETUTCDATE() END,
        abcdTable.SydneyAbsoluteItem = CASE WHEN tempTable.VendorName = 'Sydney' THEN 0 END;
END

在执行此查询之前我的表格为' Inpost':

InpostPrice    HRCPrice    ...
0              0           ...

为' Inpost'执行此查询后的表格:

InpostPrice    HRCPrice    ...
213.57         NULL        ...

为什么HRCPrice变为空?对不起英语不好。帮助我!

3 个答案:

答案 0 :(得分:1)

您需要在else声明中添加case部分。

UPDATE SET
        abcdTable.InpostPrice = CASE WHEN tempTable.VendorName = 'Inpost' THEN tempTable.Price 
                                ELSE abcdTable.InpostPrice  END,
        abcdTable.InpostUpdatedDate = CASE WHEN tempTable.VendorName = 'Inpost' THEN GETUTCDATE() 
                                      ELSE abcdTable.InpostUpdatedDate END,
        abcdTable.InpostAbsoluteItem = CASE WHEN tempTable.VendorName = 'Inpost' THEN 0 
                                       ELSE abcdTable.InpostAbsoluteItem END,
......

答案 1 :(得分:1)

因为每个列都是无条件更新的,所以case语句将默认为null。将当前值作为默认值:

     abcdTable.InpostPrice = CASE WHEN tempTable.VendorName = 'Inpost' THEN tempTable.Price 
else abcdTable.InpostPrice
END,

答案 2 :(得分:0)

您正在分配NULL,因为ELSE中没有CASE。我假设您想要使用旧值:

UPDATE SET
    abcdTable.InpostPrice = CASE WHEN tempTable.VendorName = 'Inpost'
                             THEN tempTable.Price 
                             ELSE abcdTable.InpostPrice END,
   .....

来自documentation

  

ELSE else_result_expression:如果没有比较操作的计算结果为TRUE,则返回表达式。 如果省略此参数   并且没有比较操作评估为TRUE,CASE返回NULL