插入时违反主键约束

时间:2015-12-10 04:55:19

标签: sql-server stored-procedures

我有一张表,主键由4列组成,如下所示:

CREATE TABLE [dbo].[INV_STOCK_TEST]
(
    [STOCK_WRH_ID]  [varchar](6) NOT NULL,
    [STOCK_LOC_ID]  [varchar](6) NOT NULL,
    [STOCK_ITEM_NO] [varchar](20) NOT NULL,
    [STOCK_BEG_QTY] [decimal](9, 2) NULL,
    [YEAR]          [nvarchar](5) NOT NULL, 

    CONSTRAINT [PK__INV_STOC__3B64B7082B9540B9]
    PRIMARY KEY CLUSTERED  (
        [STOCK_WRH_ID] ASC,
        [STOCK_LOC_ID] ASC,
        [STOCK_ITEM_NO] ASC,
        [YEAR] ASC
    )WITH (
        PAD_INDEX = OFF,
        STATISTICS_NORECOMPUTE = OFF, 
        IGNORE_DUP_KEY = OFF,
        ALLOW_ROW_LOCKS = ON, 
        ALLOW_PAGE_LOCKS = ON
    ) ON [PRIMARY]
) ON [PRIMARY]

我有一个更新此表中年度数据的程序

DECLARE @YEAR nvarchar(20)

SET @YEAR = (SELECT TOP 1 [YEAR] FROM INV_STOCK_TEST ORDER BY [YEAR] DESC)

INSERT INTO INV_STOCK_TEST([STOCK_WRH_ID], [YEAR],
                           [STOCK_LOC_ID], [STOCK_BEG_QTY], [STOCK_ITEM_NO])
    SELECT
        STOCK_WRH_ID, @YEAR + 1,
        STOCK_LOC_ID, 0, STOCK_ITEM_NO
    FROM
        INV_STOCK_TEST

示例插入数据

A   A   ITEM_A  0.00    2014
A   A   ITEM_A  0.00    2015
B   B   ITEM_B  0.00    2014
B   B   ITEM_B  0.00    2015

2014年到2015年没关系,但2015年到2016年我运行程序时出现此错误:

  

违反PRIMARY KEY约束'PK__INV_STOC__3B64B7082B9540B9'。   无法在对象'dbo.INV_STOCK_TEST'中插入重复键。该   重复键值为(A,A,ITEM_A,2017)。

我无法更改主键,如何解决此问题?

1 个答案:

答案 0 :(得分:0)

拥有与记录相关的ID字段并将其用作主键,而不是尝试创建多个非唯一标识字段。

CREATE TABLE [dbo].[INV_STOCK_TEST]
(
[PK_ID]         [INT] PRIMARY KEY CLUSTERED,
[STOCK_WRH_ID]  [varchar](6) NOT NULL,
[STOCK_LOC_ID]  [varchar](6) NOT NULL,
[STOCK_ITEM_NO] [varchar](20) NOT NULL,
[STOCK_BEG_QTY] [int] NULL, -- decimals lack precision
                            -- use integers when dealing with discrete.
[YEAR]          [varchar](5) NOT NULL --I would use a datetime here
                                      --purely for formatting reasons
)

程序应该完全相同。