So I’m trying to learn SQLCLR and have chosen to write a table-valued function that essentially gathers some perfmon counters. I’m able to run it successfully and gather counters from the server that hosts the database instance. However, when I try to access counters on another server, I get “access denied”. I’m able to get it to work if I add the account that runs the SQL Server to the “Performance Monitor Users” group on the remote server, but I want to know if I can have the function run as a different windows account? That is to say, can I create a Windows account specifically for this task and somehow have SQL Server run the function in that context?
Share
No, you cannot have the SQLCLR function run as a specific user. You may hear about use of
LogonUserAPI to impersonate an user in the SQLCLR function but that approach is fraud with problems, particularly because of the issue of password storage. The correct solution is exactly what you did, grant the SQL Server account the needed privileges by adding him to the required security group. BTW, in case your SQLCLR function impersonates the current Windows login you will need to set up constrained delegation.That being said, using SQLCLR to connect to a remote machine for anything is not a smart thing to do. Stealing the precious SQL Server workers to have them wait on slow network access is going to grind your server to a halt under load. You can do this as a way to learn how to do it, but don’t even think about deploying it in production. Have the counter collection be done by an external process and save the counter in the database. In fact, there is already a tool that does exactly that:
logman.exe.And finally: querying performance counters from the C# API is extremity inefficient. You will quickly discover that there is a much faster API, the PDH library. But PDH has no manage equivalent, so you’ll be back at square one, namely use the tool that does leverage PDH out-of-the-box:
logman.exe.