I have a poorly normalized set of tables and I am trying to correct this issue. The DB is MS SQL 2005.
Table1 has an id field (record ID), a mainID field (person ID) and a sequence field (and int that determines the sort order)
Table2 has its own id field and a copy of the id for the first record by a person (sequence = 1).
I’ve added a new field to table2 call table2_id and I would like to populate this field with the ID from table2 so that I can do away with table1.mainID. table2 only has a record for one of the records for each person and mainId is set to the id where table1.sequence = 1.
This is the update query I thought would do the job by I’m getting errors
update table1 as a
set regInfoID = (select b.id
from table2 as b
where b.ref1 = (select c.id
from table1 as c
where c.mainID = a.mainID
and sequence = 1))
I believe I’m on the right track her since the following query works fine
select regInfoID = (select b.id
from table2 as b
where b.ref1 = (select c.id
from table1 as c
where c.mainID = a.mainID
and sequence = 1)), a.*
from table1 as a
I think your query is equivalent to this:
From this query, I think you will potentially have indeterminate results because table2 (b) is not guaranteed to be a single row result. So regInfoID will be set to one of the resulting b.id values.