computertim — 2011-03-24T11:54:01-04:00 — #1
I have an application with a parent/child relationship, both records are in the same table. I'm trying to write a MSSQL script to run nightly to make an update to the cost of the child. So my table is something like this (simple form):
ID| UPC | DESCRIPTION | COST | PRICE | PARENT_ID | PARENT QTY
1 | 123 | 6PK BEER | 6.00 | 8.00 | <NULL> | <NULL>
2 | 345 | SINGLE BEER | 1.00 | 2.00 | 1 | 6
My application is setup to update the cost of the master pack (the 6pk in this case) but the cost update doesn't roll down to the child. The formula would be Cost = 6/6, but I'm struggling with how to write the script.
I was thinking an inner join but can't seem to formulate the syntax. Any ideas?
fatbat — 2011-03-25T09:49:27-04:00 — #2
Assuming that your table is called 'tblStock', this should do it;
SET A.COST = B.COST/A.PARENT_QTY
FROM tblStock AS A
INNER JOIN tblStock AS B ON A.PARENT_ID = B.ID
computertim — 2011-03-25T11:34:15-04:00 — #3
Works perfectly. Thanks much!
fatbat — 2011-03-25T12:48:51-04:00 — #4
I guess you should include a check to make sure you're not trying to divide by zero, just to be on the safe side.
computertim — 2011-03-25T15:08:03-04:00 — #5