update a field based off of another table

rivkamak
rivkamak used Ask the Experts™
on
I have 1 table with a list of car makes and an ID.
then I have a list of models with a column for carid that matches the first table.

I was wondering  how I can update the model table and replace all the ids with the name from the make table where the makeid matches the other table.

Would something like this work?
update carmodels set carmodels.makeid = carmakes.carname where carmodels.makeid = carmakes.carid

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ste5anSenior Developer

Commented:
The T-SQL syntax is

UPDATE c
SET makeID = O.carName
FROM carmodels C
  INNER JOI carmakes M ON C.makeID = M.makeID;

Open in new window


But why want you do this? You can use a JOIN anytime you need this information. Also it is semantically wrong, cause an ID is not a name. Thus this kind of update is not a good idea. It introduces also redundancy, which is a unwanted situation in the relational model, because it opens the model to get inconsistent.
Scott PletcherSenior DBA
Most Valuable Expert 2018
Top Expert 2014

Commented:
1) You would not want to do that.  If you do want to put the name in the other table, you should create a corresponding column for it, not put a name into an "id" column.
2) I doubt you could put the full name in an id column anywhere.  Presumably the id column is either numeric or much shorter than the name value anyway.

Author

Commented:
Right now I am using 2 sql statmenets and I am trying to figure out how to combine it into 1.
select * from CarMakes where name= ' getname' and type='automobile'
then
select * from CarModels where makeid = '"  & (makeList.Fields.Item("carid").Value)  & "' order by model

can i do this with 1 join?
IT Engineer
Distinguished Expert 2017
Commented:
If you want only show the car make then isn't an update but a select with a join on both tables:
SELECT  carmakes.carname,  carmodels.modelname 
FROM carmakes
INNER JOIN carmodels ON carmodels.carid = carmakes.carid

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial