I am doing data migration in SQL Server 2008 R2. I am a noob SQL server, but I know Ingres and MySql well.
I need to set the "default values" for two new fields to the "current values" from another table. Here is my first naive attempt (as I would have done in Ingra).
update rk_risk
set n_target_probability_ID = a.n_probability_ID
, n_target_consequence_ID = a.n_consequence_ID
from rk_assess a
WHERE a.n_assess_id = (
SELECT MAX(n_assess_id)
FROM rk_assess a2
WHERE a2.n_risk_id = a.n_risk_id
);
The above query is executed without errors in the future, but it sets ALL parameters n_target_probability_ID and n_target_consequence_ID to the same value ... as for the last OUTRIGHT score (as indicated to the "last assessment of THIS RISK").
The table rk_assesscontains the full history of the score records for rk_risks, and my mission is to “default” a new probability column and the consequences of the risk table on the values from the “current” (ie last) score. The column rk_assess.n_assess_idis an automatically incrementing identifier (unchanged after installation), so the maximum identifier should always be the last entry entered.
I had a search, both in google and SO, and tried several different versions of the request, but I was still stuck. Here are a couple of other epic setbacks, with links.
update rk_risk
set n_target_probability_ID = (select a.n_probability_ID from rk_assess a where a.n_assess_id = (select max(n_assess_id) from rk_assess a2 where a2.n_risk_id = a.n_risk_id) as ca)
, n_target_consequence_ID = (select a.n_consequence_ID from rk_assess a where a.n_assess_id = (select max(n_assess_id) from rk_assess a2 where a2.n_risk_id = a.n_risk_id) as ca)
;
http://stackoverflow.com/questions/6256844/sql-server-update-from-select
update r
set r.n_target_probability_ID = ca.n_probability_ID
, r.n_target_consequence_ID = ca.n_consequence_ID
from rk_risk r
join rk_assess a
on a.n_risk_id = r.n_risk_id
select r.n_risk_id
, r.n_target_probability_ID, r.n_target_consequence_ID
, ca.n_probability_ID, ca.n_consequence_ID
from rk_risk r
join rk_assess a
on a.n_risk_id = r.n_risk_id
http://stackoverflow.com/questions/4024489/sql-server-max-statement-returns-multiple-results
UPDATE rk_risk
SET n_target_probability_ID = ca.n_probability_ID
, n_target_consequence_ID = ca.n_consequence_ID
FROM ( rk_assess a
INNER JOIN (
SELECT MAX(a2.n_assess_id)
FROM rk_assess a2
WHERE a2.n_risk_id = a.n_risk_id
) ca
Any pointers would be greatly appreciated. Thanks to everyone in advance for even reading this far.
Greetings. Whale.