使用具有不同标题的表中的两个主键属性

时间:2013-12-09 10:46:11

标签: sql sql-server sql-server-2012 ssms

我得到了带有Function_ID {PK}的表“函数”,我想要另一个带有Hierarchy_ID {PK}的表“Hierarchy”,它定义了函数的树结构,所以我需要一个来自Function表AS Parent_ID的Function_ID和一个Function_ID AS Child。我的问题是我如何使用另一个表中的两个主键将它作为外键组合在一起

我正在使用SQL Server 2012和Management Studio

非常感谢

2 个答案:

答案 0 :(得分:0)

实际上你只需要在Functions表中添加一个ParentFunction_ID列 如果您的结构确实是一棵树,则不需要另一张桌子 然后将ParentFunction_ID设为同一个表函数的FK 所以ParentFunction_ID(FK)将指向Function_ID(PK) 具有ParentFunction_ID NULL的唯一记录将是树的根

以下是一些示例代码:

USE [test]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Functions](
    [Function_ID] [int] IDENTITY(1,1) NOT NULL,
    [FunctionCode] [varchar](max) NULL,
    [ParentFunction_ID] [int] NULL,
 CONSTRAINT [PK_Functions] PRIMARY KEY CLUSTERED 
(
    [Function_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Functions]  WITH CHECK ADD  CONSTRAINT [FK_Functions_Functions] FOREIGN KEY([ParentFunction_ID])
REFERENCES [dbo].[Functions] ([Function_ID])
GO

ALTER TABLE [dbo].[Functions] CHECK CONSTRAINT [FK_Functions_Functions]
GO

答案 1 :(得分:0)

功能表命名为功能表。 AFAIK使用
表名的复数并不是一个好习惯

所以你可以这样做。

--- 1 ---    
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Function](
    [Function_ID] [int] IDENTITY(1,1) NOT NULL,
    [FunctionCode] [varchar](max) NULL,
 CONSTRAINT [PK_Function] PRIMARY KEY CLUSTERED 
(
    [Function_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO




--- 2 ---
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Hierarchy](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ParentFunction_ID] [int] NULL,
    [ChildFunction_ID] [int] NULL,
 CONSTRAINT [PK_Hierarchy] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Hierarchy]  WITH CHECK ADD  CONSTRAINT [FK_Hierarchy_Function] FOREIGN KEY([ParentFunction_ID])
REFERENCES [dbo].[Function] ([Function_ID])
GO

ALTER TABLE [dbo].[Hierarchy] CHECK CONSTRAINT [FK_Hierarchy_Function]
GO

ALTER TABLE [dbo].[Hierarchy]  WITH CHECK ADD  CONSTRAINT [FK_Hierarchy_Function1] FOREIGN KEY([ChildFunction_ID])
REFERENCES [dbo].[Function] ([Function_ID])
GO

ALTER TABLE [dbo].[Hierarchy] CHECK CONSTRAINT [FK_Hierarchy_Function1]
GO