Im using SQL Server 2000 and am trying to establish a foreign key in
a table that already exists. So I tried executing:
Alter Table Book
Foreign Key (PublisherCode) References Publisher
It gives me the error:
"Incorrect syntax near the keyword Foreign "
Any idea why this is happening?
Posted using the http://www.dbforumz.com interface, at author's request
Articles individually checked for conformance to usenet standards
Topic URL: http://www.dbforumz.com/Programming...77.ht
ml
Visit Topic URL to contact author (reg. req'd). Report abuse: http://www.dbforumz
.com/eform.php?p=844431Here's an example and the correct syntax:
ALTER TABLE b ADD CONSTRAINT X FOREIGN KEY (j) REFERENCES a(i)
HTH,
Vyas, MVP (SQL Server)
SQL Server Articles and Code Samples @. http://vyaskn.tripod.com/
"Xee" <UseLinkToEmail@.dbForumz.com> wrote in message
news:4_844431_0c41147eef0173be529f08af89
751d60@.dbforumz.com...
> I'm using SQL Server 2000 and am trying to establish a foreign key in
> a table that already exists. So I tried executing:
> Alter Table Book
> Foreign Key (PublisherCode) References Publisher
> It gives me the error:
> "Incorrect syntax near the keyword 'Foreign' "
> Any idea why this is happening?
> --
> Posted using the http://www.dbforumz.com interface, at author's request
> Articles individually checked for conformance to usenet standards
> Topic URL:
> http://www.dbforumz.com/Programming...pict243077.html
> Visit Topic URL to contact author (reg. req'd). Report abuse:
> http://www.dbforumz.com/eform.php?p=844431|||Your statement is legal if you just insert the ADD keyword:
ALTER TABLE Book ADD
FOREIGN KEY (PublisherCode) REFERENCES Publisher
However, this will create a foreign key constraint with a default name,
something like: "FK__Book__publisherc__7A6A5B6E" and it will be different
each time you run the code. Default names are difficult to work with and
will cause you problems later. To avoid default names, always specify a name
explicitly ("fk_book_publisher" in this example):
ALTER TABLE Book ADD CONSTRAINT fk_book_publisher
FOREIGN KEY (PublisherCode) REFERENCES Publisher
David Portas
SQL Server MVP
--|||On 26 Jul 2005 18:35:48 -0400, Xee wrote:
>Im using SQL Server 2000 and am trying to establish a foreign key in
>a table that already exists. So I tried executing:
>Alter Table Book
>Foreign Key (PublisherCode) References Publisher
>It gives me the error:
>"Incorrect syntax near the keyword Foreign "
>Any idea why this is happening?
Hi Xee,
Try adding the keyword "Add":
Alter Table Book
Add Foreign Key (PublisherCode) References Publisher
Or, even better, provide a name for your constraint as well, to
facilitate future reference:
Alter Table Book
Add Constraint FK_Book_Publisher
Foreign Key (PublisherCode) References Publisher
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)
No comments:
Post a Comment