SQL SMO - checking if a user is a server admin

非 Y 不嫁゛ 提交于 2019-12-11 03:22:05

问题


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:


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'


来源:https://stackoverflow.com/questions/25206405/sql-smo-checking-if-a-user-is-a-server-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!