July 5, 2011 at 12:58 pm
OK, I am testing a SQL Dev box. I P2V'd our Dev server into our Lab. Now I want to grant/add a user called "SQLLab" to ALL of the DB's on this DB server. I have the following script to iterate through all the db's...
DECLARE @DB_Name varchar(128)
DECLARE @DUMMY varchar(128)
DECLARE DBList CURSOR
FOR
SELECT name FROM sys.databases
WHERE name <> 'master' AND name <> 'model' AND name <> 'msdb' AND name <> 'Northwind' AND
name <> 'pubs' AND name <> 'tempdb'
ORDER BY name
OPEN DBList
FETCH NEXT FROM DBList
INTO @DB_Name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @DUMMY = 'USE [' + + @DB_Name + ']' + '; sp_grantdbaccess ' + CHAR(39) + 'SQLLab' + CHAR(39) + ';'
PRINT @DUMMY
EXEC (@DUMMY)
FETCH NEXT FROM DBList
INTO @DB_Name
END
CLOSE DBList
DEALLOCATE DBList
I'm pretty sure my scoping may be off or the t-sql isn't following the scope of the DB I wnat to get into in the "USE" statement. I get the following output on the first DB....
USE [_RESTORERECOVER]; sp_grantdbaccess 'SQLLab';
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'sp_grantdbaccess'.
I'm missing something but im drawing a blank....lol :crazy:
July 5, 2011 at 1:05 pm
i think all you need is EXEC in from of the proc: multi line statements require EXECUTE procname, only when a command is standalone can you just put the name of the proc.
SET @DUMMY = 'USE [' + + @DB_Name + ']' + '; EXEC sp_grantdbaccess ' + CHAR(39) + 'SQLLab' + CHAR(39) + ';'
Lowell
July 5, 2011 at 1:12 pm
THAT WAS IT!!!!
I knew I was forgetting something simple...... :hehe:
Thanks a bunch!
July 5, 2011 at 3:51 pm
As an alternative for you and others dropping by you can also fully qualify your proc reference like this:
SET @DUMMY = 'EXEC ' + @DB_Name + '.sys.sp_grantdbaccess ' +
CHAR(39) + 'SQLLab' + CHAR(39) + ';'
There are no special teachers of virtue, because virtue is taught by the whole community.
--Plato
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply