Database Administrators
Q&A for database professionals who wish to improve their database skills
Latest Questions
1
votes
1
answers
635
views
View T-SQL in CLR Assembly
I have a production database with numerous scalar functions. My goal is to create set based alternatives for reporting. Unfortunately, I don't have a good way to view the T-SQL actually being executed because the functions reference a CLR assembly. Is there a good way to view the T-SQL inside the as...
I have a production database with numerous scalar functions. My goal is to create set based alternatives for reporting. Unfortunately, I don't have a good way to view the T-SQL actually being executed because the functions reference a CLR assembly. Is there a good way to view the T-SQL inside the assembly for each function?
DraftinBandit
(61 rep)
Dec 5, 2019, 07:32 PM
• Last activity: May 10, 2025, 01:03 AM
9
votes
3
answers
1066
views
Azure SQL Database CLR functions are working
I'm in the middle of migrating a database to Azure SQL Database. I was reading about the differences between Azure SQL Database and Azure Managed Instance and noticed that CLR functions are NOT supported in Azure SQL Database. This surprised me as I've already loaded a test version of the database i...
I'm in the middle of migrating a database to Azure SQL Database. I was reading about the differences between Azure SQL Database and Azure Managed Instance and noticed that CLR functions are NOT supported in Azure SQL Database.
This surprised me as I've already loaded a test version of the database into Azure SQL Database and nobody complained about issues. I looked and sure enough, the CLR assembly is there and running queries that use the CLR functions work just fine.
So I went searching the web, and all the information I see is that CLR does not work with Azure SQL Database. Yet here I am, with a working CLR assembly in Azure SQL Database.
So now I'm wondering, do I tell the business we have to switch to use Managed Instance because that's the only place that CLR is supported? Or stick with Azure SQL Database because it's working fine? Or have I missed something? Did Microsoft re-enable CLR without telling anyone?
paulH
(1642 rep)
Sep 25, 2024, 09:18 AM
• Last activity: Sep 27, 2024, 09:27 AM
0
votes
2
answers
145
views
CLR 1-row table valued function or user defined type?
I'm working with a database of web spidering data and I'm trying to leverage the C# Uri class via CLR to help with traffic analysis. My first pass was to create a CLR table valued function (that returns only 1 row) and CROSS APPLY to break up the urls into the component parts for review, but I'm fin...
I'm working with a database of web spidering data and I'm trying to leverage the C# Uri class via CLR to help with traffic analysis.
My first pass was to create a CLR table valued function (that returns only 1 row) and CROSS APPLY to break up the urls into the component parts for review, but I'm finding adding that CROSS APPLY really slows down queries (like doing a query with LIKE over the database can take 5-8 minutes, but CROSS APPLY and looking at the host value takes 45 minutes kind of thing)
I was wondering if it might be faster to implement the Uri interface as a user defined type and work that into my queries instead? I haven't done a lot of user defined types, but I thought knowing there would only ever be 1 response object might lighten some of the overhead in Sql Server. Would a UDT perform better in a query?
My tvf implementation currently looks like this:
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, IsPrecise = true, Name = "ufn_UrlParts", SystemDataAccess = SystemDataAccessKind.None, FillRowMethodName = "GetUrlParts")]
public static IEnumerable UrlParts(SqlString input)
{
if (!input.IsNull && Uri.TryCreate(input.Value, UriKind.Absolute, out Uri url) && url.Valid(false))
yield return url;
yield break;
}
private static void GetUrlParts(object input, out string scheme, out string userinfo, out string host, out int hostType, out int port, out bool isdefaultPort, out string path, out string query)
{
Uri u = input as Uri;
scheme = u?.Scheme;
userinfo = u?.UserInfo;
host = u?.Host;
hostType = (int)(u?.HostNameType ?? UriHostNameType.Unknown);
port = u?.Port ?? 0;
isdefaultPort = u?.IsDefaultPort ?? false;
path = u?.AbsolutePath;
query = u?.Query;
}
user1664043
(379 rep)
Aug 6, 2024, 05:00 PM
• Last activity: Aug 8, 2024, 07:46 PM
3
votes
2
answers
456
views
How can I access SQLCLR assembly functions in MySQL
We have an SQLCLR assembly (DLL-file) built in C# that contains about 100 functions that we call from store procedures in SQL Server databases. Is is possible to call these functions in MySQL store procedures as well ? How ??
We have an SQLCLR assembly (DLL-file) built in C# that contains about 100 functions
that we call from store procedures in SQL Server databases.
Is is possible to call these functions in MySQL store procedures as well ?
How ??
user291050
(31 rep)
Jun 4, 2024, 02:14 PM
• Last activity: Jun 4, 2024, 03:33 PM
1
votes
0
answers
582
views
CLR unloaded due to security data definition language
Today, we got a very weird situation. We added a SQL login to our database server. After adding this login, SQL unloaded a critical CLR routine "due to security data definition language" (error 10310). As a result several user processed crashed. The CLRs unloaded in all the registered databases, but...
Today, we got a very weird situation. We added a SQL login to our database server. After adding this login, SQL unloaded a critical CLR routine "due to security data definition language" (error 10310). As a result several user processed crashed. The CLRs unloaded in all the registered databases, but the new login had nothing to do with these databases. The databases using the CLR have the TRUSTWORTHY setting to on.
Any idea why creating a regular SQL login is causing this issue? It's certainly NOT a memory issue, plenty of GB available for the OS. We fixed this issue by executing TRUSTWORTHY and registering the CLR, but we're a little afraid if this happens again when adding another login.
Configuration: SQL server 2019 CU20 Enterprise, 512GB memory, 384GB for SQL
Wilfred van Dijk
(21 rep)
Jun 28, 2023, 02:33 PM
7
votes
2
answers
5777
views
Is there a way to use standard CLR functions on Azure SQL Edge for Ubuntu Docker on an M1 Mac?
I have a MacBook with an M1 chip, so (about) the only option for me to run SQL Server is to [run it as a Docker container](https://database.guide/how-to-install-sql-server-on-an-m1-mac-arm64/). This works fine for standard SQL, but our application uses some CLR features like [`COMPRESS`](https://lea...
I have a MacBook with an M1 chip, so (about) the only option for me to run SQL Server is to [run it as a Docker container](https://database.guide/how-to-install-sql-server-on-an-m1-mac-arm64/) . This works fine for standard SQL, but our application uses some CLR features like [
COMPRESS
](https://learn.microsoft.com/en-us/sql/t-sql/functions/compress-transact-sql) ; when I try to use that, it tells me
> Msg 50000, Level 16, State 1, Line 45
Common Language Runtime(CLR) is not enabled on this instance.
[Enabling it](https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration/clr-integration-enabling) does not work:
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
GO
gives
> Msg 15392, Level 16, State 1, Procedure sp_configure, Line 166
The specified option 'clr enabled' is not supported by this edition of SQL Server and cannot be changed using sp_configure.
I found [this Stack Overflow post](https://stackoverflow.com/q/59690813/4751173) but that is about someone using a custom .NET library; I'm looking for the 'standard' functionality available in SQL Server for Windows.
Glorfindel
(2205 rep)
Feb 8, 2022, 10:45 AM
• Last activity: Mar 13, 2023, 10:42 AM
2
votes
2
answers
1473
views
Security Considerations/Risks/Best Practices for Enabling CLR Integration (Assemblies) for SSIS Catalog
The major pre-requisite in utilizing SSIS Catalog is enabling CLR Integration. The instance in question is running SQL Server 2014. I'm looking for feedback and resources I can mine which specifically covers best practices and security considerations for enabling CLR Integration on SQL Server 2014....
The major pre-requisite in utilizing SSIS Catalog is enabling CLR Integration. The instance in question is running SQL Server 2014. I'm looking for feedback and resources I can mine which specifically covers best practices and security considerations for enabling CLR Integration on SQL Server 2014.
As I understand it, there are some peculiar differences with CLR Integration and the nature of safe vs unsafe assemblies between older version of SQL Server up to the latest and greatest versions. For example, SQL Server 2017+ has a feature called CLR Strict Security, which my 2014 instance does not. What is the default permission set to for assemblies on SQL Server 2014?
The primary goal is to employ SSIS Catalog and be sure to follow proper procedure to reduce security risk. Are assemblies solely for the deployment of projects to SSIS Catalog marked as safe? Are there any assemblies for SSIS Catalog I have to keep an eye on which will be unsigned and, thus, not necessarily trusted?
Secondarily, I may want to push data via API calls from SSIS packages and that, too, would require CLR Integration and doing so gives me pause on how and where assemblies are set to safe/unsafe, trustworthy vs asymmetric key. It sounds like calling an API from a SSIS package would be considered unmanaged code and, thus, would have to be marked with unsafe or external_access and need a cert/key.
But the main thing is, before I make use of SSIS Catalog on a SQL Server 2014 instance, I just want to understand and be aware of any security pitfalls before I embark on it and enable CLR Integration.
user3621633
(275 rep)
Feb 23, 2023, 05:44 PM
• Last activity: Feb 23, 2023, 08:23 PM
0
votes
1
answers
679
views
Do Azure SQL and SQL Server still call-out into the CLR for FORMAT and PARSE? If so, which CLR version and how does marshalling affect performance?
The documentation for SQL Server's T-SQL `FORMAT` function implies calls are forwarded to .NET's `ToString` methods on .NET types corresponding to T-SQL types, and `TRY_PARSE` and `PARSE`'s documentation is quite explicit about it using the CLR: > https://learn.microsoft.com/en-us/sql/t-sql/function...
The documentation for SQL Server's T-SQL
FORMAT
function implies calls are forwarded to .NET's ToString
methods on .NET types corresponding to T-SQL types, and TRY_PARSE
and PARSE
's documentation is quite explicit about it using the CLR:
> https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql
> ## FORMAT( value, format, culture )
> **format
**: The format
argument must contain a valid .NET Framework format string, either as a standard format string (for example, "C"
or "D"
), or as a pattern of custom characters for dates and numeric values (for example, "MMMM DD, yyyy (dddd)"
). Composite formatting is not supported.
>
> **culture
**: culture
accepts any culture supported by the .NET Framework as an argument; it is not limited to the languages explicitly supported by SQL Server. If the culture argument is not valid, FORMAT
raises an error.
and:
> https://learn.microsoft.com/en-us/sql/t-sql/functions/parse-transact-sql?view=sql-server-ver16
> ## PARSE( string_value AS data_type [ USING culture ] )
> ### Remarks
> * Keep in mind that there is a certain performance overhead in parsing the string value.
> * PARSE
relies on the presence of the .NET Framework Common Language Runtime (CLR).
> * This function will not be remoted since it depends on the presence of the CLR. Remoting a function that requires the CLR would cause an error on the remote server.
So using FORMAT( intValue, 'N2', 'en-US' )
and PARSE( '2023-02-21' AS date )
in a T-SQL SELECT
projection will cause SQL Server to somehow invoke .NET's Int32.ToString( "N2", CultureInfo.GetCultureInfo( "en-US" ) )
and DateTime.Parse( "2023-02-21" )
methods at runtime.
...which strikes me as introducing considerable overhead, as SQL Server would need to use .NET's runtime type/value marshalling to convert from SQL Server's own internal representation of varchar(n)
and nvarchar
values to .NET's UTF-16-based strings, invoking those .NET methods (which, in many cases, are forwarded-out to non-CIL native code within the CLR... thus making the CLR part pointless, no?)
But more profoundly, Azure SQL notably disabled SQL-CLR shortly after launch for security reasons and there's no indication Microsoft will bring the feature back, except [in their _Managed Instance_ service](https://learn.microsoft.com/en-us/shows/data-exposed/its-just-sql-clr-in-azure-sql-database-managed-instance) , so if Azure SQL has the SQL-CLR disabled, how is it that our T-SQL scripts have no problem with using .NET-based FORMAT
/PARSE
functions?
-----
Based on this, I have some questions, which all basically boil-down to _"What's going on, eh?"_:
* Computers can have multiple versions of .NET installed side-by-side, so exactly what version of the CLR and BCL are being used when you use FORMAT
/PARSE
/TRY_PARSE
?
* e.g. .NET Framework 4.8 x64 vs. .NET Core 2.1 vs. .NET 5 vs. .NET 7+
* [The official documentation for SQL-CLR doesn't seem to have been updated](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sql-server-common-language-runtime-integration) since .NET 5+ effectively replaced Framework 4.x, so my reading implies it always uses .NET Framework 4.x...
* How does it work on SQL Server-for-Linux where only _post-.NET Core 3.1_ versions of .NET are available?
* The ("_classic_") .NET Framework 4.x is very Windows-specific, and I know SQL Server-for-Linux is essentially its own operating-system, but that seems like a lot of engineering-effort to keep using .NET Framework 4.x in this situation. It boggles the mind.
* Whereas if SQL Server is using .NET Core, or .NET 5+ instead of the .NET Framework 4.8 runtime, then how can we use .NET 5+ in our own SQL-CLR projects?
* How does this impact parallelisation of queries and query-plan generation?
* The article about SQL-CLR performance does not make any mention of scalar parallelisation nor UDF inlining at all, beyond saying that T-SQL built-ins are generally better than SQL-CLR, but that SQL-CLR is still far better than old-world CURSOR
-based approaches.
* ...but I assume that using a scalar SQL-CLR function in a query breaks parallelisation (as .NET doesn't expose a way to explicitly mark a method as being reentrant or thread-safe, so SQL Server would have no way of knowing that, so it would _have to_ disable parallelisation) - which kills performance, on top of the type-marshalling overhead - it's very odd that this factor isn't mentioned in the documentation.
* And if Azure SQL has SQL-CLR disabled, then how do FORMAT
and PARSE
work? Does Azure SQL have a _native_ built-in reimplementation of these functions that avoid the CLR entirely, or does it _actually_ have SQL-CLR enabled but only allows a small set of _blessed_ .NET BCL functions to be called? If so, then why _only_ those functions when there exist _many_ other useful functions we'd also like to call from T-SQL (composite string-formatting, Calendar
, Regex
, etc) - the whole thing seems _very arbitrarily limited_.
* And if Azure SQL _does_ have SQL-CLR running internally but only for first-party code, why does [the clr enabled
option](https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/clr-enabled-server-configuration-option) return 0
(and many other CLR-related properties/functions seem broken) unless Azure SQL's T-SQL sandboxing is doing some convoluted hiding-of-functionality?
-----
## Update
(I hate it when my initial research doesn't find anything helpful, then I post to SO/SE, and then _right afterwards_ I search Google again with slightly different keywords and find out what I wanted to know... so here's some information I just found, but I don't want to post it as an answer just yet, maybe in a couple of weeks if no-one else can post a succint, accurate, recent and relevant answer)
* According to https://github.com/MicrosoftDocs/sql-docs/issues/1594 and my own quick research:
* See also: https://stackoverflow.com/a/41114654/159145
* As of Q1 2023, all versions of SQL Server, up-to-and-including SQL Server 2022, including SQL Server for Linux, use _some version_ of the .NET Framework 4.x.
* On Windows Server, it uses whatever the latest version of the OS-provided .NET Framework 4.x is, which should be .NET 4.8.1.
* On Linux, it uses a private build of .NET Framework 4.x that runs within SQL Server's Windows-abstraction layer "SQLPAL" which is also involved with sandboxing SQL-CLR user-code.
* On Linux, the EXTERNAL_ACCESS
option (which would allow SQL-CLR code to break-out of the sandbox) is not supported, ditto on _Azure SQL Server Managed Instance_.
* However I haven't been able to find out how/why PARSE
/FORMAT
/etc works in Azure SQL despite all the indications that SQL-CLR is entirely disabled - or the performance/overhead/query-plan implications of the native-to-managed-and-back process involved in invoking .NET code from T-SQL.
Dai
(632 rep)
Feb 21, 2023, 07:18 PM
• Last activity: Feb 21, 2023, 11:43 PM
7
votes
1
answers
2153
views
Does lightweight pooling disable built-in CLR facilities?
Running SQL Server in fibre mode ([lightweight pooling][1]) disables the use of SQL CLR: > Common language runtime (CLR) execution is not supported under lightweight pooling. Disable one of two options: "clr enabled" or "lightweight pooling". Features that rely upon CLR and that do not work properly...
Running SQL Server in fibre mode (lightweight pooling ) disables the use of SQL CLR:
> Common language runtime (CLR) execution is not supported under lightweight pooling. Disable one of two options: "clr enabled" or "lightweight pooling". Features that rely upon CLR and that do not work properly in fiber mode include the hierarchy data type, replication, and Policy-Based Management.
On the other hand, disabling SQL CLR alone (without enabling lightweight pooling) does **not** disable the built-in CLR types like
geometry
, and geography
(though hierarchyid
is mentioned above), as shown in https://dba.stackexchange.com/q/77608
Now some new language features rely on the CLR, for example the FORMAT
function :
> FORMAT relies on the presence of the .NET Framework Common Language Runtime (CLR).
Does running SQL Server in fibre mode disable the FORMAT
function and/or using the CLR types?
Paul White
(95095 rep)
Jul 13, 2018, 05:02 PM
• Last activity: Dec 21, 2022, 09:31 AM
5
votes
1
answers
15648
views
How to register CLR assembly as trusted in SSDT deployment
I have CLR assembly in SSDT and to deploy that it has to be trusted. What I understand there are 4 options how to do that ### First option, use TRUSTWORTHY ```sql EXEC sp_configure 'clr enabled', 1; RECONFIGURE; ALTER DATABASE SourceDatabase SET TRUSTWORTHY ON; ``` ### Second option, disable strict...
I have CLR assembly in SSDT and to deploy that it has to be trusted. What I understand there are 4 options how to do that
### First option, use TRUSTWORTHY
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
ALTER DATABASE SourceDatabase SET TRUSTWORTHY ON;
### Second option, disable strict security
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'clr strict security', 0;
RECONFIGURE;
### Third option, sign assembly with key or certificate
Seems complicated and I was not able to manage that yet. I will appreciate the instructions, because the workflow is not clear here.
### Fourth option, use sp_add_trusted_assembly
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
declare @assembly varbinary(max) = 0x4D5A90000300000004000000FFFF0000... -- I have to manually copy that from the failed SQL publish file.
declare @hash varbinary(64) = HASHBYTES('SHA2_512', @assembly);
EXEC sys.sp_add_trusted_assembly @hash, N'Foo Assembly';
In the 4th option I have to manually register the assembly as trusted and only after that I can publish the assembly. It's possible to somehow automate this process?
I am thinking about creating pre-deployment script
that can run the 4th option code but I don't know how to populate the @assembly variable from the file of the assembly .dll
.
Alternatively, if it's possible to deploy assembly as untrusted I can make it trusted on the server with the following code (post-deployment script
)
-- Register all database assemblies as trusted
declare @name nvarchar(4000),
@content varbinary(max);
DECLARE appCursor CURSOR FAST_FORWARD FOR
SELECT [name], content
FROM SourceDatabase.sys.assembly_files
OPEN appCursor
FETCH NEXT FROM appCursor INTO @name, @content
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @hash varbinary(64) = HASHBYTES('SHA2_512', @content);
EXEC sys.sp_add_trusted_assembly @hash, @name;
FETCH NEXT FROM appCursor INTO @name, @content
END
CLOSE appCursor
DEALLOCATE appCursor
GO
Any idea or what's your approach?
Muflix
(1099 rep)
Oct 16, 2022, 04:31 PM
• Last activity: Oct 16, 2022, 05:41 PM
8
votes
2
answers
36310
views
How to grant a user UNSAFE ASSEMBLY permission
How can we assign **a user** , e.g.: the database owner (DBO) the UNSAFE ASSEMBLY permission? I'm asking it to enable a user to create an assembly and don't know the SA password, so `EXEC sp_changedbowner ‘sa’` can't help. Any idea? Thank you.
How can we assign **a user** , e.g.: the database owner (DBO) the UNSAFE ASSEMBLY permission?
I'm asking it to enable a user to create an assembly and don't know the SA password, so
EXEC sp_changedbowner ‘sa’
can't help.
Any idea?
Thank you.
Sky
(3744 rep)
Nov 2, 2012, 02:14 AM
• Last activity: Sep 21, 2022, 06:41 PM
3
votes
2
answers
1095
views
SQLCLR TVF that calls web service is getting error 401: Unauthorized
I am calling a web service from a SQLCLR TVF in SQL Server 2008 R2. On the IIS server this service has open permissions. When tested using GET or POST requests on a browser the web service works as expected. However, when the function calls the service, it returns: > The request failed with HTTP sta...
I am calling a web service from a SQLCLR TVF in SQL Server 2008 R2.
On the IIS server this service has open permissions. When tested using GET or POST requests on a browser the web service works as expected. However, when the function calls the service, it returns:
> The request failed with HTTP status 401: Unauthorized.
In the typical anecdotal way, when I run the TVF on my machine to access the service on my machine, it works. (proof that code is correct)
This error occurs when using a SQL Server on the network accessing another ISS server on the network. Both servers are in the same domain.
How to determine the missing permissions that prevent this TVF from working?
MauMen
(151 rep)
Jun 23, 2011, 03:03 PM
• Last activity: Jul 21, 2022, 02:00 PM
11
votes
2
answers
9044
views
Security or performance risks using SQL CLR
Are there any particular security or performance risks in using the CLR in SQL Server ?
Are there any particular security or performance risks in using the CLR in SQL Server ?
SQLBen
(355 rep)
Dec 9, 2014, 01:01 PM
• Last activity: Nov 24, 2021, 03:55 AM
1
votes
1
answers
7423
views
Sql Server 2019, migrating clr assemblies, clr strict security
We have some old code running in Sql Server 2008 servers, and we're looking to upgrade to Sql Server 2019. The old clr code is *really* old (like .net framework 2.0 old), so I knew I'd have to rebuild the assemblies for the new server. We did a backup/restore from the old systems to the new system,...
We have some old code running in Sql Server 2008 servers, and we're looking to upgrade to Sql Server 2019. The old clr code is *really* old (like .net framework 2.0 old), so I knew I'd have to rebuild the assemblies for the new server. We did a backup/restore from the old systems to the new system, and while all the assemblies were there, they throw errors on execution.
I ran into the "CLR strict security" posts and the "CREATE or ALTER ASSEMBLY for assembly XXX with the SAFE or EXTERNAL_ACCESS option failed because the 'clr strict security' option of sp_configure is set to 1. Microsoft recommends that you sign the assembly with a certificate..." message.
I started on the first assembly in the first db. I changed the framework to 4.6.1 and signed it. I first tried ALTER ASSEMBLY and it said it couldn't ALTER because of the signature difference. So I dropped all the references to that assembly, then dropped the assembly, and did a CREATE ASSEMBLY with the new code. And it worked. Maybe it shouldn't have but it did.
So I started slogging through the next assembly in the next database. Did the same process (update framework, sign it, rebuild, drop all references, drop assembly, create assembly). Only next time I get the "CREATE or ALTER ASSEMBLY for assembly XXX with the SAFE or EXTERNAL_ACCESS option failed because the 'clr strict security' option of sp_configure is set to 1. Microsoft recommends that you sign the assembly with a certificate..." message.
I ran
sp_configure
SELECT * FROM sys.trusted_assemblies
SELECT * FROM sys.assemblies
in both databases. Both show "clr strict security" run_value as 1, both show no entries in trusted_assemblies.
I'm realizing my "just sign the assembly" understanding wasn't sufficient but I'm puzzled why the methodology worked on the first db and failed in the second db.
I generated the snk files fresh for each assembly and I haven't associated any logins with them.
How did "just sign the assembly" manage to work in the first try and not in the second?
In the first database, under the output of sys.assemblies, I see the public key token of the new build on the assembly and I see SAFE_ACCESS in the permission_set_desc and the new install dates, but I can't figure out why that sufficed in the first db and not in the second.
Thanks
user1664043
(379 rep)
Oct 28, 2021, 08:22 PM
• Last activity: Oct 28, 2021, 08:54 PM
5
votes
1
answers
1615
views
Load assembly from a certificate in SQL Server
We received an assembly from external vendor as ``` CREATE ASSEMBLY MYCALC_DLL AUTHORIZATION dbo FROM 0x42A728.... WITH PERMISSION_SET = UNSAFE GO ``` And this DLL is been called from an SP. We would not like to set TRUSTWORTHY ON for the database to load this assembly into SQL Server DB and was exp...
We received an assembly from external vendor as
----- It worked this way. Is this correct method?------
1. Downloaded Visual Studio Community Edition 2019
2. From the above set of files, opened the project file
3. Build CALCproject
4. It created a .dll file
5. In the properties of the project, signing tab
created a new strong name key file
**Did not select the checkbox "Protect my key file with a password"
ANd chosen sha256RSA as the Signature Algorithm
Save the Project and Build, it creates a .snk file
5. Copy the DLL and snk file to the SQL Server box
6. Run the below script
CREATE ASSEMBLY MYCALC_DLL
AUTHORIZATION dbo
FROM 0x42A728....
WITH PERMISSION_SET = UNSAFE
GO
And this DLL is been called from an SP.
We would not like to set TRUSTWORTHY ON for the database to load this assembly into SQL Server DB and was exploring options. Came across these links
https://nielsberglund.com/2017/07/01/sqlclr-and-certificates/
https://sqlquantumleap.com/2017/08/09/sqlclr-vs-sql-server-2017-part-2-clr-strict-security-solution-1/
https://sqlquantumleap.com/2017/08/16/sqlclr-vs-sql-server-2017-part-3-clr-strict-security-solution-2/
However these links use tools like MAKECERT (replaced by new-selfsignedcertificate), pvk2pfx.exe and signtool.exe are not existing on our win2016 servers.
Also would the DLL be called with this approach
Enable TRUSTWORTHY in the DB ->
Install the assembly in the DB AS WITH PERMISSION_SET = UNSAFE->
Disable TRUSTWORTHY in the DB
I suppose that's a stupid question, however i'm loading assembly as UNSAFE, then what's the point to disable TRUSTWORTHY? Correct me...
We would like to use certificates. How to proceed further? And these DB's will be soon configured for AlwaysOn, would there be any complications? Thanks
Now the developer gave these files


USE [Master]
GO
CREATE ASYMMETRIC KEY CLR_SP_Key
FROM EXECUTABLE FILE = 'H:\CLR_SP\CALC.dll'
GO
CREATE LOGIN CLR_SP_Login FROM ASYMMETRIC KEY CLR_SP_Key
GO
GRANT UNSAFE ASSEMBLY TO CLR_SP_Login
GO
USE [target_database]
GO
CREATE USER CLR_SP_Login FOR LOGIN CLR_SP_Login
GO
CREATE ASSEMBLY DBCALC_DLL FROM 'H:\CLR_SP\CALC.dll'
WITH PERMISSION_SET=UNSAFE
GO
CREATE function dbo.Proc_CLR_SP
(
@name as nvarchar(200) ,
@name2 as nvarchar(200)
)
RETURNS nvarchar(200)
AS EXTERNAL NAME DBCALC_DLL
Kris
(452 rep)
Oct 4, 2021, 05:41 PM
• Last activity: Oct 5, 2021, 06:58 PM
8
votes
3
answers
16496
views
Access to the path 'c:\some\path' is denied for MSSQL CLR
I think this is a permissions problem, but I'm having trouble locating it. I have a group of CLRs on one server (SQL Server 2016) and they work as they should. All are marked UNSAFE and they do various types of file I/O (read, write, copy, move, rename, etc.). I can run them via SSMS or from a job w...
I think this is a permissions problem, but I'm having trouble locating it.
I have a group of CLRs on one server (SQL Server 2016) and they work as they should. All are marked UNSAFE and they do various types of file I/O (read, write, copy, move, rename, etc.). I can run them via SSMS or from a job with equal ease.
I need to install them on another server (also SQL Server 2016). Using the original Visual Studio Project I have deployed them to the new sever. They show up in SSMS. That part looks fine.
When I, from SSMS, try to run one I get the following error: "Access to the path 'whatever path I passed in' is denied."
I'm logged into SSMS under my windows login. I have permissions to the database, I'm dbo. I'm an admin on the server. I have permissions in the file system.
What else could I be missing?
WillG
(327 rep)
May 23, 2019, 08:49 PM
• Last activity: Sep 7, 2021, 09:30 AM
1
votes
0
answers
144
views
Service Broker's SEND statement causes security context switch
We have triggers in multiple tables that will send messages to a Service Broker service upon INSERT, UPDATE and DELETE operations. These operations may be nested as parts of bigger, transactional operations in various different processes, with additional operations coming up after sending the messag...
We have triggers in multiple tables that will send messages to a Service Broker service upon INSERT, UPDATE and DELETE operations. These operations may be nested as parts of bigger, transactional operations in various different processes, with additional operations coming up after sending the messages but before transactions actually gets committed.
Our users authenticate using SSPI (Windows Active Directory). Some legacy stored procedure have been setup with
From this point on, it's as if the
WITH EXECUTE AS OWNER
clause so we don't have to worry about possible permission issues for whatever these procedures will do - including writing in tables described above.
Yesterday, following up an update to one of our apps, it started logging a strange permission error on a very basic SELECT statement. I looked up the procedure (it happens to be a SQLCLR
procedure) and it should indeed be running as its owning schema (dbo
in this case, which happens to be mapped to sa
user) and therefore have every possibly required permissions.
I ran a Sql Profiler
session while trying to reproduce the issue and noticed something strange: the SEND
command caused LoginName
to switch back to the domain user.

EXECUTE AS OWNER
condition in the head procedure was being reverted.
Just to make sure, I disabled Service Broker
on the database and did the exact same action. Sure enough, there was no more security context switch.
What could possibly be the cause for this? Is this by design? Is it smh because it's invoked from within SQLCLR?
As a reference, here is the declaring code for the head procedure:
CREATE PROCEDURE [dbo].[ps_SQLCLR_RunTicket]
@ticket [nvarchar](128)
WITH EXECUTE AS OWNER
AS
EXTERNAL NAME [SomeAssembly].[SomeStaticClass].[SomeMethod]
GO
And here is a slimmed down version of the nested code that's calling out SEND
:
-- This code normally is in a stored procedure that's invoked from a trigger
DECLARE @msg VARCHAR(MAX) = ''
SET @handle = NEWID();
BEGIN DIALOG CONVERSATION @handle
FROM SERVICE auditService
TO SERVICE 'receivingService'
ON CONTRACT auditServiceContract
WITH ENCRYPTION = OFF, LIFETIME = 600;
SEND ON CONVERSATION @handle
MESSAGE TYPE auditMessageType (@msg);
END CONVERSATION @handle;
Crono
(111 rep)
Aug 12, 2021, 08:44 PM
9
votes
3
answers
451
views
Is the hierarchyid CLR open-source?
The built-in *hierarchyid* is a CLR that stores paths in an efficient binary form, and provides other useful functionality. Unfortunately, there is limit to how deep the represented paths can be, and it's ~1427 for a binary tree. I would like to increase that limit for a complex existing application...
The built-in *hierarchyid* is a CLR that stores paths in an efficient binary form, and provides other useful functionality.
Unfortunately, there is limit to how deep the represented paths can be, and it's ~1427 for a binary tree. I would like to increase that limit for a complex existing application that is bound to hit this limit. I don't wish to change the interface of the type. I am not confident that I could pull off changing the interface of the type without introducing subtle bugs into all the code that would have to be changed as a result.
I could (in theory) create a "binhierarchyid" CLR UDT that implements the same interface as hierarchyid, but only supports binary trees. That should get me a depth of ~7000 while still remaining inside the 900 byte limit. Not sure how big of an undertaking that would be.
Is the source of this hierarchyid CLR available somewhere, so that I could create my own based on it that supports deeper structures?
Tarnay Kálmán
(193 rep)
Apr 22, 2016, 06:35 PM
• Last activity: May 13, 2021, 11:22 AM
0
votes
1
answers
73
views
I am wanting to use UDTT in my database, but we have CLR turned off, and according to the docs for create type, all types require a CLR assembly
Is this true? Or can I use User defined Table Types with having CLR off? (I.e. they don't require the use of CLR) If they do require CLR, is there an alternative I can use for my stored procedure parameter that serves the same functionality?
Is this true? Or can I use User defined Table Types with having CLR off? (I.e. they don't require the use of CLR)
If they do require CLR, is there an alternative I can use for my stored procedure parameter that serves the same functionality?
Jack.Frost
(3 rep)
Apr 12, 2021, 09:37 PM
• Last activity: Apr 12, 2021, 11:52 PM
3
votes
2
answers
701
views
Is using CLR for regular expressions safer than using external scripts?
# Problem The main problem we need to use regular expression on MS SQL Server 2019, with the capability of at least the level on the POSIX Regular expression. # Possible solutions This [Q/A][1] from stackoverflow rightly concludes that if you query must rely on regular expressions you shuould use CL...
# Problem
The main problem we need to use regular expression on MS SQL Server 2019, with the capability
of at least the level on the POSIX Regular expression.
# Possible solutions
This Q/A from stackoverflow rightly concludes that if you query must rely on regular expressions you shuould use CLR. This Readgate article elaborates this approach more. So one of my colleagues and I proposed this solution, but my other colleague categorically stated that using CLR here would be a huge risk to security and stability, and using external script (Python or R) is more secure.
This seems to be dubious claim, since the user code in the [CLR can be managed](https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration/assemblies/managing-clr-integration-assemblies?view=sql-server-ver15) , so perhaps the opposite is true, but I was not able to persuade my colleague.
In my other [question](https://dba.stackexchange.com/questions/283102/parallel-execution-of-a-sql-server-external-script) which I wrote in my desperation because I was forced to use external script and still produce a blazing fast query. SQLpro user states in his comment that:
> Using Python or R can be worst in terms of security rather than using CLR!
Which I tend to believe.
# Questions
So I have two questions:
1. Which Regexp solution is more secure external script or CLR based (as described here )? And why?
2. I also proposed to run the python code on the same Windows Server (must be the same server, because of a policy) but with python intrepeter installed on the OS. Because the results are exported into CSV files either way and stored in the SQL Server. So then I would able to use Python's multiprocessing module to achieve the right performance. The answer was the same that running Python inside SQL Server is more secure than in a outside application. Which is also a questionable claim.
atevm
(337 rep)
Jan 14, 2021, 10:00 AM
• Last activity: Jan 15, 2021, 10:13 PM
Showing page 1 of 20 total questions