因为前期表设计不合理,为提高性能,需要将主键重新设置为其他字段。以下是示例脚本。
--修改主键示例
DECLARE @keyColName VARCHAR(50),@PkName NVARCHAR(200)
SELECT @keyColName = syscolumns.name ,@PkName = sysobjects.name
FROM syscolumns,sysobjects,sysindexes,sysindexkeys
WHERE syscolumns.id = object_id('表名') AND sysobjects.xtype = 'PK'
AND sysobjects.parent_obj = syscolumns.id
AND sysindexes.id = syscolumns.id
AND sysobjects.name = sysindexes.name AND sysindexkeys.id = syscolumns.id
AND sysindexkeys.indid = sysindexes.indid
AND syscolumns.colid = sysindexkeys.colid
SELECT @keyColName,@PkName
IF @keyColName = '原主键字段'
BEGIN
BEGIN TRAN
EXEC ( N'ALTER TABLE [dbo].[表名] DROP CONSTRAINT [' + @PkName + ']');
ALTER TABLE [dbo].[表名] ADD CONSTRAINT [PK_表名] PRIMARY KEY CLUSTERED ( 新主键字段 ASC)
PRINT '表名修改主键为新主键字段'
COMMIT
End
SELECT @keyColName = name FROM SysColumns WHERE id=Object_Id('表名') and colid=(select top 1 colid from sysindexkeys where id=Object_Id('表名'))
SELECT @keyColName
注意:只有字段类型为not null才能设置为主键。如果字段类型为可null,并且字段有做索引,因为有索引,用脚本很难操作,可以手动在表设计中将字段设置为not NULL。然后再用上面的脚本执行修改。