一个离开.NET的程序员

ryhan

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
--定义变量存储主键
DECLARE @Constraint_Name varchar(128)
--获取主键
SELECT @Constraint_Name = Name
FROM dbo.sysobjects
WHERE Xtype = 'PK'
and Parent_Obj =
(
SELECT [ID]
FROM dbo.sysobjects
WHERE id = OBJECT_ID(N'TestTableName')
and OBJECTPROPERTY(OBJECT_ID(N'TestTableName'), N'IsUserTable') = 1
)


PRINT @Constraint_Name
--删除原主键
EXEC ('ALTER TABLE TestTableName DROP CONSTRAINT '+@Constraint_Name )

--加入新自增长列并设置主键
IF EXISTS(SELECT * FROM syscolumns WHERE id=OBJECT_ID('TestTableName') and name='TestID')
BEGIN
ALTER TABLE TestTableName DROP COLUMN TestID
ALTER TABLE TestTableName ADD TestID BIGINT IDENTITY(1,1)
ALTER Table TestTableName ADD CONSTRAINT PK_TestTableName PRIMARY KEY (TestID)
END
ELSE 
 BEGIN
    ALTER TABLE TestTableName ADD TestID BIGINT IDENTITY(1,1)
    ALTER Table TestTableName ADD CONSTRAINT PK_TestTableName PRIMARY KEY (TestID)
 END

 

posted on 2011-11-03 15:29  ryhan  阅读(696)  评论(0编辑  收藏  举报