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