Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

update using a lookup

Status
Not open for further replies.

snowneil

Programmer
Mar 22, 2006
40
GB
Hi,

I have an old database layout that is still being used and i need to change the design.

I have 2 tables.

COM, USERS.

COM has a 'managedBy' field which contains a foreign key from USERS.

USERS has the following fields,
'id','username','access','active'.

At the moment USERS.id is a code, ie. J1S.
This code is going into COM.managedBy.

I want to change USERS.id to USERS.code and add a new field called USERS.id which will be an id number used as its primary key.

That bit is simple enough to change but what i am asking is this.

Is there a way to write 1 SQL statement to update all the records with a value in COM.managedBy to its relevant USERS.id by doing a lookup on the id and code in USERS.

I need to update it quickly and updating each different code separately seems tedious.

If that doesn't make sense i will give a bit more detail.
 
Code:
UPDATE Table COM SET managedBy = (SELECT Id FROM Users WHERE Code = COM.managedBy)

or

Code:
UPDATE COM SET managedBy = Users.Code
FROM COM
INNER JOIN Users ON Com.managedBy = Users.Code
-- not tested

Borislav Borissov
VFP9 SP1, SQL Server 2000/2005.
 
Oops. last one must be:
Code:
UPDATE COM SET managedBy = Users.Id
FROM COM
INNER JOIN Users ON Com.managedBy = Users.Code

Borislav Borissov
VFP9 SP1, SQL Server 2000/2005.
 
I figured it out and wrote this before your replies.

Code:
UPDATE COM
SET managedBy = USERS.id
FROM (SELECT id, code FROM USERS) AS USERS
WHERE COM.managedBy = USERS.code

I take it yours works as well but i have nothing to test it on now..

Thanks for the help
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top