Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constraint on RowParentId within same table?

Tags:

sql-server

How do I specify constraint on my field that allows null but if value exists it should be one of values of primary key within existing table? Take a look at the code:

  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

I want to be able to generate parent child view without limiting depth and enforcing constraint on existing parent.

Hope I was able to convey what I'm looking for.

Cheers

like image 760
krul Avatar asked May 09 '26 03:05

krul


1 Answers

Isn't that just a foreign key?

RowParentId int NULL references ParentTable (ParentTableIdColumn),

if it is not null, then it must be a value from the parent table.

like image 165
Nick DeVore Avatar answered May 11 '26 14:05

Nick DeVore