Skip to main content

It's all about permissions - Part 2 ; TSQL Permissions users

Hi guys!

This post is simply on TSQL permissions.

Specifically, how to script out users and logins.

Users are specific to a SQL server instance while Logins can be used across a domain (via Active Directory).

Let's get started on how to script users.

This script has only one step.

--Check if ##stage tables exists, and if it does, drop it If exists (Select name from tempdb..sysobjects where name = '##scriptlogins') Drop Table ##scriptlogins Go --Create table that lists all staging tables to be purged Create table ##scriptlogins (listid int identity(1,1), script nvarchar(max)); Insert into ##scriptlogins SELECT 'Use ['+[name]+ ']' + char(13) +char(10) + ' If exists (Select name from tempdb..sysobjects where name = ''##Users'') Drop Table ##Users If exists (Select name from tempdb..sysobjects where name = ''xcur'') close xcur create table ##users ( row_order int not null identity (1, 1), sqltxt varchar(2000) null ) on [PRIMARY] Declare @UseCMD varchar(255) Set @UseCMD = ''use '' + db_name() + char(13) + char(10) + ''go'' + char(13) + char(10) insert into ##Users values (@usecmd) insert into ##Users select ''If exists (Select name from sysusers where name = ''''''+u.name+'''''') Drop User ['' + u.name + '']'' + char(13) + char(10) + ''go'' --+ '''''', @name_in_db='''''' + u.name + '''''''' + char(13) + char(10) + ''go'' from sysusers u inner join master..syslogins l on l.sid = u.sid where gid!=uid and u.name not in (''public'',''dbo'',''guest'',''INFORMATION_SCHEMA'',''sys'') insert into ##Users select ''Create User [''+ u.name + ''] For Login [''+ l.name + '']'' + char(13) +char(10)+''go'' from sysusers u inner join master..syslogins l on l.sid = u.sid where gid!=uid and u.name not in (''public'',''dbo'',''guest'',''INFORMATION_SCHEMA'',''sys'') insert into ##Users SELECT pe.state_desc COLLATE DATABASE_DEFAULT + '' '' + pe.permission_name COLLATE DATABASE_DEFAULT + '' to ['' + pr.name COLLATE DATABASE_DEFAULT + '']'' + char(13) +char(10) + ''go'' FROM sys.database_principals AS pr JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id where pe.permission_name not in (''Select'',''Connect'') Declare @rolename sysname declare xcur cursor for select name from sysusers where issqlrole = 1 or isapprole = 1 open xcur fetch xcur into @rolename while @@fetch_status=0 begin insert ##Users select ''ALTER ROLE ['' + @rolename + ''] ADD MEMBER ['' + u.name + ''] '' + char(13) +char(10) + ''go'' from sysusers u, sysusers g, sysmembers m where g.name=@rolename and g.uid=m.groupuid and g.issqlrole=1 and u.uid=m.memberuid fetch xcur into @rolename end close xcur deallocate xcur Delete from ##Users where sqltxt like ''ALTER ROLE%dbo%'' -- To allow advanced options to be changed. EXEC sp_configure ''show advanced options'', 1 -- To update the currently configured value for advanced options. RECONFIGURE -- To enable the feature. EXEC sp_configure ''xp_cmdshell'', 1 -- To update the currently configured value for this feature. RECONFIGURE select sqltxt from ##Users order by row_order Declare @bcpCMD varchar(200) Set @bcpCMD = ''bcp "select sqltxt from ##Users order by row_order" queryout C:\temp\Permissions2\'' +db_name()+ ''_RestoreUsers.sql -T -c -S SERVER'' exec master..xp_cmdshell @bcpCMD --EXEC sp_configure ''show advanced options'', 1 --GO ---- To update the currently configured value for advanced options. --RECONFIGURE --GO ---- To disable the feature. --EXEC sp_configure ''xp_cmdshell'', 0 --GO ---- To update the currently configured value for this feature. --RECONFIGURE --GO' FROM sys.databases Select * from ##scriptlogins --Loop that goes through the list of tables and truncates them based on the id declare @tableid int declare @sqltext nvarchar (max) Set @tableid = 1 While @tableid <= (Select max(listid) from ##scriptlogins) Begin Set @sqltext = (Select script from ##scriptlogins where listid = @tableid) exec sp_executesql @sqltext Set @tableid = @tableid + 1 End --drop table #scriptlogins


Note: You will need to update the path to the permissions location. The permissions location has your SQL file that will contain all the user permissions for the SQL server instance [currently at c:\Temp\Permissions in the script above]. You will also need to replace the name of the SERVER with your server name.
I.e. queryout C:\temp\Permissions2\'' +db_name()+ ''_RestoreUsers.sql -T -c -S SERVER''

After executing the script, you will now have at the location you specified [c:\Temp\Permissions] a SQL file that has permissions for all users of the SQL instance in addition to individual SQL files that contain user permissions for each database on your SQL server instance.


That's it!



If you have any questions related to this post, please put them below.


Thank you and Happy reading,

-marshé hutchinson
#learnSQLwithme

Comments

Popular posts from this blog

event id 101 task start failed - task scheduler event id 101 launch failure

Hello again. This post is related to automating SQL server tasks with Task Scheduler. In this example I was tasked with exporting SQL server agent jobs twice a month. To achieve this, I setup a task scheduler task that ran a PowerShell script that: establishes a local connection to the SQL server. cleans the file before writing to the .sql file to avoid adding on (appending) results on subsequent runs of the task scheduler task. when a connection is established, export the SQL agent jobs on the server to a .sql file on a remote server. sends a confirmation email via the SQL server database mail profile that the SQL agent jobs were exported to the specified remote server path. That was a mouthful. Now that you know my task scheduler task is calling a PowerShell script, let's get back to why it is failing.  The good news is this error is not related to the script. The error launch failure means the task could not even run. This is most likely due to a permissi

Msg 14234, Level 16, State 1, Procedure sp_verify_job, Line 199 The specified '@owner_login_name' is invalid (valid values are returned by sp_helplogins [excluding Windows NT groups]).

Hi guys! Here's another quick and easy post. Scenario I was trying to copy a SQL agent job from one server to another by just copying the script of that SQL job. You can copy any script by right clicking a job > Script job as > create to > new query window. I pasted the job on a different server and tried to execute it and received this error: Msg 14234, Level 16, State 1, Procedure sp_verify_job, Line 199 The specified '@owner_login_name' is invalid (valid values are returned by sp_helplogins [excluding Windows NT groups]). This error message is simply saying for the variable '@owner_login_name', the user account associated with the variable is incorrect because it does not exist. Fix Simply update the variable for '@owner_login_name' to a valid user account for the current SQL instance. Now when you execute the script again to create the SQL agent job your results will be: Command(s) completed successfully. If you have any furt

Executed as user: . Incorrect syntax near ''. [SQLSTATE 42000] (Error 102). The step failed.

Hi everyone! Today's post is about an all too common problem... syntax issues. Whether you fat-finger your keyboard or are always in a rush, chances are you have already encountered many syntax errors. But if you are a newbie,  your syntax error is just around the corner. No worries, this is an easy fix. Syntax errors just let you know part of your code or script is incorrect. Scenario I have a SQL agent job that is using the SQL command line to perform index maintenance, but it is failing. Here's my code : sqlcmd -E -S $(ESCAPE_SQUOTE(SRVR)) -d master -Q "EXECUTE dbo.IndexOptimize @Databases = ' databaseName ', @FragmentationLow = NULL, @FragmentationMedium = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', @FragmentationHigh = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', @FragmentationLevel1 = 5, @FragmentationLevel2 = 30, @UpdateStatistics = 'ALL',@WaitAtLowPriorityMaxDuration = 180, @WaitAtLowPriorityAbortA