[MSSQL]T-SQL自定义函数LeftPad

T-SQL自定义函数LeftPad T-SQL自定义函数,它有点像MS SQL Server的REPLICATE函数。它有三个参数,第一个@String是原有字符串,第二@Char参数就将要加入至前置字符串,第三个@Leng参数为前置字符串重复次数。
udf_LeftPad 


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        Insus.NET
-- Create date:   2012-03-24
-- Description:   Character to prepend onto String
-- =============================================
CREATE FUNCTION [dbo].[udf_LeftPad] 
(
    @String NVARCHAR(MAX),--原字符串
    @Char NVARCHAR, --前置字符
    @Leng INT --前置字符串最终长度
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @s NVARCHAR(MAX) = N''
    IF LEN(ISNULL(@Char,N'')) <> 0        
    BEGIN        
        WHILE LEN(@s) < @Leng 
        BEGIN
            SET @s = @Char + @s
        END  
    END
   RETURN @s + @String
END

SELECT [dbo].[udf_LeftPad]('01','a',7) AS [NewString]

你可能感兴趣的:(sql,Date,server,String,function,character)