T-SQL使用什么样的约束

时间:2014-02-19 15:08:39

标签: sql-server tsql constraints

我有以下两个表(仅显示相关的键列)

CREATE TABLE [dbo].[Jobs](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [JobNo] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Jobs] 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]


    CREATE TABLE [dbo].[Items](
    [JobID] [int] NOT NULL,
    [BarcodeNo] [nvarchar](50) NOT NULL,
    [SerialNo] [nvarchar](50) NOT NULL,

 CONSTRAINT [PK_Items_1] PRIMARY KEY CLUSTERED 
(
    [JobID] ASC,
    [BarcodeNo] ASC,
    [SerialNo] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

我需要确保在输入项目时,JobID与Jobs表中的ID匹配。看来,我不能使用FK,因为items表中的PK是3列的复合键。

TIA

标记 我可以使用什么样的约束?

1 个答案:

答案 0 :(得分:6)

外键工作正常。

单列[dbo].[Items].[JobID]引用作业PK是没有问题的。

CREATE TABLE [dbo].[Jobs]
  (
     [ID]    [INT] IDENTITY(1, 1) NOT NULL,
     [JobNo] [NVARCHAR](50) NOT NULL,
     CONSTRAINT [PK_Jobs] 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]

CREATE TABLE [dbo].[Items]
  (
     [JobID]     [INT] NOT NULL REFERENCES [dbo].[Jobs]([ID]), /*<-- FK declaration*/
     [BarcodeNo] [NVARCHAR](50) NOT NULL,
     [SerialNo]  [NVARCHAR](50) NOT NULL,
     CONSTRAINT [PK_Items_1] PRIMARY KEY CLUSTERED ( [JobID] ASC, [BarcodeNo] ASC, [SerialNo] ASC )
    WITH (PAD_INDEX = OFF, 
          STATISTICS_NORECOMPUTE = OFF, 
          IGNORE_DUP_KEY = OFF, 
          ALLOW_ROW_LOCKS = ON, 
          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  )
ON [PRIMARY]