这篇文章主要介绍“SQL Server怎么导出db所有用户权限创建语句”,在日常操作中,相信很多人在SQL Server怎么导出db所有用户权限创建语句问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”SQL Server怎么导出db所有用户权限创建语句”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
use db
go
DECLARE
@Database varchar(255),
@loginName varchar(255),
@roleName varchar(255),
@sql nvarchar(max);
SET @sql=N'';
DECLARE curLogin CURSOR LOCAL for
select db_name() as dbname,dp.name as username,dpr.name as rolename
from sys.database_principals dp
join sys.database_role_members drm on drm.member_principal_id=dp.principal_id
join sys.database_principals dpr on drm.role_principal_id=dpr.principal_id
join sys.server_principals sp on sp.name=dp.name
where 1=1
--and dpr.is_fixed_role=1
and dp.type<>'R'
and dp.type in('S','U','G') --SQL USER,WINDOWS USER AND windows group
order by username,rolename
OPEN curLogin;
FETCH NEXT FROM curLogin INTO @Database,@loginName,@roleName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql=@sql+N'
use '+@Database+';
if not exists(select * from '+@Database+'.sys.database_principals where name='''+@LoginName+''')
begin
CREATE USER '+QUOTENAME(@LoginName)+';
end
else
begin
ALTER USER '+QUOTENAME(@LoginName)+' with login = '+QUOTENAME(@LoginName)+'
end
;
'
--print @sql
--exec sp_executesql @sql
select @sql=@sql+N'
use '+@Database+';
exec sp_addrolemember '''+@roleName+''', ''' + @LoginName + ''''
--exec sp_executesql @sql
FETCH NEXT FROM curLogin INTO @Database,@loginName,@roleName;
END
CLOSE curLogin
DEALLOCATE curLogin
;
--select len(@sql)
--print @sql --this will be truncated
exec sysadmin.dbo.printmax @sql
go
到此,关于“SQL Server怎么导出db所有用户权限创建语句”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!