删除字符串前导的零字符

在这篇《前导或后导字符串https://www.cnblogs.com/insus/p/10842839.html

中。是为字符串使用前导来补充字符串,令其长度一致。

相反,如果我们把带有前导零的字符串,去除这些前导的零。我们又需要怎样处理呢?

 

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_TrimLeadingZero]
(
    @InputString NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN    
    DECLARE @position INT = 1, @len INT = LEN(@InputString)
    DECLARE @trimString NVARCHAR(MAX) = SUBSTRING(@InputString,@position, @len)
   
    WHILE @position <= @len
    BEGIN
        DECLARE @d NVARCHAR(2) = SUBSTRING(@InputString, @position, 1)
        IF LEN(ISNULL(@d,N'')) > 0 AND (@d LIKE '%[^0-9]%' OR @d > 0)
        BEGIN
            SET @trimString = SUBSTRING(@InputString,@position, @len)    
            BREAK;
        END
        SET @position = @position + 1
    END
    RETURN @trimString
END
GO
Source Code

 

列举几个实例:

 

posted @ 2019-05-13 00:14  Insus.NET  阅读(1049)  评论(0编辑  收藏  举报