简体   繁体   中英

SSMS SQL - Create table with related columns

I have a DB Diagram with relationships on primary and foreign keys. Then I create a new table in the diagram, with foreign keys to 2 other tables. Example:

Tables in the diagram: Customers, Orders and Status

New table: View (with fk to Customers(CustID), Orders(OrID) and Status(SID))

In view table, I want a column Ordertype which should be a related/linked column to Orders table. Meaning, that whenever I change a value of Ordertype in my new View table, it gets updated in the Orders table as well.

How can I achieve this? I guess I need sql script that adds such a related column to my view table.

What I have tried: Relationship Orders(PK) and View(FK) has update property set to "Cascade". Given same column name and datatype to Ordertype in both tables, Orders and View But, this doesn't work for me.

Thanks.

Foreign key constraints can't help you to update data. You could try to use DML Trigger. For example,

CREATE TRIGGER InsertUpdateTrigger ON View
AFTER Insert, Update AS 
BEGIN 
    UPDATE O
    SET O.OrderType = I.OrderType 
    FROM ORDERS O 
    JOIN INSRTED I on O.orid = I.id(change to your id)
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM