script out SQL user login wiht permission

Dear all,

any script / method for us to script out all user permission on a TEST DB as we are going to backup production DB and restore it to TEST DB.

this one doesn't works.

http://www.sqlservercentral.com/scripts/Security/71562/

error message is :
Msg 207, Level 16, State 1, Line 63
Invalid column name 'authentication_type'.
Msg 207, Level 16, State 1, Line 63
Invalid column name 'authentication_type'.

sys.database_principals do not have the column authentication_type
LVL 1
marrowyungSenior Technical architecture (Data)Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ramprakash JeyabalanCommented:
Try this.
CREATE TABLE #TT (ID INT IDENTITY,NAME VARCHAR(100))

INSERT INTO #LOGINS SELECT NAME FROM SYS.SERVER_PRINCIPALS WHERE TYPE = 'S' AND NAME <> 'SA'

DECLARE @CNT INT , @LOGINNAME VARCHAR(100)
SELECT @CNT = COUNT(1) FROM #LOGINS

WHILE @CNT<>0
BEGIN
   SELECT @LOGINNAME = NAME FROM #LOGINS WHERE ID = @CNT
   EXEC ('ALTER LOGIN ' + @LOGINNAME + ' DISABLE;')
   SET @CNT = @CNT - 1
END
GO

Open in new window

0
marrowyungSenior Technical architecture (Data)Author Commented:
I am sorry, this one only ALTER login but nothing related to permission script out, right? permission is much important.
0
Vitor MontalvãoMSSQL Senior EngineerCommented:
any script / method for us to script out all user permission on a TEST DB as we are going to backup production DB and restore it to TEST DB.
If you are going to restore from a backup why do you need to script the permissions? The permissions will be in the backup so when you restore the database in TEST they will be immediately there.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

marrowyungSenior Technical architecture (Data)Author Commented:
no we tried to restore production DB to TEST DB, so the permission will be mess up once restore,

developer can do much more on TEST than production.
0
Vitor MontalvãoMSSQL Senior EngineerCommented:
no we tried to restore production DB to TEST DB, so the permission will be mess up once restore,
 developer can do much more on TEST than production.
Maybe because the developer is using his own user instead of the application user? Don't forget that an user that has System Administrator role can do anything in any database. It has full access to everything.
0
marrowyungSenior Technical architecture (Data)Author Commented:
no, it is not, please check the link above, quite common in the world.
0
Yashwant VishwakarmaSQL DBACommented:
Are you looking to transfer logins from one server to another using backup and restore? If you are in this situation you can run below query on server where logins / users are existing:
USE master
GO
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
  DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
    @binvalue varbinary(256),
    @hexvalue varchar (514) OUTPUT
AS
DECLARE @charvalue varchar (514)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
  DECLARE @tempint int
  DECLARE @firstint int
  DECLARE @secondint int
  SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
  SELECT @firstint = FLOOR(@tempint/16)
  SELECT @secondint = @tempint - (@firstint*16)
  SELECT @charvalue = @charvalue +
    SUBSTRING(@hexstring, @firstint+1, 1) +
    SUBSTRING(@hexstring, @secondint+1, 1)
  SELECT @i = @i + 1
END

SELECT @hexvalue = @charvalue
GO
 
IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
  DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @type varchar (1)
DECLARE @hasaccess int
DECLARE @denylogin int
DECLARE @is_disabled int
DECLARE @PWD_varbinary  varbinary (256)
DECLARE @PWD_string  varchar (514)
DECLARE @SID_varbinary varbinary (85)
DECLARE @SID_string varchar (514)
DECLARE @tmpstr  varchar (1024)
DECLARE @is_policy_checked varchar (3)
DECLARE @is_expiration_checked varchar (3)

DECLARE @defaultdb sysname
 
IF (@login_name IS NULL)
  DECLARE login_curs CURSOR FOR

      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'
ELSE
  DECLARE login_curs CURSOR FOR


      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name
OPEN login_curs

FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
IF (@@fetch_status = -1)
BEGIN
  PRINT 'No login(s) found.'
  CLOSE login_curs
  DEALLOCATE login_curs
  RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
  IF (@@fetch_status <> -2)
  BEGIN
    PRINT ''
    SET @tmpstr = '-- Login: ' + @name
    PRINT @tmpstr
    IF (@type IN ( 'G', 'U'))
    BEGIN -- NT authenticated account/group

      SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']'
    END
    ELSE BEGIN -- SQL Server authentication
        -- obtain password and sid
            SET @PWD_varbinary = CAST( LOGINPROPERTY( @name, 'PasswordHash' ) AS varbinary (256) )
        EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT
        EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT
 
        -- obtain password policy state
        SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
        SELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
 
            SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']'

        IF ( @is_policy_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked
        END
        IF ( @is_expiration_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked
        END
    END
    IF (@denylogin = 1)
    BEGIN -- login is denied access
      SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name )
    END
    ELSE IF (@hasaccess = 0)
    BEGIN -- login exists but does not have access
      SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name )
    END
    IF (@is_disabled = 1)
    BEGIN -- login is disabled
      SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE'
    END
    PRINT @tmpstr
  END

  FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
   END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO
-------------------------------------------------------------------------


After executing above script run below command in query window:
EXEC sp_help_revlogin
and copy the script which will return as output and execute on the other server where you restored the database.

Read more
0
marrowyungSenior Technical architecture (Data)Author Commented:
Yashwant Vishwakarma,

"Are you looking to transfer logins from one server to another using backup and restore? "

nono , that one we can have script to create 2 x SP on Master DB and which doing what you are saying , but no.

look at the link what it is saying is, which is exactly what we are trying to do but I am not sure why I only need to take care it now !

also in a situation where we need to produce much closer execution plan to production platform in TEST platform we need to restore production DB to TEST DB as execution plan also depends on database size, number of records to make the best prediction and give a good execution plan.

so AFTER we restore production DB to TEST platform, we need to massage the sensitive information so that no sensitive information like customer credit card information will be in TEST platform.

so once restored ,as TEST platform (all developer can update/execute query) as diff permission than production (all developer can't ,just the application can update/execute query) , there will be chance that we don't want production permission to restore back to TEST.

In this case developer will rise up their hand and say they can't do works any more and they can't update/execute query any more.
0
Yashwant VishwakarmaSQL DBACommented:
Hi Marrowyung,

Try to execute query Script DB Level Permissions v2.1 which is as below:

DECLARE
    @sql VARCHAR(2048)
    ,@sort INT

DECLARE tmp CURSOR FOR


/*********************************************/
/*********   DB CONTEXT STATEMENT    *********/
/*********************************************/
SELECT '-- [-- DB CONTEXT --] --' AS [-- SQL STATEMENTS --],
  1 AS [-- RESULT ORDER HOLDER --]
UNION
SELECT 'USE' + SPACE(1) + QUOTENAME(DB_NAME()) AS [-- SQL STATEMENTS --],
  1 AS [-- RESULT ORDER HOLDER --]

UNION

SELECT '' AS [-- SQL STATEMENTS --],
  2 AS [-- RESULT ORDER HOLDER --]

UNION

/*********************************************/
/*********     DB USER CREATION      *********/
/*********************************************/

SELECT '-- [-- DB USERS --] --' AS [-- SQL STATEMENTS --],
  3 AS [-- RESULT ORDER HOLDER --]
UNION
SELECT 'IF NOT EXISTS (SELECT [name] FROM sys.database_principals WHERE [name] = ' + SPACE(1) + '''' + [name] + '''' + ') BEGIN CREATE USER ' + SPACE(1) + QUOTENAME([name]) + ' FOR LOGIN ' + QUOTENAME([name]) + ' WITH DEFAULT_SCHEMA = ' + QUOTENAME([default_schema_name]) + SPACE(1) + 'END; ' AS [-- SQL STATEMENTS --],
  4 AS [-- RESULT ORDER HOLDER --]
