我的INSERT语句在尝试将新记录添加到空表(属性)时失败(尚未记录)。 我对系统引发的错误感到惊讶:
违反UNIQUE KEY约束'CK_Attribute_Name_IDproject'。无法在对象'dbo.Attribute'中插入重复键。重复键值为(dummy,55)。
此表的创建脚本类似于
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]。
运行以下语句时
SELECT *
FROM [dbo].[Attribute]
GO
SELECT *
FROM [dbo].[Project]
GO
我得到了结果
(0行(s)受影响) (2行受影响)
第一个结果表明属性表为空 第二,有2个项目 s
然后在表属性中运行以下INSERT,它失败并出现上述UNIQUE CONSTRAINT错误
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
如何在空表上出现这样的错误?
答案 0 :(得分:0)
我自己找到了解决方案:派生的SELECT返回带有'dummy'的2条记录,因为INTO其中一个表(AttributeType)与INNER JOIN的重复执行。