SQL Server使用UDF检查约束

时间:2018-01-22 20:12:57

标签: sql sql-server constraints

我试图生成一种安全的方法来确保表格中添加的年份范围记录与现有记录不重叠。

我创建了我的表,创建了一个udf并创建了检查约束,并且奇怪的是他们不应该工作

用于创建表,udf和约束的查询:

Create Table EasyBankVehicleProductsCatSettings
(
    ProductCode int not null,
    Name varchar(100) not null,
    MinYear int not null, 
    MaxYear int not null
)

alter table EasyBankVehicleProductsCatSettings
    add constraint PK_VehicleProductCatSetting 
    Primary Key nonclustered (ProductCode, Name, MinYear, MaxYear)
go

Create Function CheckIfYearRangeExists
     (@Year int, @ProductCode int)
returns smallint
as 
begin
    declare @ret varchar(5);

    declare @count smallint;
    set @count = 0;

    select @count = count(productcode) 
    from EasyBankVehicleProductsCatSettings 
    where @Year between MinYear and MaxYear
      and ProductCode = @ProductCode

    return @count
end 
go

alter table EasyBankVehicleProductsCatSettings
    add constraint CK_MinYear
        check (dbo.CheckIfYearRangeExists(minyear, productcode) = 0)

alter table EasyBankVehicleProductsCatSettings
    add constraint CK_MaxYear
        check (dbo.CheckIfYearRangeExists(maxyear, productcode) = 0)
go

用于测试的插入:

INSERT INTO EasyBankVehicleProductsCatSettings(ProductCode, Name, MinYear, MaxYear)
VALUES (400, 'a',2015, 2019)

这不起作用。它回滚插件并说我违反了我的约束。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

运行这些并告诉我你是否可以

Create Table EasyBankVehicleProductsCatSettings
(
ProductCode int not null,
Name varchar(100) not null,
MinYear int not null, 
MaxYear int not null
)
go

alter table EasyBankVehicleProductsCatSettings
add constraint PK_VehicleProductCatSetting Primary Key nonclustered (ProductCode)
go


/* run once */

INSERT  INTO EasyBankVehicleProductsCatSettings(ProductCode, Name, MinYear, MaxYear)
VALUES (400, 'a',2015, 2019)