我在SQL Server 2008 R2中工作,并且编写了一个存储过程,该约束为数据库中的多个表中的多个列添加了约束。但是,我发现存储过程失败,因为由于列上的索引,它无法将特定列设置为主键。各种表中的许多列都是这种情况。
有没有办法将COLUMN改为NOT NULL并将其设置为PRIMARY KEY而不删除索引?否则,是否有一种很好的方法可以禁用或删除索引,然后在ALTER COLUMN语句后启用或重新创建它?
答案 0 :(得分:2)
谢谢大家的意见。经过一些研究,我能够使用@mwigdahl提到的确切表格来确定如何动态执行此操作。请参阅以下代码:
DECLARE @indexName nvarchar(254),
@tableName nvarchar(254),
@indexType nvarchar(254),
@columnName nvarchar(254),
@isPadded integer,
@ignore_dup_key integer,
@allow_row_locks integer,
@allow_page_locks integer,
@fillFactor integer
SELECT
@indexName = i.name,
@tableName = o.name,
@indexType = i.type_desc,
@columnName = co.[name],
@isPadded = i.is_padded,
@ignore_dup_key = i.[ignore_dup_key],
@allow_row_locks = i.[allow_row_locks],
@allow_page_locks = i.[allow_page_locks],
@fillFactor = i.fill_factor
FROM sys.indexes AS i
INNER JOIN sys.objects AS o ON i.object_id = o.object_id
INNER JOIN sys.index_columns ic on ic.object_id = i.object_id AND ic.index_id = i.index_id
INNER JOIN sys.columns co on co.object_id = i.object_id AND co.column_id = ic.column_id
WHERE
i.[type] = 2 AND
o.[type] = 'U'
DECLARE @sql varchar(max)
SET @sql = 'DROP INDEX [' + @indexName + '] ON [' + @tableName + ']'
EXEC (@sql)
PRINT 'Dropped Index'
-- Do work here
DECLARE @pad_index nvarchar(3),
@ignore_dup nvarchar(3),
@row_locks nvarchar(3),
@page_locks nvarchar(3)
IF @isPadded = 0 SET @pad_index = 'OFF'
ELSE SET @pad_index = 'ON'
IF @ignore_dup_key = 0 SET @ignore_dup = 'OFF'
ELSE SET @ignore_dup = 'ON'
IF @allow_row_locks = 0 SET @row_locks = 'OFF'
ELSE SET @row_locks = 'ON'
IF @allow_page_locks = 0 SET @page_locks = 'OFF'
ELSE SET @page_locks = 'ON'
SET @sql = 'CREATE ' + @indexType + ' INDEX [' + @indexName + '] ON [' + @tableName + ']' +
'(' +
'[' + @columnName + '] ASC' +
') WITH (' +
'PAD_INDEX = ' + @pad_index + ',' +
'STATISTICS_NORECOMPUTE = OFF,' +
'SORT_IN_TEMPDB = OFF,' +
'IGNORE_DUP_KEY = ' + @ignore_dup + ',' +
'DROP_EXISTING = OFF,' +
'ONLINE = OFF,' +
'ALLOW_ROW_LOCKS = ' + @row_locks + ',' +
'ALLOW_PAGE_LOCKS = ' + @page_locks + ',' +
'FILLFACTOR = ' + CONVERT(nvarchar(100),@fillFactor) + ')' +
'ON [PRIMARY]'
PRINT @sql
EXEC (@sql)
PRINT 'Created Index'
我在SSMS中使用Script Index As
函数来查看如何在T-SQL中创建索引。
然后我查询sys.indexes
和sys.index_columns
表以确定哪些属性可用。
代码显示针对这些表的查询,将这些属性保存到变量,然后删除并重新创建索引。我必须硬编码的那些表格中有一些选项不可用。有谁知道这些OPTIONS在系统表的某个地方是否可用?
我希望将来可以帮助别人。