何查询SQL Server数据库没有主键的表并增加主键

时间:2023-03-08 21:43:47
何查询SQL Server数据库没有主键的表并增加主键

SQL Server数据库中,如果一个表没有主键,我们该如何查询呢?本文我们主要就介绍了如何查询数据库中没有主键的表名并为其增加主键的方法,希望能够对您有所帮助。

该功能的实现代码如下:

    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 

以上就是SQL Server数据库中查询没有主键的表的名称并为其增加主键的实现代码