How are CLR (.NET) objects managed in SQL Server?
The entry point to any CLR code from SQL Server is a static method. Typically you\'ll only create objects that exi
Not conceivably; you very much can create static members. BUT, they need to be marked as readonly
for assemblies that have a PERMISSION_SET
of either SAFE
or EXTERNAL_ACCESS
. Only an assembly marked as UNSAFE
can have writable static members. And this restriction is due to the very nature of static members: they are shared between threads and sessions.
An assembly is loaded the first time a method within it is accessed. It is shared for all sessions to use, which is why only static methods are accessible. The idea is to write functions, not an application, so there isn't a lot of use in keeping state. And it can easily (though certainly not always) lead to unpredictable behavior if various sessions are overwriting each other. So concurrency isn't handled at all, unless you write that part yourself.
It should be expected that once loaded, the class (and the App Domain it resides in) will remain in memory until either the SQL Server service restarts or the PERMISSION_SET
value is changed. But this is not guaranteed. According to this page, Memory Usage in SQL CLR:
when there is memory pressure on the server, SQL CLR will try to release memory by explicitly running garbage collection and, if necessary, unloading appdomains.
So you are correct on both counts regarding static members:
And, the amount of memory available for CLR routines varies greatly depending on whether SQL Server is 32 or 64 bit, and whether you are using SQL Server 2005 / 2008 / 2008 R2 or using SQL Server 2012 / 2014. For more info on how much memory SQLCLR has to play with, check out SQL Server 2012 Memory and Memory Usage in SQL CLR (same as the first link, posted above the quote).