This is a follow up question to this one:
Query examples in a many-to-many relationship
regarding updating the junction table. To do this, I would have to use both key values in the junction table, in the WHERE clause.
Users UserAddresses Addresses ======= ============= ========= FirstName UserId City LastName AddressId State Zip
In this example, for instance, say I wanted to update the AddressId field in the UserAddresses table, because a user changed his address. I would have to use both the existing UserId and the address AddressId in the update WHERE clause.
I’m using a stored procedure, and passing in UserId and the new AddressId as parameters.
I’ve tries this:
CREATE PROCEDURE dbo.test ( @UserId int, @AddressId int ) AS create table #temp ( UserId int not null, AddressId int not null ) insert into #temp select UserId, AddressId from UserAddresses where UserId = @UserId update UserAddresses set AddressId = @AddressIdD WHERE (UserId+AddressId in #temp table = UserId+AddressId passed in as parameters)??
I’ve tried all sorts of combinations, but I can’t seem to get the syntax right.
The UserId passed in, would ofcourse be the same as the one in the UserAddresses table, but this is just me trying some things. The WHERE clause is where it seems to go wrong.
Any thoughts?
This actually looks like a many-to-one relationship. If it’s not you’ll need the old address id as well as the new address id and user id to make the change. If it’s a many to one relationship then a simple update should work since only one user id/address id pair will exist for each user id:
If it truly is a many-to-many relationship you need to find the existing pair out of many possible ones and update that one — that’s where you’ll need both the new and old address ids in addition to the user id.