查询数据库没有主键的表名并增加主键

declare @tablename sysname
declare @strsql nchar(500)
declare tableNameCursor cursor for
select b.name from sysobjects b where xtype='U' and  b.name not in 
(select object_name(a.parent_obj)  from sysobjects a where xtype='PK' )

open tableNameCursor  
fetch next from tableNameCursor into @tablename
while @@FETCH_STATUS = 0
begin
	print @tablename
	set @strsql= 'alter table ' + @tablename + ' add primary key (id) '
	print @strsql
	exec (@strsql)
	fetch next from tableNameCursor into @tablename
end
close tableNameCursor
deallocate  tableNameCursor

游标的使用

sysobjects对象的使用http://www.yesky.com/imagesnew/software/tsql/ts_sys-o_4zll.htm

posted @ 2011-08-02 11:39  acjialiren  阅读(540)  评论(0编辑  收藏  举报