如何进行 SQL Server 批理修改权限

网络整理 - 07-27

问题:在机器备份的数据库到SQL Server,恢复后该数据库有一个mooip用户,该用户是数据库和一些表的所有者,但安全性里的登录中没有该用户,在删除该用户时提示“因为选定的用户拥有对象,所以无法除去该用户”。遇到这类问题不要慌张,按着该文介绍的方法一步步操作即可。

具体解决方式如下:

1、如果是一张表有此问题,解决方式如下:

exec sp_changeobjectowner 'mooip.tablename', 'dbo'这样就把tablename指定的表的所有者赋值给了dbo用户。

2 、如果所有表都存在此问题,这是就要编写存储过程实现批量修改了

IF OBJECT_ID('ChangeAll') IS NOT NULL Drop PROC ChangeAll
         GO

         Create PROCEDURE ChangeAll (
             @old sysname,
             @new sysname
         )
        AS
             DECLARE @objname sysname

             SET NOCOUNT ON

             IF USER_ID(@old) IS NULL
                BEGIN
                    RAISERROR ('The @old passed
                does not exist in the database', 16, 1)
                    RETURN
                END
             IF USER_ID(@new) IS NULL
                BEGIN
                    RAISERROR ('The @new passed
                does not exist in the database', 16, 1)
                    RETURN
                END

             DECLARE owner_cursor CURSOR FOR

             Select name FROM sysobjects
              Where uid = USER_ID(@old)
             OPEN owner_cursor
             FETCH NEXT FROM owner_cursor INTO @objname
             WHILE (@@fetch_status <> -1)
                 BEGIN
                     SET @objname = @old + '.' + @objname
                     EXEC sp_changeobjectowner @objname, @new
                     FETCH NEXT FROM owner_cursor INTO @objname
                 END

            CLOSE owner_cursor
            DEALLOCATE owner_cursorz
            GO

             EXEC ChangeAll @old = 'mooip', @new = 'dbo'

这样就你就完成了批量修改权限的工作