使用不同的表添加约束

时间:2015-11-20 12:07:22

标签: sql sql-server sql-server-2012 constraints check-constraints

我有一个包含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)

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是创建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')