tags:

views:

40

answers:

3

Say I have:

create table Post(
  PostID int not null constraint PK_Post primary key clustered,
  Title nvarchar(200) not null
) on [primary]

create table PostDetail(
  PostID int not null constraint PK_PostDetail primary key clustered,
  Text nvarchar(max) null
) on [primary]

How do I make PostDetail.PostID an FK referencing Post.PostID?

+1  A: 

After the fact:

alter table PostDetail
    add constraint FK_PostDetail_Post 
        foreign key (PostID) references Post (PostID)

Or in the table def:

create table PostDetail(
  PostID int not null constraint PK_PostDetail primary key clustered,
  Text nvarchar(max) null,
  constraint FK_PostDetail_Post foreign key (PostID) references Post (PostID)
) on [primary]
Ben M
for what it's worth the fk constraint can begin immediately after the word "clustered", with just a space between them (of course leaving out which column it is for since that's implied by its position). Constraints can be chained together on the same line after the column. They can all also be put at the end of the create table, as you put one of the constraints.
Emtucifor
@Emtucifor, thanks for the clarification!
Xerion
+2  A: 

Use:

ALTER TABLE POSTDETAIL
  ADD CONSTRAINT fk_post 
      FOREIGN KEY (postid) REFERENCES POST (postid)

Though I have to say that what you've listed looks to be a one-to-one relationship - only one POSTDETAIL record associates with a POST record. You might as well use:

create table Post(
  PostID int not null constraint PK_Post primary key clustered,
  Title nvarchar(200) not null,
  Text nvarchar(max) null
) on [primary]
OMG Ponies
Having them in separate tables could be useful if the majority of queries are just against PostID and Title, as the CIX would be smaller.
Rob Farley
@OMG, that was the intent. The tables were simplified greatly for the purpose of this question. But Post has mostly simple columns that are not null and needed for quick list searching/sorting. PostDetail contains text, image large data for the "details" view. Hence 2 tables with 1-to-1 relationship.
Xerion
;) @OMG: I've seen this type of problem before, and seen the significant benefit in it. It can be very elegant if you have a view over the top, so that you query it like a normal table.
Rob Farley
@Rob Farley: Interesting - something new every day
OMG Ponies
+2  A: 

If you want to make a proper 1-1 relationship, that's harder. Currently, you can still have an entry in [Post] that doesn't have an entry in [PostDetail].

If you want to go one step further, you may want to research Tony Rogerson's recent investigations into the problem, at http://sqlblogcasts.com/blogs/tonyrogerson/archive/2010/01/23/how-to-create-a-one-to-one-relationship-in-sql-server-using-dri-triggers-and-views.aspx

Rob Farley