午后红茶 2012-11-24
--SQL创建数据库中所有用户数据表自增一主键
--主键说明:名称为ID,数据类型为整形自增一
--查询创建前的当前数据库所有约束
select * from information_schema.key_column_usage
declare @TableName nvarchar(250)
declare @ColumnName nvarchar(250)
set @ColumnName='ID'
--声明读取数据库所有数据表名称游标mycursor1
declare mycursor1 cursor for select name from dbo.SysObjects WHERE OBJECTPROPERTY(ID, 'ISUSErTable') = 1
--打开游标
open mycursor1
--从游标里取出数据赋值到我们刚才声明的数据表名变量中
fetch next from mycursor1 into @TableName
--如果游标执行成功
while (@@fetch_status=0)
begin
--如果存在主键列
IF EXISTS (select * from syscolumns Where ID=OBJECT_ID(N'['+@TableName+']') and name=''+@ColumnName+'')
begin
exec ('ALTER TABLE ['+@TableName+'] DROP COLUMN '+@ColumnName+'')
end
exec ('ALTER TABLE ['+@TableName+'] ADD '+@ColumnName+' [int] IDENTITY(1,1) NOT NULL PRIMARY KEY')
--用游标去取下一条记录
fetch next from mycursor1 into @TableName
end
--关闭游标
close mycursor1
--撤销游标
deallocate mycursor1
--查询创建后的当前数据库所有约束
select * from information_schema.key_column_usage