1

无法[U_Family]从下表中删除列:

表创建脚本:

CREATE TABLE [dbo].[Users](
    [U_Id] [int] IDENTITY(101,1) NOT NULL,
    [U_Name] [nvarchar](50) NULL,
    [U_Family] [nvarchar](50) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
    [U_Id] ASC
),
 CONSTRAINT [IX_UserIdUnique] UNIQUE NONCLUSTERED 
(
    [U_UserId] ASC
)
) ON [PRIMARY]
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_Users(UserId)] ON [dbo].[Users] 
(
    [U_Id] ASC
)
INCLUDE ( [U_Name],
[U_Family]) ) ON [PRIMARY]
GO

错误信息 :

“用户”表 - 无法修改表。索引“IX_Users(UserId)”取决于列“U_Family”。ALTER TABLE DROP COLUMN U_Family 失败,因为一个或多个对象访问此列。

我知道问题是因为这个索引:

CREATE UNIQUE NONCLUSTERED INDEX [IX_Users(UserId)] ON [dbo].[Users] 
(
    [U_Id] ASC
)
INCLUDE ( [U_Name],
[U_Family])) ON [PRIMARY]
GO

但我从未找到编辑此索引并[U_Family]从包含列中删除的语法。

我无法删除此索引,因为它被外键约束使用,我不应该删除它。

有什么解决办法???

提前致谢。

4

4 回答 4

5

在 SQL Server 2008 中,您应该能够“重新创建”索引并在单个命令中删除现有索引 - 试试这个:

CREATE UNIQUE NONCLUSTERED INDEX [IX_Users(UserId)] 
  ON [dbo].[Users]([U_Id] ASC) 
  WITH DROP_EXISTING

WITH DROP_EXISTING应该删除包含列的“旧”索引。运行该命令后,您应该能够从表中删除列。

于 2011-04-20T07:57:50.527 回答
0

您将不得不删除索引 IX_Users 并创建一个没有 U_Family 的新索引。

于 2011-04-20T07:55:45.223 回答
0

我使用sys.indexes删除索引,然后删除列:

DECLARE @sql VARCHAR(max)

SELECT @sql = 'DROP INDEX ' + idx.NAME + ' ON tblName'
FROM sys.indexes idx
INNER JOIN sys.tables tbl ON idx.object_id = tbl.object_id
INNER JOIN sys.index_columns idxCol ON idx.index_id = idxCol.index_id
INNER JOIN sys.columns col ON idxCol.column_id = col.column_id
WHERE idx.type <> 0
    AND tbl.NAME = 'tblName'
    AND col.NAME = 'colName'

EXEC sp_executeSql @sql
GO

ALTER TABLE tblName
DROP COLUMN colName
于 2013-05-20T10:59:48.593 回答
0

我找到了这个解决方案并为我工作:

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS WHERE 
PARENT_OBJECT_ID = OBJECT_ID('__TableName__') AND PARENT_COLUMN_ID = (SELECT 
column_id FROM sys.columns WHERE NAME = N'__ColumnName__' AND object_id = 
OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
   EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
IF EXISTS (SELECT * FROM syscolumns WHERE id=object_id('__TableName__') AND 
name='__ColumnName__')
   EXEC('ALTER TABLE __TableName__ DROP COLUMN __ColumnName__')

只需替换__TableName____ColumnName__

于 2017-10-24T13:21:42.020 回答