空表INSERT [sql-server]抛出UNIQUE约束异常

UNIQUE constraint exception thrown on empty table INSERT [sql-server]

我的INSERT语句在尝试将新记录添加到空表(属性)(尚未记录)时失败。
我对系统引发的错误感到惊讶:

Violation of UNIQUE KEY constraint 'CK_Attribute_Name_IDproject'. Cannot insert duplicate key in object 'dbo.Attribute'. The duplicate key value is (dummy, 55).

该表的创建脚本如下所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CREATE TABLE [dbo].[Attribute](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [IDproject] [int] NOT NULL,
    [IDtype] [int] NOT NULL,
    [IDgroup] [int] NOT NULL,
    [name] [varchar](50) NOT NULL,
    [color] [int] NULL,
    [protected] [tinyint] NULL,
    [datemodified] [datetime] NOT NULL,
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],
 CONSTRAINT [CK_Attribute_Name_IDproject] UNIQUE NONCLUSTERED
(
    [name] ASC,
    [IDproject] 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

我滑过外键引用和默认值,这在这种情况下似乎并不重要。
UNIQUE约束适用于[name]和[IDproject]。

运行以下语句时

1
2
3
4
5
6
SELECT *
  FROM [dbo].[Attribute]
GO
SELECT *
  FROM [dbo].[Project]
GO

我得到了结果

(0 row(s) affected)
(2 row(s) affected)

第一个结果表明属性表为空
第二,有2个项目

然后在表Attribute中运行以下INSERT,它失败并出现上述UNIQUE CONSTRAINT错误

1
2
3
4
5
6
7
8
INSERT INTO [dbo].[Attribute] ([IDproject], [name], [IDtype], [IDgroup], [color], [protected], [datemodified])
        SELECT DISTINCT
            p.[ID],'dummy',t.[ID],g.[ID],-1,0,getdate()
        FROM [dbo].[Project] p
        INNER JOIN [dbo].[Group] g ON g.[name]='none' AND g.[IDproject] = p.[ID]
        INNER JOIN [dbo].[AttributeType] t ON t.[format]='text' AND g.[IDproject] = p.[ID]
        WHERE p.[name]='TESTPROJ'
GO

我如何在空表上得到这样的错误?


我自己找到了解决方案:派生的SELECT返回带有'dummy'的2条记录,因为INTO其中一个表(AttributeType)与INNER JOIN一起执行。