我希望能够为登录创建用户并分配一些权限,我想对名称为>的数据库执行此操作。 4这就是我所拥有的
EXEC sp_MSForEachDB
'Declare @name varchar(100), @UserToAdd VARCHAR(100) = ''HQ\tname''
select @name = ''?''
PRINT @name
IF db_id(@name) > 4
BEGIN
USE ?
EXEC (''CREATE USER ['' + @UserToAdd + ''] FOR LOGIN ['' + @UserToAdd + ''];'')
EXEC (''EXEC sp_addrolemember N''db_datareader'', N'''' + @UserToAdd + '''';'')
END'

我在使用多个引号的语法方面遇到了一些问题,如果我只是为单个数据库运行它,我知道它使用以下代码
DECLARE @UserToAdd VARCHAR(100) = 'HQ\tname'
BEGIN
USE [dbnamehere]
EXEC ('CREATE USER [' + @UserToAdd + '] FOR LOGIN [' + @UserToAdd + '];')
EXEC ('EXEC sp_addrolemember N''db_datareader'', N''' + @UserToAdd + ''';')
END

有人可以帮忙解决语法吗?
答案 0 :(得分:0)
一种方法是使用光标:
declare
@sql nvarchar(max),
@db sysname,
@UserToAdd sysname = 'HQ\tname';
declare db_cursor cursor local fast_forward for
select
name
from
sys.databases
where
database_id > 4;
open db_cursor;
fetch next from db_cursor into @db;
while @@fetch_status = 0
begin
set @sql = 'use ' + quotename(@db) + ';
create user ' + quotename(@UserToAdd) + ' for login ' + quotename(@UserToAdd) + ';
exec sp_addrolemember ''db_datareader'', ' + quotename(@UserToAdd, '''') + ';';
exec sp_executesql @sql;
fetch next from db_cursor into @db;
end;
close db_cursor;
deallocate db_cursor;