从表问题中删除一列(SQL Server 2008)

时间:2011-04-20 07:50:03

标签: sql sql-server sql-server-2008 table-index

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

表CREATE脚本:

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 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:0)

您必须删除索引IX_Users并创建一个没有U_Family的新索引。

答案 2 :(得分: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

答案 3 :(得分: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__