同一个表中RowParentId的约束?

kru*_*rul 2 sql-server

如何在允许为null的字段上指定约束但如果值存在则应该是现有表中主键的值之一?看看代码:

  CREATE TABLE TestTable 
(
    RowId int IDENTITY NOT NULL PRIMARY KEY,
    RowParentId int NULL, -- < how do I specify constraint that RowParentId if not NULL should be RowId (foreign key to existing table?)
    RowName nvarchar(30),
    RowShortName nvarchar(10)
)
GO
Run Code Online (Sandbox Code Playgroud)

我希望能够生成父子视图,而不会限制现有父级的深度和强制约束.

希望我能够传达我正在寻找的东西.

干杯

Nic*_*ore 5

这不仅仅是外键吗?

RowParentId int NULL references ParentTable (ParentTableIdColumn),
Run Code Online (Sandbox Code Playgroud)

如果它不为null,则它必须是父表中的值.