如何更改表复合主键

时间:2009-08-31 12:34:03

标签: sql-server sql-server-2005 composite-primary-key

CREATE TABLE [dbo].[INVS_ITEM_LOCATIONS]
([DEPARTMENT_CODE] [varchar](3) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [IM_INV_NO] [numeric](10, 0) NOT NULL,
 [LOCATION_CODE] [varchar](2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [CURR_QTY] [numeric](10, 0) NOT NULL CONSTRAINT [DF__INVS_ITEM__CURR___1352D76D]  DEFAULT ((0)),
 [DO_QTY] [numeric](10, 0) NOT NULL CONSTRAINT [DF__INVS_ITEM__DO_QT__1446FBA6]  DEFAULT ((0)),
 [ALLOC_QTY] [numeric](10, 0) NOT NULL CONSTRAINT [DF__INVS_ITEM__ALLOC__153B1FDF]  DEFAULT ((0)),
 [YOB_QTY] [numeric](10, 0) NOT NULL CONSTRAINT [DF__INVS_ITEM__YOB_Q__162F4418]  DEFAULT ((0)),
 [FOC_QTY] [numeric](10, 0) NULL CONSTRAINT [DF__INVS_ITEM__FOC_Q__17236851]  DEFAULT ((0)),
 [USER_CREATED] [varchar](25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [DATE_CREATED] [datetime] NOT NULL,
 [USER_MODIFIED] [varchar](25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
 [DATE_MODIFIED] [datetime] NULL,

 CONSTRAINT [INVS_ITEM_LOCATIONS_PK] 
 PRIMARY KEY CLUSTERED ([DEPARTMENT_CODE] ASC,
 [IM_INV_NO] ASC, [LOCATION_CODE] ASC)
 WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

这是我的表结构......如何删除表中的复合主键,我还应该将外键添加到im_inv_no引用表是包含im_inv_no的invs_location,而department_code应该是相同的主键.pls帮助

2 个答案:

答案 0 :(得分:4)

要删除复合主键,请使用:

ALTER TABLE dbo.INVS_ITEM_LOCATIONS
  DROP CONSTRAINT INVS_ITEM_LOCATIONS_PK

要添加外键,请使用:

ALTER TABLE dbo.INVS_ITEM_LOCATIONS
  ADD CONSTRAINT FK_INV_NO_REFERENCE
  FOREIGN KEY(IM_INV_NO, DEPARTMENT_CODE)
  REFERENCES dbo.invs_location(IM_INV_NO, DEPARTMENT_CODE)

这些都是非常基本的初学者SQL问题 - 我会强烈建议您先阅读各种优秀的SQL教程之一,以便在发布之前先熟悉SQL这里每一个小问题......

W3Schools SQL Tutorial

马克

答案 1 :(得分:1)

您可以创建需要修改的新表,复制数据,然后将新塔重命名为与旧表相同的名称,并删除旧表。这可能是最有效的方式。