我收到以下错误
CREATE UNIQUE INDEX语句终止,因为找到了对象名称的重复键' dbo.MY_TABL'和索引名称' idxReqId'。重复键值为(0)。
脚本alter table,添加列,最后添加一个唯一的非聚簇索引。脚本在此行失败
CREATE UNIQUE NONCLUSTERED INDEX idxReqId ON [dbo].[MY_TABL](MY_REQID)
我做了以下查询:
SELECT * FROM sys.indexes WHERE name='idxReqId' AND object_id = OBJECT_ID('[dbo].[MY_TABL]')
我什么都没有回来
我对SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('[dbo].[MY_TABL]')
进行了查询
并且返回1但是它是一个CLUSTERED索引。
我无法弄清楚如何克服这个错误。任何帮助表示赞赏。
USE [TestWebDb2_Local]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
SET XACT_ABORT ON
GO
BEGIN TRANSACTION
BEGIN TRY
IF COLUMNPROPERTY(OBJECT_ID('[dbo].[MY_TABL]'), 'MY_REQID', 'ColumnId') IS NULL
BEGIN
ALTER TABLE [dbo].[MY_TABL] ADD MY_REQID INT NOT NULL DEFAULT(0)
END
IF COLUMNPROPERTY(OBJECT_ID('dbo.MY_TABL'), 'MY_ISCOMPLETED', 'ColumnId') IS NULL
BEGIN
ALTER TABLE [dbo].[MY_TABL] ADD MY_ISCOMPLETED BIT NOT NULL DEFAULT(0)
END
END TRY
BEGIN CATCH
-- Test whether the transaction is uncommittable.
IF (XACT_STATE()) = -1
BEGIN
PRINT 'The transaction from Alter table is in an uncommittable state.' +
' Rolling back transaction.'
ROLLBACK TRANSACTION;
END;
END CATCH;
GO
BEGIN TRY
UPDATE [dbo].[MY_TABL] SET MY_REQID = 20 WHERE MY_SHORT_NAME = '1035'
UPDATE [dbo].[MY_TABL] SET MY_REQID = 37, MY_ISCOMPLETED = 1 WHERE MY_SHORT_NAME = 'ABVRPARA'
END TRY
BEGIN CATCH
IF (XACT_STATE()) = -1
BEGIN
PRINT 'The transaction from UPDATE table is in an uncommittable state.' +
' Rolling back transaction.'
ROLLBACK TRANSACTION;
END;
END CATCH;
BEGIN TRY
CREATE UNIQUE NONCLUSTERED INDEX idxReqId ON [dbo].[MY_TABL](MY_REQID)
PRINT 'Index created'
END TRY
BEGIN CATCH
-- Test whether the transaction is uncommittable.
IF (XACT_STATE()) = -1
BEGIN
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
PRINT 'The transaction from Create Index is in an uncommittable state.' +
' Rolling back transaction.'
ROLLBACK TRANSACTION;
END;
END CATCH;
GO
if XACT_STATE() = 1
BEGIN
COMMIT TRANSACTION
PRINT 'Transaction committed.';
END;
答案 0 :(得分:1)
运行以下查询
SELECT MY_REQID, COUNT(*) as COUNT
FROM [dbo].[MY_TABL]
GROUP BY MY_REQID
HAVING COUNT(*) > 1
这将为您提供一个非独特的MY_REQID列表。要制作此索引,它们必须是唯一的。删除重复项/弄清楚为什么它们不是唯一的,因为您知道哪些/多少记录不是唯一的。