使用不同的 table 添加约束

add constraint using different table

我有一个包含表 Customer 和 WatchHistory 的数据库。客户只能在 subscription_start 之后和 subscription_end 之前观看电影。我尝试了以下方法:

ALTER TABLE WatchHistory
ADD CONSTRAINT ck_watch_date
  CHECK (watch_date > Customer.subscription_start AND watch_date < Customer.subscription_end)

但我收到以下错误:

Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "Customer.subscription_start" could not be bound.
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "Customer.subscription_end" could not be bound.

我的猜测是我必须使用连接,但我应该把它放在哪里? 以下无效:

ALTER TABLE WatchHistory INNER JOIN Customer
  ON WatchHistory.customer_mail_address = Customer.customer_mail_address
ADD CONSTRAINT ck_watch_date
  CHECK (watch_date > Customer.subscription_start AND watch_date < Customer.subscription_end)

这样做的一种方法是创建一个 UDF,然后在该 UDF 上创建约束。

您的代码示例(未测试,请测试)-

CREATE FUNCTION ufn_check_customerwatchhistory (
    @watch_date DATE
)
RETURNS VARCHAR(10)
AS
BEGIN
    IF EXISTS (SELECT 1 FROM Customer WHERE @watch_date > Customer.subscription_start AND @watch_date < Customer.subscription_end)
        return 'True'
    return 'False'
END

ALTER TABLE WatchHistory
ADD CONSTRAINT ck_watch_date
  CHECK (ufn_check_customerwatchhistory(watch_date) = 'True')