字符串中去除多余的空格保留一个(MS SQL Server)

大约2年前,写过一篇《字符串中去除多余的空格保留一个(C#)https://www.cnblogs.com/insus/p/7954151.html

今天,Insus.NET使用MS SQL Server来实现相同的功能。现Insus.NET已经把它写成一个自定义函数。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Insus.NET
-- Create date: 2019-05-13
-- Update date: 2019-05-13
-- Description: 保留一个空格
-- =============================================
CREATE FUNCTION [dbo].[svf_Leave_A_Space] 
( 
    @InputString NVARCHAR(MAX)
) 
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @Index INT = 1
    DECLARE @CurrentChar CHAR(1)
    DECLARE @PreviousChar CHAR(1)
    DECLARE @Str NVARCHAR(MAX) = N''

    WHILE @Index <= LEN(@InputString)
    BEGIN
        SET @CurrentChar = SUBSTRING(@InputString, @Index, 1)
        SET @PreviousChar = SUBSTRING(@InputString, @Index - 1, 1)

        IF @CurrentChar != ' ' OR @CurrentChar != @PreviousChar                
            SET @Str = @Str + CAST(@CurrentChar AS NVARCHAR(MAX))

        SET @Index = @Index + 1
    END
    RETURN @Str
END
GO
Source Code

 

使用一个例子来说明:

 

posted @ 2019-05-13 21:26  Insus.NET  阅读(1079)  评论(0编辑  收藏  举报