SQL 服务器:添加比较 2 个表中日期的约束

SQL Server: add constraint that compares the date from 2 tables

我有 2 个 table:

键:

我需要为 table 首歌曲添加约束,以便插入的记录年份必须大于或等于艺术家的开始日期(年份)所以我尝试了这个:

alter table Song 
add constraint GreaterThanStartDate 
    check (year > (select startdate from Artist, Song 
                   where Artist.artistname = Song.artistname));

它不起作用,因为检查只接受标量值。所以我想我应该使用用户定义的函数:

create function CompareStartDate()
returns int
as
begin 
    declare @result int

    if (some condition here)
        set @result = 1
    else 
        set @result = 0

    return @result 
end

我被困在if语句中写条件(我可以加入Artist和Song tables,但是如何比较2列和return 1或0)。我不确定我是否在正确的轨道上。

您可以像这样从歌曲 table 向函数传递参数:

CREATE FUNCTION CompareStartDate(@artistname varchar(255), @year int)
RETURNS bit
AS

BEGIN

    DECLARE @result bit

    IF (SELECT TOP 1 YEAR(startdate) FROM Artist WHERE artistname = @artistname) <= @year
        SET @result = 1
    ELSE
        SET @result = 0

    RETURN @result 

END

您的约束将类似于:

ALTER TABLE Song
WITH CHECK
ADD CONSTRAINT CheckYear
CHECK (CompareStartDate(artistname, year) = 1)