如何使用两个主键将行插入表中?

时间:2012-06-21 01:25:05

标签: sql-server

我创建了以下表格:

CREATE TABLE [dbo].[tblArchLogDetail](
    [RecordID] [numeric](18, 0) NOT NULL,
    [TableName] [varchar](30) NOT NULL,
    [TotalRecords] [int] NULL,
    [ArchivedRecords] [int] NULL,
 CONSTRAINT [PK_tblArchLogDetail] PRIMARY KEY CLUSTERED 
(
    [RecordID] ASC,
    [TableName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

那么,如何在此表中插入行?我一直收到错误“违反PRIMARY KEY约束”。 这是我的示例代码:

Insert into tblArchLogDetail values(54,'tblAuditLogin',13128,0)

2 个答案:

答案 0 :(得分:1)

这里有一个所谓的“复合”主键。

这意味着您选择构成复合主键的任何组合值必须是唯一的。

您获得的错误仅表示您已在该表中拥有RecordId为54且TableName为'tblAuditLogin'的记录。

答案 1 :(得分:0)

认为你要做的是在RecordID字段中添加一个自动递增的整数。如果是,请将其设为身份字段:

CREATE TABLE [dbo].[tblArchLogDetail](
    [RecordID] [numeric](18, 0) IDENTITY NOT NULL,
    [TableName] [varchar](30) NOT NULL,
    [TotalRecords] [int] NULL,
    [ArchivedRecords] [int] NULL,
 CONSTRAINT [PK_tblArchLogDetail] PRIMARY KEY CLUSTERED 
(
    [RecordID] ASC,
    [TableName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

如果这不是您的意图,并且您确实需要RecordIDTableName中的重复记录,请在RecordID之前添加一个标识字段并将其添加到PRIMARY KEY约束中:

CREATE TABLE [dbo].[tblArchLogDetail](
    [ID] [bigint] IDENTITY NOT NULL
    [RecordID] [numeric](18, 0) NOT NULL,
    [TableName] [varchar](30) NOT NULL,
    [TotalRecords] [int] NULL,
    [ArchivedRecords] [int] NULL,
 CONSTRAINT [PK_tblArchLogDetail] PRIMARY KEY CLUSTERED 
(
    [ID] ASC,
    [RecordID] ASC,
    [TableName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

如果这两个解决方案无法解决问题,则您需要提供回答此问题所需的其他详细信息。