• 前导或后导字符串


    根据需求,需要把某一些数字或字符串进行格式化,前导或后导字符串。Insus.NET把这个功能写成一个自定义函数。需要时,直接使用即可。

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    
    -- =============================================
    -- Author:      Insus.NET
    -- Create date: 2019-05-10
    -- Update date: 2019-05-10
    -- Description: 前导或后导字符
    -- =============================================
    CREATE FUNCTION [dbo].[svf_LeadingString]
        (
            @OriginalCharacter NVARCHAR(MAX),
            @ExpectedLength INT,
            @PadCharacterString NVARCHAR(MAX),
            @LeadingToRight BIT
        )
    RETURNS NVARCHAR(MAX)
    AS
    BEGIN
        DECLARE @rtv NVARCHAR(MAX) = @OriginalCharacter
    
        IF LEN(ISNULL(@OriginalCharacter,'')) < @ExpectedLength
        BEGIN
            DECLARE @ReplicateString NVARCHAR(MAX) = REPLICATE(@PadCharacterString, @ExpectedLength - LEN(@OriginalCharacter))
            
            IF @LeadingToRight = 1        
                SET @rtv = @OriginalCharacter + @ReplicateString        
            ELSE        
                SET @rtv = @ReplicateString + @OriginalCharacter
        END
                  
        RETURN @rtv
    END
    
    GO
    Source Code

    举例可以更好说明函数使用如何。

    --创建临时表,并随机添加一些数据
    DECLARE @dumpTable AS TABLE ([OriginalCharacter] NVARCHAR(MAX))
    INSERT INTO @dumpTable  ([OriginalCharacter])  VALUES (12)
    INSERT INTO @dumpTable  ([OriginalCharacter])  VALUES (3456)
    INSERT INTO @dumpTable  ([OriginalCharacter])  VALUES ('RT')
    INSERT INTO @dumpTable  ([OriginalCharacter])  VALUES ('GFR')
    INSERT INTO @dumpTable  ([OriginalCharacter])  VALUES ('345E')
    INSERT INTO @dumpTable  ([OriginalCharacter])  VALUES (43)
    INSERT INTO @dumpTable  ([OriginalCharacter])  VALUES (7777)
    INSERT INTO @dumpTable  ([OriginalCharacter])  VALUES (254687)
    INSERT INTO @dumpTable  ([OriginalCharacter])  VALUES ('adrf')
    
    
    --设置自定义函数的参数
    DECLARE @ExpectedLength INT = 8, @PadCharacterString NVARCHAR(MAX) = '0'
    
    
    SELECT [OriginalCharacter],
        [dbo].[svf_LeadingString]([OriginalCharacter],@ExpectedLength,@PadCharacterString,0) AS [LeadingToLeft],
        [dbo].[svf_LeadingString]([OriginalCharacter],@ExpectedLength,@PadCharacterString,1) AS [LeadingToRight] 
    FROM @dumpTable
    Source Code
  • 相关阅读:
    如何使用 Python 创建一名可操控的角色玩家
    Unity查找物体的四大主流方法及区别
    JavaFX桌面应用开发-鼠标事件和键盘事件
    profiler-gpu分析记录
    JavaFX桌面应用开发-Button(按钮)与事件
    CodeCombat代码全记录(Python学习利器)--Kithgard地牢代码1
    spine骨骼动画组件使用详解
    微信小程序animation
    LeetCode--不同路径
    Learning opencv续不足(七)线图像的设计D
  • 原文地址:https://www.cnblogs.com/insus/p/10842839.html
Copyright © 2020-2023  润新知