Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Administration
 Granting access on multiple databases

Author  Topic 

parlagi
Starting Member

1 Post

Posted - 2009-11-11 : 13:21:12
I was hoping to grant data reader access in several databases at once for a report login. Unfortunately, when I try the following, I get an "Incorrect syntax near @name" error.

Is there a query that can do this, or do you have to go through each database one at a time?

DECLARE @name VARCHAR(50) -- database name  

DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name LIKE '2009%'

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
use @name --Error points here.
go
exec sp_addrolemember db_datareader, reportuser
go
FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor
DEALLOCATE db_cursor

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-11-11 : 13:25:51
Remove the USE statement and instead put EXEC @name.dbo.sp_addrolemember into dynamic SQL.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page
   

- Advertisement -