SQL SMO - checking if a user is a server admin

2k Views Asked by At

I want to check if the connected user is a SQL Server admin (in the sysadmin role) and wondering if this is this is the best way to do it?

private static bool IsUserAdmin(Server server)
{
   Login login = server.Logins[server.ConnectionContext.Login];
   return login.IsMember("sysadmin");
}

In SQL DMO (the COM based predecessor to SMO) there was a property that hung off the SQLDMO.SQLServer object called IsServerAdmin. I'm wondering if there's something similar in SMO but that I just haven't been able to find it?

1

There are 1 best solutions below

1
On BEST ANSWER

Yes, actually I think yours is the best way to check if the current login is a SQL Server administrator (that then is a member of sysadmin role).

I have some experience with SMO and I found no other way better than this, also because there's no property similar to IsServerAdmin listed in the SMO documentation related to the Login object.

If you want, you can execute a T-SQL query to know which SQL Server Logins are members of sysadmin role (that will give you the same results of C# code):

SELECT p.name AS [Name] ,r.type_desc,r.is_disabled,r.create_date , r.modify_date,r.default_database_name
FROM
sys.server_principals r
INNER JOIN sys.server_role_members m ON r.principal_id = m.role_principal_id
INNER JOIN sys.server_principals p ON
p.principal_id = m.member_principal_id
WHERE r.type = 'R' and r.name = N'sysadmin'