Skip to main content

Posts

Showing posts with the label dynamic management views

Generate SQL script to extract user permissions from a SQL database

When you restore a database, it will also restore all permissions along with it. But what if you are restoring over an existing database and it has different sets of permissions and you would like to preserve those after the restore? For example, due to security policy of your organization or client the users in test and production are different, have different names, permissions etc... A while back I was faced with exactly that and I decided to write a set of scripts to extract user permissions before restoring over the database. Fix orphaned users, if any. SELECT Db_name()     DB,        NAME,        sid,        'exec sp_change_users_login ''Auto_Fix'',''' + NAME + '''' cmd FROM   sysusers u WHERE  1 = 1        AND issqlrole = 0        AND sid IS NOT NULL        AND sid != 0x00        AND NOT EXISTS (SELECT * FROM...