开发者

SQL Alter: add multiple FKs?

From here

ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID); 

How do I add several keys with SQL Server? Is it something like the below? (I cant test ATM and unfortunately I have no way to test queries unless I run it through code)

ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID), 
ADD FOREIGN KEY (customer_sid2) REFERENCES CUSTOMER(SID2);

or is it like

ALTER TABLE ORDERS
ADD FOREIGN 开发者_如何学运维KEY (customer_sid, customer_sid2) REFERENCES CUSTOMER(SID, SID2)


The second code block from your question:

ALTER TABLE ORDERS 
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID),  
ADD FOREIGN KEY (customer_sid2) REFERENCES CUSTOMER(SID2); 

will take care of what you are trying to do.


ALTER TABLE ORDERS
    ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID),
        FOREIGN KEY (customer_sid2) REFERENCES CUSTOMER(SID2),
        FOREIGN KEY (customer_sid3) REFERENCES CUSTOMER(SID3);


Here is the sql generated by sqlserver after I use the database diagram to draw the foreign key. Their approach is that one alter table for one foreign key

USE [TimeSheet]
GO
/****** Object:  Table [dbo].[WeekTasks]    Script Date: 05/19/2010 20:09:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WeekTasks](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [WeekID] [int] NOT NULL,
    [TaskDescription] [nvarchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [ProjectID] [int] NOT NULL
 CONSTRAINT [PK_WeekTasks] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[WeekTasks]  WITH CHECK ADD  CONSTRAINT [FK_WeekTasks_Projects] FOREIGN KEY([ProjectID])
REFERENCES [dbo].[Projects] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[WeekTasks] CHECK CONSTRAINT [FK_WeekTasks_Projects]
GO
ALTER TABLE [dbo].[WeekTasks]  WITH CHECK ADD  CONSTRAINT [FK_WeekTasks_WeekTimeSheet] FOREIGN KEY([WeekID])
REFERENCES [dbo].[WeekTimeSheet] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[WeekTasks] CHECK CONSTRAINT [FK_WeekTasks_WeekTimeSheet]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