簡體   English   中英

如何在SQL中用單個空格替換多個空格和回車

[英]How to replace multiple white spaces and carriage return with a single white space in sql

我試圖用sql中的單個空格替換多個空格和回車符。 到目前為止,我已經提出了以下建議:

select  
replace(

replace(

replace(

replace(

replace(

replace(

LTrim(RTrim('      6      Spaces  6      Spaces.     
            abcde ')),char(13),''),--Trim the field
enter code here
                                                char(10),''),
char(13) + char(10),''),

 '  ',' |'),                                            
--Mark double spaces

  '| ',''),                                                 
--Delete double spaces offset by 1

'|','')  

現在,上述字符串的預期輸出為:6個空格6個空格。 ABCDE

但是我得到6個空格和6個空格。 [多個空格] abcde(Stackoverflow正在修剪此處的空格,因此,我必須寫它)我覺得這是一個難題。 怎么了?

好吧,我只是把它放在那兒作為替代,因為我剛剛完成了第二步,就接受了答案。

通過修剪和替換正確的順序,這還將為您提供所需的結果:

Select Replace(replace(replace(replace(
                                       RTRIM(LTRIM(this)), 
                                       char(13) + char(10), ''),
                                       '  ', ' |'),
                                       '| ', ''),
                                       '|','')
from
(select '      6      Spaces  6      Spaces.     
            abcde ' as this) a

這種類型的問題很難通過簡單的替換功能來解決,但是使用正則表達式功能則變得非常容易。

遺憾的是,Microsoft尚未將其作為SQL Server的內置函數提供,但是通過某些SQLCLR工作,它可以使用。

T-SQL中的SQL Server正則表達式有一個用於搜索字符串的SQLCLR函數的示例,但是在這里您將需要regex_replace函數

using System.Data.SqlTypes;

namespace Public.SQLServer.SQLCLR
{
    public class Regex
    {

        #region Regex_IsMatch Function
        /// <summary>
        ///     Searches an expression for another regular expression and returns a boolean value of true if found.
        /// </summary>
        /// <param name="expressionToFind">Is a character expression that contains the sequence to be found. This expression leverages regular expression pattern matching syntax. This expression may also be simple expression.</param>
        /// <param name="expressionToSearch">Is a character expression to be searched.</param>
        /// <param name="start_location">Is an integer expression at which the search starts. If start_location is not specified, is a negative number, or is 0, the search starts at the beginning of expressionToSearch.</param>
        /// <returns>Bit.</returns>
        [Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true, IsPrecise = true)]
        public static SqlBoolean Regex_IsMatch(SqlString expressionToFind, SqlString expressionToSearch, SqlInt32 start_location)
        {
            // Process expressionToFind parameter
            string etf;

            if (expressionToFind.IsNull)
            {
                return SqlBoolean.Null;
            }
            else if (expressionToFind.Value == string.Empty)
            {
                return new SqlBoolean(0);
            }
            else
            {
                etf = expressionToFind.Value;
            }

            // Process expressionToSearch parameter
            string ets;

            if (expressionToSearch.IsNull)
            {
                return SqlBoolean.Null;
            }
            else if (expressionToSearch.Value == string.Empty)
            {
                return new SqlBoolean(0);
            }
            else
            {
                ets = expressionToSearch.Value;
            }

            // Process start_location parameter
            int sl;

            if (start_location.IsNull)
            {
                sl = 0;
            }
            else if (start_location.Value < 1)
            {
                sl = 0;
            }
            else
            {
                sl = (int)start_location.Value -1;
                if (sl > expressionToSearch.Value.Length + 1)
                {
                    sl = expressionToSearch.Value.Length;
                }
            }


            // execute the regex search
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(etf);

            return regex.IsMatch(ets, sl);

        }
        #endregion

        #region Regex_Replace Function
        /// <summary>
        ///     Replaces all occurrences of a specified regular expression pattern with another regular expression substitution.
        /// </summary>
        /// <param name="expression">Is the string expression to be searched.</param>
        /// <param name="pattern">Is a character expression that contains the sequence to be replaced. This expression leverages regular expression pattern matching syntax. This expression may also be simple expression.</param>
        /// <param name="replacement">Is a character expression that contains the sequence to be inserted. This expression leverages regular expression substitution syntax. This expression may also be simple expression.</param>
        /// <returns>String of nvarchar(max), the length of which depends on the input.</returns>
        [Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true, IsPrecise = true)]
        public static SqlString Regex_Replace(SqlString expression, SqlString pattern, SqlString replacement)
        {

            // Process null inputs
            if (expression.IsNull)
            {
                return SqlString.Null;
            }
            else if (pattern.IsNull)
            {
                return SqlString.Null;
            }
            else if (replacement.IsNull)
            {
                return SqlString.Null;
            }

            // Process blank inputs
            else if (expression.Value == string.Empty)
            {
                return expression;
            }
            else if (pattern.Value == string.Empty)
            {
                return expression;
            }

            // Process replacement parameter

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern.Value);

            return regex.Replace(expression.Value, replacement.Value);

        }
        #endregion

    }
}

一旦可用,您可以通過如下查詢獲得結果:

select [library].[Regex_Replace]('String  with  many        odd spacing
    issues.

        !','\s{1,}',' ')

哪個返回

具有許多奇數間距問題的字符串。

表達式\\ s {1,}表示按一個或多個{1,}的順序匹配任何空格\\ s,並且匹配項將替換為您的單個空格字符。

使用SQLCLR的功能要比這里包含的代碼更多,並且需要進一步研究以創建程序集和SQLCLR函數。

您可以嘗試以下代碼:

select top 10 Note, LEN(Note) AS Before, LEN(replace(replace(replace(Note,' ','<>'),'><',''),'<>',' ') ) AS After,
 replace(replace(replace(Note,' ','<>'),'><',''),'<>',' ') as Note  from #ClientNote
 WHERE note LIKE '%  %'
 order by DATALENGTH(Note) desc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM