By Yunji
CLR (Common Language Runtime) integration of SQL Server allows developers to compile and execute database objects, such as stored procedures, triggers, and user-defined functions (UDFs), by using programming languages for the .NET Framework (such as C#). With CLR integration, SQL Server can use .NET to process more complex tasks, such as string and file management and regular expression parsing. This provides developers with more powerful tools. CLR integration is a flexible and efficient solution for processing compute-intensive tasks or tasks that cannot be processed using Transact-SQL (T-SQL).
This article describes how to deploy and use CLR integration in ApsaraDB RDS for SQL Server instance (hereinafter referred to as RDS instance) by using a demo.
To deploy CLR integration, you first need to configure the "clr enabled" instance-level parameter of your RDS instance to 1. The default value of this parameter is 0. Log in to the ApsaraDB RDS console, enter the Parameters page, and find the "clr enabled" parameter to enable CLR, as shown in Figure 1:
This section describes how to use a demo program to call a sentiment analysis function to deploy CLR integration to your RDS instance. The demo program sets up a simple dictionary and tokenization logic. When the comment content is provided, the program compares the content with the words in the dictionary to obtain a sentiment score.
Sample code of the demo program in C#:
public class SentimentAnalysis
{
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlDouble AnalyzeSentiment(SqlString text)
{
if (text.IsNull)
return SqlDouble.Null;
var sentimentDictionary = InitializeSentimentDictionary();
string input = text.Value.ToLower();
double sentimentScore = 0;
int wordCount = 0;
int i = 0;
while (i < input.Length)
{
bool matched = false;
// Match the longest word in the dictionary starting from the current position.
foreach (var entry in sentimentDictionary.Keys.OrderByDescending(k => k.Length))
{
if (i + entry.Length <= input.Length && input.Substring(i, entry.Length) == entry)
{
sentimentScore += sentimentDictionary[entry];
wordCount++;
i += entry.Length; // Skip the matched words.
matched = true;
break;
}
}
// If no word in the dictionary is matched, the character is skipped.
if (!matched)
{
i++;
}
}
return new SqlDouble(wordCount > 0 ? sentimentScore / wordCount : 0);
}
private static Dictionary<string, double> InitializeSentimentDictionary()
{
return new Dictionary<string, double>
{
{"good", 1.0}, {"like", 1.0}, {"excellent", 1.0}, {"great", 1.0}, {"satisfied", 0.8},
{"nice", 0.6}, {"okay", 0.2}, {"average", 0},
{"bad", -0.6}, {"terrible", -0.8}, {"disappointed", -0.8}, {"awful", -1.0}, {"hate", -1.0}
};
}
}
An RDS instance is a Platform as a Service (PaaS) application. Users cannot access the operating system (OS) of the server on which the RDS instance is deployed. In this case, you cannot complie C# code to create an assembly. We can first compile the C# CLR code into a DLL file and then use the RDS instance that is granted access permissions on the OS to create a CLR assembly, as shown in the following code.
-- Create a CLR assembly.
CREATE ASSEMBLY [CLRFuncDemo]
FROM 'E:\Backup\CLRFuncDemo.dll'
WITH PERMISSION_SET = SAFE
Next, export the assembly as a binary string through the export feature of the RDS instance, as shown in Figure 2.
The user who has the permissions of the database owner can connect to the RDS instance and create a function in binary mode based on the exported CLR assembly, as shown in Figure 3.
Figure 4 shows that the assembly is imported and a CLR function is created.
In this section, we will use a table to check the availability of a CLR function. The code is shown below.
CREATE TABLE UserReviews (
ReviewID INT IDENTITY(1,1) PRIMARY KEY,
Username NVARCHAR(50),
ProductName NVARCHAR(100),
ReviewContent NVARCHAR(MAX),
ReviewDate DATETIME
)
INSERT INTO UserReviews (Username,ProductName,ReviewContent,ReviewDate)
VALUES
('Chen Qi','Smartphone E',N'This phone is terrible, the battery life is awful, I am very disappointed!','2024-03-25 13:00:00'),
('Zhou Ba','Laptop F',N'The experience is very poor, the cooling is bad, the performance is terrible, not recommended!','2024-03-26 14:30:00'),
('Sun Jiu','Headphones G',N'The sound quality is terrible, these headphones are really awful, I am very disappointed!','2024-03-27 16:10:00'),
('Wu Shi','Tablet H',N'This tablet is okay, the performance is average, it is also acceptable to use.','2024-03-28 10:00:00'),
('Zhang Yi','Smartphone I',N'The phone is average, not particularly good, nor particularly bad, it is just so-so.','2024-03-29 11:20:00'),
('Li Si','Laptop B',N'This laptop is really excellent! The performance is great, I love it very much, extremely satisfied!','2024-03-20 09:15:00'),
('Wang Wu','Headphones C',N'The sound is very good, the material is excellent, the user experience is top-notch, I am very satisfied!','2024-03-22 11:00:00'),
('Zhao Liu','Tablet D',N'This tablet is really nice, the performance is strong, the battery life is also good, I love it very much!','2024-03-24 15:45:00'),
('Wang Kang','Smartphone K',N'The phone is very easy to use, the camera effect is excellent, I love it very much!','2024-03-31 12:05:00');
SELECT
ReviewID,
Username,
ProductName,
ReviewContent,
dbo.AnalyzeSentiment(ReviewContent) AS SentimentScore,
CASE
WHEN dbo.AnalyzeSentiment(ReviewContent) > 0.3 THEN 'Positive'
WHEN dbo.AnalyzeSentiment(ReviewContent) < -0.3 THEN 'Negative'
ELSE 'Neutral'
END AS SentimentCategory
FROM UserReviews
ORDER BY SentimentScore DESC
Figure 5 shows that the function meets expectations. Users can extract the keyword in comments to determine whether the tested service can meet user requirements.
If you encounter the following error while creating or modifying the "CLRFuncDemo" CLR assembly on your RDS instance:
Message 10343, Level 14, State 1, Line 12
The CREATE or ALTER ASSEMBLY for the "CLRFuncDemo" assembly 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 or asymmetric key with the UNSAFE ASSEMBLY permission for the corresponding login. Alternatively, you can trust the assembly using sp_add_trusted_assembly.
Starting from SQL Server 2017, Microsoft introduced the clr strict security option and set its default value to 1 to enhance the security of CLR integration. This ensures that only signed assemblies can be loaded with a security level of SAFE or EXTERNAL_ACCESS.
You can use one of the following methods to resolve the error:
A signature helps SQL Server verify the publisher's identity and grant permissions based on the principle of least privilege (PoLP) to ensure CLR security.
The method is relatively complex. For more information, please refer to link.
sp_add_trusted_assembly can be used to independently add an assembly to the list of trusted assemblies without modifying the assembly for signing.
However, this method is also complex and requires the system administrator permissions. If you want to choose one from Method 1 and Method 2, we recommend that you use Method 1.
As a PaaS service, SQL Server is not authorized to access instances. Therefore, you cannot directly disable the "clr strict security" option by using the default method. An alternative solution is to disable this option by using the system administrator account provided by your RDS instance.
Warning: Disabling clr strict security causes all CLR assemblies to run with higher permissions, which may pose security risks.
We can create a "super privileged account" through the console. The permissions for this account are equivalent to the sysadmin group permissions built into the SQL Server. It is worth noting that, as the memorable quote goes, "The greater the capability, the greater the responsibility". After having SA permissions, your RDS instance no longer guarantees the SLA. At the same time, this operation is of no return and cannot be disabled after it is enabled.
Execute the following statements to disable the clr strict security option as the system admin account:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'clr strict security', 0;
RECONFIGURE;
When this option is disabled, you can create the CLR assembly.
CLR integration provides powerful extensions for SQL Server, allowing developers to use the various features of the .NET Framework and process complex database tasks. This article describes how to deploy and use CLR integration on your RDS instance and provides examples.
CLR integration enhances the use scenarios of SQL Server to allow you to process tasks that cannot be managed by T-SQL.
You can use CLR rather than implementing these functions in the application. From a performance perspective, direct database operations can reduce data transmission overheads and provide higher processing efficiency. From a security perspective, processing sensitive data within databases can effectively reduce risks. From a maintenance perspective, centralized storage of business logic facilitates unified management and version control while supporting multiple application systems to share the same business rules.
In actual scenarios, T-SQL and the application layer are used to implement features. T-SQL is suitable for data queries, processing, and underlying business logic, while the application layer is good at handling complex interactions and workflows. CLR is a supplementary option for T-SQL and the application layer. If your workloads involve operations such as complex string processing, high-performance computing, or external system integration, you can use CLR as a complementary solution. This applies if T-SQL fails to be implemented and limits are imposed on the application layer's performance, deployment, and security.
PolarDB for MySQL Cold Data Archiving Supports DDL Changes Within Seconds
Alibaba Clouder - February 26, 2019
Alibaba Clouder - July 9, 2020
ApsaraDB - June 2, 2023
Alibaba Clouder - January 8, 2018
Alibaba Clouder - December 8, 2017
Alibaba Clouder - March 30, 2018
An on-demand database hosting service for SQL Server with automated monitoring, backup and disaster recovery capabilities
Learn MoreAn on-demand database hosting service for MySQL with automated monitoring, backup and disaster recovery capabilities
Learn MoreAn on-demand database hosting service for PostgreSQL with automated monitoring, backup and disaster recovery capabilities
Learn MoreApsaraDB RDS for MariaDB supports multiple storage engines, including MySQL InnoDB to meet different user requirements.
Learn MoreMore Posts by ApsaraDB