cannot be executed within a transaction
Hej,Jeg har lavet det her fine script til at oprette Read only brugere på alle databaser på en server. Men på to ud af 12 server får jeg fejlen:
Msg 15002, Level 16, State 1, Procedure sp_addrolemember, Line 16
The procedure 'sys.sp_addrolemember' cannot be executed within a transaction.
Er der en setting på de to servere som gør denne forskel:
CREATE TABLE #USERS (username VARCHAR(10),userpassword VARCHAR(10))
GO
INSERT INTO #USERS (username,userpassword) VALUES ('RO_dsj','12345')
GO
--TILFØJ EN RÆKKE PER PERSON
--INSERT INTO #USERS (username,userpassword) VALUES ('BRUGERNAVN','PASSWORD')
DECLARE
@user VARCHAR(10),
@password VARCHAR(10),
@db VARCHAR(50),
@script VARCHAR(max)
set @script = ''
BEGIN tran
DECLARE usercursor CURSOR FOR
SELECT username,userpassword FROM #USERS
OPEN usercursor
FETCH NEXT FROM usercursor INTO @user,@password
WHILE (@@FETCH_STATUS = 0)
BEGIN
set @script = 'USE MASTER'+CHAR(10)+CHAR(13)
set @script = @script+'IF NOT EXISTS (SELECT 1 FROM sys.syslogins WHERE loginname ='''+@user+''')'+CHAR(10)+CHAR(13)
set @script = @script+'BEGIN'+CHAR(10)+CHAR(13)
set @script = @script+'CREATE LOGIN ['+@user+'] WITH PASSWORD=N'''+@password+''' ,DEFAULT_DATABASE=[master], CHECK_POLICY=OFF'+CHAR(10)+CHAR(13)
set @script = @script+'END'+CHAR(10)+CHAR(13)
EXEC(@script)
DECLARE dbcursor CURSOR FOR
SELECT name FROM sys.databases
WHERE name NOT in ('master','model','msdb','tempdb')
OPEN dbcursor
FETCH NEXT FROM dbcursor INTO @db
WHILE (@@FETCH_STATUS = 0)
BEGIN
set @script = 'USE '+@db+CHAR(10)+CHAR(13)
set @script = @script+'IF NOT EXISTS (SELECT 1 FROM sys.sysusers WHERE name ='''+@user+''')'+CHAR(10)+CHAR(13)
set @script = @script+'BEGIN'+CHAR(10)+CHAR(13)
set @script = @script+ 'CREATE USER ['+@user+'] FOR LOGIN ['+@user+'] WITH DEFAULT_SCHEMA=[dbo]'+CHAR(10)+CHAR(13)
set @script = @script+'END'+CHAR(10)+CHAR(13)
set @script = @script+ 'Exec sp_addrolemember N''db_datareader'', '''+@user+''''+CHAR(10)+CHAR(13)
set @script = @script+ 'GRANT CONNECT TO ['+@user+']'+CHAR(10)+CHAR(13)
set @script = @script+ 'GRANT VIEW DEFINITION TO ['+@user+']'+CHAR(10)+CHAR(13)
--PRINT @script
EXEC(@script)
FETCH NEXT FROM dbcursor INTO @db
END
CLOSE dbcursor
DEALLOCATE dbcursor
FETCH NEXT FROM usercursor INTO @user,@password
END
GO
CLOSE usercursor;
GO
DEALLOCATE usercursor;
GO
commit tran
DROP TABLE #USERS
GO