我有两张桌子:
键:
我需要为表格歌曲添加一个约束,以便插入的唱片年份必须大于或等于艺术家的开始日期(年份),所以我尝试了这个:
alter table Song
add constraint GreaterThanStartDate
check (year > (select startdate from Artist, Song
where Artist.artistname = Song.artistname));
它不起作用,因为check只接受标量值。所以我认为我应该使用用户定义的函数:
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表,但是如何比较2列并返回1或0)。我不确定我是否走在正确的轨道上。
答案 0 :(得分:1)
您可以从Song表中将参数传递给函数,如下所示:
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)