• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

SQL noob question

professor1942

Senior member
I have a table in a database which has one field I need to update for all instances. My problem is the value of the field will be derived from other another field plus fields in two other tables, eg.
-----------------------------------------------------------
Table A contains:

Table B + Table C PK's (combined as PK for Table A)
quantity (int)
total_price (money) - this is the one that needs to be updated

Table B contains:
unit_price (money)

Table C contains:
shipping_charge (money)

-----------------------------------------------------------

total_price will be (quantity from Table A * unit_price from Table B) + shipping_charge from Table C. No problem for a SELECT statement, but how in hell do I UPDATE each total_price field with the calculations?

TIA


BTW I am using MS SQL Server 2005.

 
I don't know MS SQL, but I know MYSQL. I think you would just do a select of each option and then use that for the update?
UPDATE TableA SET TableA_Value = ((SELECT quantity FROM TableA...) * (SELECT price FROM TableB) + (SELECT shipping_cost FROM TableC)) WHERE PK = ...
 
You can join the tables just like you would in a select statement, or you can use a subquery.

Update tableA
set total_price = tableA.quantity * tableB.Unit_price + tableC.Shipping_charge
from tableA, TableB, TableC
where tableA.whateverykey = tableB.whateverkey
and tableA.whateverKey = tableC.whateverkey

I'm not sure if you can use the tableA join tableB on tableA.key = tableB.Key syntax or not. For some reason, the sql examples I see use the oracle style join syntax.
 
I can't test this here, so don't quote me...

UPDATE TableB SET TotalPrice =
SELECT ((TableA.Quantity * TableB.UnitPrice) + TableC.Shipping))
WHERE TableA.ProdID = TableB.ProdID AND TableC.ProdID = TableB.ProdID

You probably need another AND in there to grab the right row in TableB, which is probably something like order id? If not, then I think something is wrong with your scheme and you might want to post it so we can look at it.

Like I said, can't test this here, but something like that should work since you can perform general arithmetic on column values in a SELECT.

But I would really write a stored procedure for this.

[Yep, as the previous two posters said while I was typing 🙂]
 
Back
Top