I’m trying to compose an SQL statement but keep getting errors…
Here is my situation:
I have a table with sales orders and a table with item transfers.
The sales orders have an order number and an extension, where the ID itself might not be unique, but the combination of order number and extension is. The extension can be null.
The item transfer table has a reference number and sometimes a sales order number plus extension, but not always.
The reason is that sometimes items are transferred for a sales order, sometimes for other reasons. Also, a sales order can happen without the item being transferred first. One order can only have one transfer though, and vice versa.
I added a field “transref” to the sales order table so an order can be connected to a transfer, if applicable. (This info can’t be computed on-the-fly for performance reasons.) So my tables now look like this (they are actually bigger but this is the important info):
SALESORDERS
ORDERNO ORDEXT TRANSREF
1 (null) (null)
2 (null) (null)
2 a (null)
3 (null) (null)
TRANSFERS
TRANSREF ORDERNO ORDEXT
t1 1 (null)
t2 (null) (null)
t3 2 a
Now I need to get the transref code into the sales orders table so that it looks like this:
SALESORDERS
ORDERNO ORDEXT TRANSREF
1 (null) t1
2 (null) (null)
2 a t3
3 (null) (null)
I tried all kinds of statements, e.g.
UPDATE SALESORDERS
INNER JOIN TRANSFERS
ON SALESORDERS.ORDERNO = TRANSFERS.ORDERNO and (SALESORDERS.ORDEXT = TRANSFERS.ORDEXT or (SALESORDERS.ORDEXT is null and TRANSFERS.ORDEXT is null))
SET SALESORDERS.TRANSREF = TRANSFERS.TRANSREF
WHERE TRANSFERS.ORDERNO IS NOT NULL
but nothing worked so far. Can someone help me untie the knot I got in my brain after trying a dozen tutorials and answers for this?
Since you’ve called it an AS/400 several times, I’m going to assume you’re on an old version of the operating system. You probably want a correlated subselect. Something like: