>>Script Language and Platform: SQL Server 2000
This code will loop through all user tables in all databases and grant select permissions on each table. It will add the user from the variables set at the beginning of the script if the user does not already have access to each database. This script can be modified for whatever object types or permissions you need. PRINT statements can be “un-commented” in case debug output is desired. Tested for SQL 2000, but not yet for SQL 2005 (filters for schemas may be required).
Take care to use security-based scripts wisely and always test first!
Author: Pat Johnson
/*************************************************************************Script: Permissions Loop
Purpose: Loop thru objects in multiple databases and grant
specific permissions on specific objects.
Filters can be added in WHERE clauses as needed.
Author: Pat Johnson (johns_9998@yahoo.com)
Date: 9/29/2008**************************************************************************/
DECLARE
@LoginName VARCHAR(128),
@UserName VARCHAR(128),
@DatabaseName VARCHAR(100),
@SQLScript VARCHAR(6000)SET @LoginName = ‘LoginName’ — Can be Windows login such as ‘DOMAINLoginName’
SET @UserName = ‘UserName’ — Many times the same as the LoginNameIF EXISTS (SELECT * FROM master..syslogins WHERE [name] = @LoginName)
BEGIN
DECLARE DatabaseCursor CURSOR FOR
SELECT [name] FROM master..sysdatabases
ORDER BY [name]OPEN DatabaseCursor
FETCH NEXT FROM DatabaseCursor INTO @DatabaseNameWHILE @@FETCH_STATUS = 0
BEGINPRINT ‘Updating Database: ‘ + @DatabaseName + ”
SET @SQLScript = ‘
USE ‘ + @DatabaseName + ‘
IF NOT EXISTS (SELECT * FROM ‘ + @DatabaseName + ‘..sysusers WHERE [name] = ”’ + @UserName + ”’)
EXEC SP_ADDUSER ”’ + @LoginName + ”’,”’ + @UserName + ””— PRINT @SQLScript
EXEC (@SQLScript)— Modify script below to change object types or type of permissions: U = User table, etc.
SET @SQLScript = ‘
USE ‘ + @DatabaseName + ‘
DECLARE
@TableName VARCHAR(100),
@SQLScript VARCHAR(4000)DECLARE TableCursor CURSOR FOR
SELECT [name] FROM ‘ + @DatabaseName + ‘..sysobjects WHERE type = ”U” ORDER BY [name]
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQLScript = ”GRANT SELECT ON ” + @TableName + ” TO ‘ + @UserName + ”’
— PRINT @SQLScript
EXEC(@SQLScript)FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor’— PRINT @SQLScript
EXEC (@SQLScript)FETCH NEXT FROM DatabaseCursor INTO @DatabaseName
END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor
END
ELSE PRINT ‘Login ‘ + @LoginName + ‘ does not exist.’
Disclaimer: We hope that the information on these script pages is valuable to you. Your use of the information contained in these pages, however, is at your sole risk. All information on these pages is provided “as -is”, without any warranty, whether express or implied, of its accuracy, completeness, or fitness for a particular purpose… Disclaimer Continued
Back to Database Journal Home