SQL Server:如何访问通过外键链接的另一个表中的列?

时间:2019-10-31 15:56:40

标签: sql sql-server calculated-columns

我有那些表:

TypeSejour
(
    numType int primary key,
    prixNuit int not null
);

Reservation 
(
    codeR int primary key identity(1,1),
    numType int foreign key references TypeSejour(numType),
    dateDebut date,
    dateFin date,
    constraint checkDates check (dateDebut < dateFin)
);

然后我想在Reservation表中添加一列:

alter table Reservation 
    add Montant as (prixNuit * datediff(day, dateDebut, dateFin));

但是尽管两个表都是通过外键链接的,但仍无法访问prixNuit列。

有解决方案吗?

1 个答案:

答案 0 :(得分:0)

即使您具有外键并且可以精确查明另一张表中的特定行,也不能在表达式中将另一张表的列用于计算列。

您在这里有2个选择:

  • 创建一个连接表的视图,并添加新的“ compute”列作为结果。在这种情况下,该列不是表的一部分(仅在查询时计算)。

    CREATE VIEW dbo.vReservation AS 
    SELECT
        R.codeR,
        R.numType,
        R.dateDebut,
        R.dateFin,
        Montant = T.prixNuit * datediff(day, R.dateDebut, R.dateFin)
    FROM
        Reservation AS R
        INNER JOIN TypeSejour AS T ON R.numType = T.numType
    
  • ReservationTypeSejour上创建触发器,以使Reservation表上的计算保持更新。

我强烈建议您对触发器进行查看,因为触发器会增加 两者 表操作的开销,并且需要将值实际存储为表的一部分。保持该值已经存在的优点是您可以对其进行索引。

相关问题