FROM sys.database_principals AS rm
WHERE [type] IN ('U', 'S', 'G') -- windows users, sql users, windows groups

UNION

/*********************************************/
/*********    DB ROLE PERMISSIONS    *********/
/*********************************************/
SELECT '-- [-- DB ROLES --] --' AS [-- SQL STATEMENTS --],
  5 AS [-- RESULT ORDER HOLDER --]
UNION
SELECT 'EXEC sp_addrolemember @rolename ='
 + SPACE(1) + QUOTENAME(USER_NAME(rm.role_principal_id), '''') + ', @membername =' + SPACE(1) + QUOTENAME(USER_NAME(rm.member_principal_id), '''') AS [-- SQL STATEMENTS --],
  6 AS [-- RESULT ORDER HOLDER --]
FROM sys.database_role_members AS rm
WHERE USER_NAME(rm.member_principal_id) IN (
            --get user names on the database
            SELECT [name]
            FROM sys.database_principals
            WHERE [principal_id] > 4 -- 0 to 4 are system users/schemas
            and [type] IN ('G', 'S', 'U') -- S = SQL user, U = Windows user, G = Windows group
             )
--ORDER BY rm.role_principal_id ASC


UNION

SELECT '' AS [-- SQL STATEMENTS --],
  7 AS [-- RESULT ORDER HOLDER --]

UNION

/*********************************************/
/*********  OBJECT LEVEL PERMISSIONS *********/
/*********************************************/
SELECT '-- [-- OBJECT LEVEL PERMISSIONS --] --' AS [-- SQL STATEMENTS --],
  8 AS [-- RESULT ORDER HOLDER --]
UNION
SELECT CASE
   WHEN perm.state <> 'W' THEN perm.state_desc
   ELSE 'GRANT'
  END
  + SPACE(1) + perm.permission_name + SPACE(1) + 'ON ' + QUOTENAME(SCHEMA_NAME(obj.schema_id)) + '.' + QUOTENAME(obj.name) --select, execute, etc on specific objects
  + CASE
    WHEN cl.column_id IS NULL THEN SPACE(0)
    ELSE '(' + QUOTENAME(cl.name) + ')'
    END
  + SPACE(1) + 'TO' + SPACE(1) + QUOTENAME(USER_NAME(usr.principal_id)) COLLATE database_default
  + CASE
    WHEN perm.state <> 'W' THEN SPACE(0)
    ELSE SPACE(1) + 'WITH GRANT OPTION'
    END
   AS [-- SQL STATEMENTS --],
  9 AS [-- RESULT ORDER HOLDER --]
FROM
 sys.database_permissions AS perm
  INNER JOIN
 sys.objects AS obj
   ON perm.major_id = obj.[object_id]
  INNER JOIN
 sys.database_principals AS usr
   ON perm.grantee_principal_id = usr.principal_id
  LEFT JOIN
 sys.columns AS cl
   ON cl.column_id = perm.minor_id AND cl.[object_id] = perm.major_id
--WHERE usr.name = @OldUser
--ORDER BY perm.permission_name ASC, perm.state_desc ASC



UNION

SELECT '' AS [-- SQL STATEMENTS --],
 10 AS [-- RESULT ORDER HOLDER --]

UNION

/*********************************************/
/*********    DB LEVEL PERMISSIONS   *********/
/*********************************************/
SELECT '-- [--DB LEVEL PERMISSIONS --] --' AS [-- SQL STATEMENTS --],
  11 AS [-- RESULT ORDER HOLDER --]
UNION
SELECT CASE
   WHEN perm.state <> 'W' THEN perm.state_desc --W=Grant With Grant Option
   ELSE 'GRANT'
  END
 + SPACE(1) + perm.permission_name --CONNECT, etc
 + SPACE(1) + 'TO' + SPACE(1) + '[' + USER_NAME(usr.principal_id) + ']' COLLATE database_default --TO <user name>
 + CASE
   WHEN perm.state <> 'W' THEN SPACE(0)
   ELSE SPACE(1) + 'WITH GRANT OPTION'
   END
  AS [-- SQL STATEMENTS --],
  12 AS [-- RESULT ORDER HOLDER --]
FROM sys.database_permissions AS perm
 INNER JOIN
 sys.database_principals AS usr
 ON perm.grantee_principal_id = usr.principal_id
--WHERE usr.name = @OldUser

WHERE [perm].[major_id] = 0
 AND [usr].[principal_id] > 4 -- 0 to 4 are system users/schemas
 AND [usr].[type] IN ('G', 'S', 'U') -- S = SQL user, U = Windows user, G = Windows group

UNION

SELECT '' AS [-- SQL STATEMENTS --],
  13 AS [-- RESULT ORDER HOLDER --]

UNION

SELECT '-- [--DB LEVEL SCHEMA PERMISSIONS --] --' AS [-- SQL STATEMENTS --],
  14 AS [-- RESULT ORDER HOLDER --]
UNION
SELECT CASE
   WHEN perm.state <> 'W' THEN perm.state_desc --W=Grant With Grant Option
   ELSE 'GRANT'
   END
    + SPACE(1) + perm.permission_name --CONNECT, etc
    + SPACE(1) + 'ON' + SPACE(1) + class_desc + '::' COLLATE database_default --TO <user name>
    + QUOTENAME(SCHEMA_NAME(major_id))
    + SPACE(1) + 'TO' + SPACE(1) + QUOTENAME(USER_NAME(grantee_principal_id)) COLLATE database_default
    + CASE
     WHEN perm.state <> 'W' THEN SPACE(0)
     ELSE SPACE(1) + 'WITH GRANT OPTION'
     END
   AS [-- SQL STATEMENTS --],
  15 AS [-- RESULT ORDER HOLDER --]
from sys.database_permissions AS perm
 inner join sys.schemas s
  on perm.major_id = s.schema_id
 inner join sys.database_principals dbprin
  on perm.grantee_principal_id = dbprin.principal_id
WHERE class = 3 --class 3 = schema


ORDER BY [-- RESULT ORDER HOLDER --]


OPEN tmp
FETCH NEXT FROM tmp INTO @sql, @sort
WHILE @@FETCH_STATUS = 0
BEGIN
        PRINT @sql
        FETCH NEXT FROM tmp INTO @sql, @sort    
END

CLOSE tmp
DEALLOCATE tmp
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
marrowyungSenior Technical architecture (Data)Author Commented:
so this one is older?

any verison of SQL server it don't work out with ?
0
Yashwant VishwakarmaSQL DBACommented:
I tried it on SQL Server 2012 Enterprise edition it was working fine.
for other version I don't have any idea.
0
marrowyungSenior Technical architecture (Data)Author Commented:
Victor and all,

first of all, this is not a migration, I think this is true as long as the master DB MIGRATE to the TEST server too but it is not, agree?

 for migration point of view you are right, as I also did so many time and as long as the production user DB as well as production master DB all goes to the TEST server, then there will be ok.

 What if the TEST server's login and permission always diff from production one, then there will be a problem.

 we just have a problems here and before I come problem and everything the time production DB refresh to TEST, TEST SQL server will have a lot of TSET SQL user can't login/permission changed.

 because the MASTER DB of TEST DB hasn't change but user DB keep refreshing from production.
0
marrowyungSenior Technical architecture (Data)Author Commented:
Yashwant Vishwakarma,

tks for telling me SQL 2012 is working for that but I have fixed V3, tks for that.

I think we will use SQL server 2014 with SP1, you have this one in house, right? will it works on SQL 2014 too ?
0
Yashwant VishwakarmaSQL DBACommented:
Hi Marrowyung,
I have only SQL Server 2012 on my PC.
0
marrowyungSenior Technical architecture (Data)Author Commented:
ok. tks anyway

heard that SQL 2012 has problems, experiencing now ?
0
marrowyungSenior Technical architecture (Data)Author Commented:
tks all.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.