![](/img/trans.png)
[英]MS SQL Server - What is the value of WITH CHECK in a foreign key constraint?
[英]CHECK constraint in SQL Server not allowing to exceed value from foreign key
我有以下兩個表:
CREATE TABLE test1
(
ID int IDENTITY UNIQUE,
length int not null
)
CREATE TABLE test2
(
ID int IDENTITY UNIQUE,
test1number int references test1(ID),
distance int not null
)
示例:讓我們將test1的值1和100(ID = 1,長度= 100)插入。 現在,將值1作為ID插入到test2中,並將test1number = 1插入到test1中作為參考。 我想創建一個約束,該約束將不允許寫入距離大於100(距test1的長度)。
除程序外還有其他方法嗎?
如果這是針對單個行的,並且我們不需要對所有具有相同test1number
值的行斷言某些屬性,那么執行此操作的一種方法是:
CREATE TABLE test1
(
ID int IDENTITY UNIQUE,
length int not null,
constraint UQ_test1_Length_XRef UNIQUE (ID,Length)
)
go
CREATE TABLE _test2
(
ID int IDENTITY UNIQUE,
test1number int references test1(ID),
_test1length int not null,
distance int not null,
constraint FK_test2_test1_length_xref foreign key (test1number,_test1length)
references test1 (ID,length) on update cascade,
constraint CK_length_distance CHECK (distance <= _test1length)
)
go
create view test2
as
select ID,test1number,distance from _test2
go
create trigger T_I_t2 on test2
instead of insert
as
insert into _test2(test1number,_test1length,distance)
select test1number,length,distance
from inserted i inner join test1 t on i.test1number = t.id
go
如果您要向用戶隱藏_test2
表中此額外列的存在,則僅需要視圖和觸發器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.