I have this join:
UPDATE Table_Name
SET Change = isnull(tab2.Value,0) - tab1.Value
FROM
(SELECT Date,ID,ID,FileName,Value FROM Table_Name WHERE FileName = 'x' AND Date = '2012-05-17') tab1
LEFT OUTER JOIN
(SELECT Date,ID,TradeID,FileName,Value FROM Table_Name WHERE FileName = 'x' AND Date = '2012-05-18') tab2
ON tab1.FileName = tab2.FileName AND
tab1.ID = tab2.ID AND
tab1.ID = tab2.ID
As you can see, it is a left outer join. However, when I have data for May 17th and none for May 18th, the value inserted should be -17th.Value (because the general calculation is 18th.Value – 17th.Value and 18th.Value would be zero).
If I put a select statement just below the insert part (for debugging) this shows correctly, however, when I remove the SELECT statement and do the calculation in the SET part, it does not work. I end up with values for Change of null, where a match for the 18th of May could not be found.
EDIT: I should add I am unsure whether I need LEFT JOIN or LEFT OUTER JOIN. I wish to return all rows from tab1 and if it does not exist in tab2 the Change value should be -tab1.Value, as opposed to tab2.Value – tab1.Value.
DB2 doesn’t allow
UPDATEs (orDELETEs) to contain any joins in the main table-reference clause, which to my mind prevents certain types of issues. Yes, I’m aware you’re on SQL Server, which is why you’re attempting this – I just tend to write things with DB2 constraints in mind, is all.Assuming that you want to update rows for the 17th, I believe the following should work. Otherwise, please specify which rows you actually want updated.
EDIT:
Corrected errors for above.
However… from the sound of things, you may be attempting to update rows that don’t exist; specifically, the ‘result needs to entered for the 18th’. If what you’re doing is attempting to update those rows for the 18th that do exist, or insert them if they do not, you’re going to need two statements (or maybe a
MERGE? Except I don’t have them in my version, so I can’t help you with that):You MUST run them in that order.
You MUST ALSO lock the table for the combined run of both statements, have some other method to ensure that no rows containing relevant data are modified (
INSERTed,UPDATEd,DELETEd), or be able to tell which rows were not touched.If this isn’t the behavior you want, please modify your question to be more clear on what you’re trying to accomplish.