Sunday, March 11, 2012

Alter Table

I am new to SQL and struggling with some basic code!
How do I use the ALTER TABLE command to add a foreign key constraint?
I have the correct code for creating the tables and adding the constraints
when creating, but can't figure out how to modify an existing table and add
a FK.
ThanksHi,
Sample code:-
create table t90(i int primary key)
go
create table t91(i int)
go
alter table t91 add constraint fk_t1 foreign key(i) references t90(i)
--
Thanks
Hari
MCDBA
"Keith" <@..> wrote in message news:uQUuKStTEHA.4048@.TK2MSFTNGP12.phx.gbl...
> I am new to SQL and struggling with some basic code!
> How do I use the ALTER TABLE command to add a foreign key constraint?
> I have the correct code for creating the tables and adding the constraints
> when creating, but can't figure out how to modify an existing table and
add
> a FK.
> Thanks
>|||This should do:
ALTER TABLE dbo.[Tablex] ADD CONSTRAINT
FK_Tablex_Tabley FOREIGN KEY
(
id
) REFERENCES dbo.Table1
(
id
)
GO
BTW,
if you require syntax like this, you can get EM to create
it for you. Just add the FK in table design and the "Save
Change Script" button becomes available.
HTH,
Paul Ibison

No comments:

Post a Comment