从SQL Server varchar列中删除奇怪的字符(带帽子的A)

Ank*_*kit 3 c# t-sql sql-server

一些奇怪的字符存储在其中一个表中.它们似乎来自.csv饲料,因此我对此没有多少控制权.

Hello Kitty Essential Accessory Kit
Run Code Online (Sandbox Code Playgroud)

我该如何清理它并删除这些字符.我可以在db级别或C#中执行此操作.

编辑

根据评论中收到的建议.我也在研究如何在饲料水平上纠正它.这是关于它的更多信息.

  1. 饲料来自第三方.
  2. 我在记事本++中打开了feed并检查了编码菜单我在'encode in ansi'前面看到了点,所以我相信这是文件的编码
  3. 这就是它在记事本++"Hello Kitty Essential配件套件"中的显示方式
  4. 但有一件奇怪的事.当我从csv文件中搜索powershel中的那一行时.它提出了这一行.我没有看到这些奇怪的角色..

got*_*tqn 7

您可以使用.net正则表达式函数.例如,使用Regex.Replace:

Regex.Replace(s, @"[^\u0000-\u007F]", string.Empty);
Run Code Online (Sandbox Code Playgroud)

由于不需要支持正则表达式,因此SQL Server需要创建一个SQL CLR函数.有关.net集成的更多信息,请SQL Server访问:


在你的情况下:

  1. 打开Visual Studio并创建Class Library Project:

    在此输入图像描述

  2. 然后将类重命名为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)
  3. 现在,构建项目.打开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)
  4. 最后,创建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)