1

I have two tables zipTbl and locationTBl with four common columns

zipCode
City
stateCode
salesTaxRate

If the zipCode changes in the locationTbl say from '91311' to '10172' I want the city, stateCode, salesTaxRate in the locationTBL to be updated with the same values in the zipTbl where the zipCode is the new value '10172'

zipCode is the primary key for the zipTbl and a foreign key in the locationTbl.

I use the following to create a trigger but it only updates from the first row in the zipTBL not the row with the new zipCode

CREATE TRIGGER trg_update_city_state on dbo.locationTbl
AFTER Update
AS 
BEGIN
     UPDATE locationTbl
     SET locationTbl.city = zipTbl.city,
         LocationTbl.stateCode = zipTbl.stateCode,
         locationTbl.salesTaxRate = zipTbl.salesTaxRate 
     FROM zipTbl
END 

I have tried several combinations of adding "where locationTbl.zipCode = zipTbl.zipcode," but I keep getting syntax errors

2 Answers 2

1

I think it's like this:

UPDATE locationTbl
SET locationTbl.city=zipTbl.city,
    LocationTbl.stateCode=zipTbl.stateCode,
    locationTbl.salesTaxRate=zipTbl.salesTaxRate
FROM locationTbl t1
JOIN inserted i
  ON t1.zipCode=i.zipCode
JOIN zipTbl
  ON i.zipCode=zipTbl.zipCode
Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried something like

CREATE TRIGGER trg_update_city_state on dbo.locationTbl AFTER Update 
AS 
BEGIN 
  UPDATE locationTbl 
  SET locationTbl.city = INSERTED.city, 
  LocationTbl.stateCode = INSERTED.stateCode, 
  locationTbl.salesTaxRate = INSERTED.salesTaxRate 
  FROM INSERTED
  WHERE locationTbl.zipCode = INSERTED.zipcode

2 Comments

You need a join between locationTbl and INSERTED. As posted this doesn't work.
It is the locationTbl where the zipCode is changed and I want to update the city, state, taxrate in the locationTbl from the zipCodeTbl

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.