1

每周(左右)一次,我在多线程应用程序中收到以下错误消息:

数据库中已经有一个名为“IX_MY_INDEX_NAME”的对象。无法创建约束。

有问题的 SP 创建一个临时表,如下所示:

--removed for brevity
CREATE TABLE #MyTable
(
    [IndexId] INT UNIQUE IDENTITY (1, 1) NOT NULL,
    [WhateverId] INT NOT NULL,
    [CustomerId] INT NULL,
    [VendorId] INT NULL,
    CONSTRAINT IX_MY_INDEX_NAME UNIQUE (
        WhateverId,
        CustomerId,
        VendorId
    )
)
--removed for brevity

是什么导致这种情况发生?上面的语句不是原子的吗?我错过了什么吗?

4

2 回答 2

7

约束需要在数据库中唯一命名;在您上面的示例中,如果两个线程大致同时执行,则有可能在创建第二个线程时存在具有该约束的临时表。

做你想做的事,在创建表后创建一个 UNIQUE 索引;索引名称不必是唯一的。

于 2013-10-12T05:40:50.827 回答
1

2 thoughts come to mind. 1) It depends on how you generate your constraint name: IX_MY_INDEX_NAME. The error is stating that the index named has already been used (possibly for another table). 2) You mentioned it is a multi-threaded application, is it possible two threads are attempting to execute the same create statement. To rule this out, you can alter your table creation to only create if it doesn't exist. e.g. Oracle/Mysql -> CREATE TABLE IF NOT EXISTS

于 2013-10-12T05:41:08.443 回答