Friday, March 15, 2019

Grant Read & Write access on all user databases using tSQL, SQL Server


You can use below tSQL to grant any permission to a user.
Just modify it as your requirements.

Below script can be used to grant Read & Write access to all user databases...

NOTE: you have to run the printed output separately!
-------------------------


DECLARE @user_name    SYSNAME = 'ENET\azam'
DECLARE @SQL varchar(MAX)=''

SELECT @SQL = @SQL +char(10)+char(10)
       +'USE ' + QUOTENAME(NAME) + char(10)+'GO'+ char(10)
       +'CREATE USER '+QUOTENAME(@user_name)+' FOR LOGIN '+QUOTENAME(@user_name)+ char(10)+'GO'+ char(10)
       +'ALTER ROLE [db_datareader] ADD MEMBER '+QUOTENAME(@user_name)+ char(10)+'GO'+ char(10)
       +'ALTER ROLE [db_datawriter] ADD MEMBER '+QUOTENAME(@user_name)+ char(10)+'GO'+ char(10)
FROM   sys.databases
WHERE  database_id > 4
       AND state_desc = 'ONLINE'
       --and name like 'DEV_%'

print @SQL


Once you run this, you will get below code to run in another editor...

----  OUTPUT --- 
:: need to run below code separately...


USE
[dev_test_01]
GO
CREATE USER [ENET\azam] FOR LOGIN [ENET\azam]
GO
ALTER ROLE [db_datareader] ADD MEMBER [ENET\azam]
GO
ALTER ROLE [db_datawriter] ADD MEMBER [ENET\azam]
GO


USE [dev_test_02]
GO
CREATE USER [ENET\azam] FOR LOGIN [ENET\azam]
GO
ALTER ROLE [db_datareader] ADD MEMBER [ENET\azam]
GO
ALTER ROLE [db_datawriter] ADD MEMBER [ENET\azam]
GO


No comments:

Post a Comment