Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a Windows user to the sysadmin server role in SQL Server 2012? [closed]

Tags:

sql-server

I have a Powershell script that executes in the context of a Windows user. This user has a login on a SQL 2012 instance that is a member of the sysadmin server role.

I want the script to add another login on the SQL instance (which also has a corresponding Windows user) to the sysadmin server role.

To try this out in Management Studio (connected as SA), I'm using the following script:

execute as user = 'domain\currentsysadmin'

IF IS_SRVROLEMEMBER('sysadmin', 'domain\futuresysadmin') != 1
    ALTER SERVER ROLE [sysadmin] ADD MEMBER [domain\futuresysadmin]

revert

I have two issues here:

  1. When I run the script as it's displayed here, the call to IS_SRVROLEMEMBER returns 0 as expected, but even though the domain\currentsysadmin login is a member of sysadmin, the call to ALTER SERVER ROLE returns:

    Msg 15151, Level 16, State 1, Line 8 Cannot alter the server role 'sysadmin', because it does not exist or you do not have permission.

  2. When I run this in the context of SA without the EXECUTE AS statement, the ALTER SERVER ROLE statement appears to run successfully, but when I check the domain\futuresysadmin login, it is still not a member of the sysadmin role

How can I add the domain\futuresystem login to the sysadmin server role?

like image 741
drewmullet Avatar asked Dec 10 '12 18:12

drewmullet


1 Answers

Use sp_addsrvrolemember:

EXEC master..sp_addsrvrolemember @loginame = N'domain\futuresysadmin', @rolename = N'sysadmin'

UPDATE: User context switching doesn't inherit any server roles, like sysadmin. In reading the documentation: "Server-level permissions granted explicitly to identities in the user token or through role memberships are not honored." When you switch user context, your user no longer has the right to grant sysadmin to another user.

like image 104
JVC Avatar answered Oct 12 '22 21:10

JVC