更新失败,订购者为

时间:2018-10-08 16:16:45

标签: sql sql-server

我正在尝试根据“项目分类帐条目”表中“源编号”字段中的最新条目更新表“项目”的字段“卖方编号”

因此,“ Source No_”最近的记录必须是“ Entry Type = 0”,“ Posting Date”且年份> = 2018

UPDATE  i
    SET i.[Vendor No_] = (
        SELECT TOP 1 [Source No_]
        FROM [MR$Item Ledger Entry] ile
        WHERE i.[No_]=ile.[Item No_] and ile.[Source No_] is not null and i.[Vendor No_] is not null
        ORDER BY ile.[Posting Date] DESC
    )
FROM [MR$Item] i

查询返回错误

Msg 515, Level 16, State 2, Line 4
Cannot insert the value NULL into column 'Vendor No_', table 'Loja-MR.dbo.MR$Item'; column does not allow nulls. UPDATE fails.

但是,如果我尝试检查“ Vendor No _”(商品编号)空条目,我没有任何条目。.同样适用于“ Source No _”(商品分类帐条目)

select * from [MR$Item]
where [MR$Item].[Vendor No_] is null

返回0行

select * from [MR$Item Ledger Entry
where [MR$Item Ledger Entry].[Source No_] is null

1 个答案:

答案 0 :(得分:0)

您没有。请改用cross apply

UPDATE  i
    SET i.[Vendor No_] = ile.[Source No_]
FROM [MR$Item] i CROSS APPLY
     (SELECT TOP 1 [Source No_]
      FROM [MR$Item Ledger Entry] ile
      WHERE i.[No_]=ile.[Item No_] and ile.[Source No_] is not null and i.[Vendor No_] is not null
     ORDER BY ile.[Posting Date] DESC
    ) ile