Ank*_*kit 3 c# t-sql sql-server
一些奇怪的字符存储在其中一个表中.它们似乎来自.csv饲料,因此我对此没有多少控制权.
Hello Kitty Essential Accessory Kit
Run Code Online (Sandbox Code Playgroud)
我该如何清理它并删除这些字符.我可以在db级别或C#中执行此操作.
编辑
根据评论中收到的建议.我也在研究如何在饲料水平上纠正它.这是关于它的更多信息.
您可以使用.net正则表达式函数.例如,使用Regex.Replace:
Regex.Replace(s, @"[^\u0000-\u007F]", string.Empty);
Run Code Online (Sandbox Code Playgroud)
由于不需要支持正则表达式,因此SQL Server需要创建一个SQL CLR函数.有关.net集成的更多信息,请SQL Server访问:
在你的情况下:
打开Visual Studio并创建Class Library Project:
然后将类重命名为StackOverflow并将以下代码粘贴到其文件中:
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public class StackOverflow
{
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, Name = "RegexReplace")]
public static SqlString Replace(SqlString sqlInput, SqlString sqlPattern, SqlString sqlReplacement)
{
string input = (sqlInput.IsNull) ? string.Empty : sqlInput.Value;
string pattern = (sqlPattern.IsNull) ? string.Empty : sqlPattern.Value;
string replacement = (sqlReplacement.IsNull) ? string.Empty : sqlReplacement.Value;
return new SqlString(Regex.Replace(input, pattern, replacement));
}
}
Run Code Online (Sandbox Code Playgroud)现在,构建项目.打开SQL Server Management Studio.选择您的数据库并替换以下FROM子句的路径值以匹配您的StackOverflow.dll:
CREATE ASSEMBLY [StackOverflow] FROM 'C:\Users\gotqn\Desktop\StackOverflow\StackOverflow\bin\Debug\StackOverflow.dll';
Run Code Online (Sandbox Code Playgroud)最后,创建SQL CLR函数:
CREATE FUNCTION [dbo].[StackOverflowRegexReplace] (@input NVARCHAR(MAX),@pattern NVARCHAR(MAX), @replacement NVARCHAR(MAX))
RETURNS NVARCHAR(4000)
AS EXTERNAL NAME [StackOverflow].[StackOverflow].[Replace]
GO
Run Code Online (Sandbox Code Playgroud)您已准备好在语句中RegexReplace .net直接使用函数T-SQL:
SELECT [dbo].[StackOverflowRegexReplace] ('Hello Kitty Essential Accessory Kit', '[^\u0000-\u007F]', '')
//Hello Kitty Essential Accessory Kit
Run Code Online (Sandbox Code Playgroud)