简体   繁体   English

SSMS SQL - 创建具有相关列的表

[英]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.然后我在图中创建一个新表,外键指向另外 2 个表。 Example:例子:

Tables in the diagram: Customers, Orders and Status图表中的表格:客户、订单和状态

New table: View (with fk to Customers(CustID), Orders(OrID) and Status(SID))新表:视图(带有 fk 到客户(CustID)、订单(OrID)和状态(SID))

In view table, I want a column Ordertype which should be a related/linked column to Orders table.在视图表中,我想要一个列Ordertype ,它应该是 Orders 表的相关/链接列。 Meaning, that whenever I change a value of Ordertype in my new View table, it gets updated in the Orders table as well.这意味着,每当我在新的View表中更改Ordertype的值时,它也会在 Orders 表中更新。

How can I achieve this?我怎样才能做到这一点? I guess I need sql script that adds such a related column to my view table.我想我需要 sql 脚本,将这样一个相关的列添加到我的视图表中。

What I have tried: Relationship Orders(PK) and View(FK) has update property set to "Cascade".我尝试过的:关系订单(PK)和视图(FK)已将更新属性设置为“级联”。 Given same column name and datatype to Ordertype in both tables, Orders and View But, this doesn't work for me.在两个表 Orders 和 View 中给定相同的列名和数据类型 Ordertype 但是,这对我不起作用。

Thanks.谢谢。

Foreign key constraints can't help you to update data.外键约束不能帮助你更新数据。 You could try to use DML Trigger.您可以尝试使用 DML 触发器。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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