Yogus
Yogus

Reputation: 2272

Can I add a FK column of same table?

I am creating the tables as per the sheet provided by my client . This is one of the table provided to me to create .

enter image description here

How can I add a FK parent.id of the same table?

I created a query like this

CREATE TABLE Calendar (
id varchar(64) PRIMARY KEY,
idsite varchar(64) NOT NULL ,
FOREIGN KEY (parentid) REFERENCES Calendar(id));    

Obviously this query failed. I know this is not correct ? could you please help to make me understand that this is possible case ? I have never seen this kind of FK relationship before .

Upvotes: 0

Views: 38

Answers (1)

SteveC
SteveC

Reputation: 6015

The parentid inherits the column type varchar(64) from the 'id' column. You could try it like this

drop table if exists dbo.test_Calendar;
go
create table dbo.test_Calendar (
id varchar(64) constraint pk_test_Calendar primary key not null,
idsite varchar(64) not null ,
parentid varchar(64) constraint fk_test_Calendar_id references dbo.test_Calendar(id));

Upvotes: 3

Related Questions