【叶子函数分享十九】向左填充指定字符串

本文介绍了两种用于SQL的自定义函数实现方式,一种是通过循环填充字符串至指定长度,另一种则是利用内置函数快速完成字符串左对齐填充。此外,还提供了具体的测试案例,展示如何使用这些函数对数据进行格式化。

go

--创建函数(该函数来自csdn,作者不详)

create function [dbo].[padleft]

(

@str varchar(50), --需要填充的字符串

@totalwidth int, --填充后的长度

@paddingchar char(1)--填充使用的字符

)

returns varchar(1000) as

begin

declare @s varchar(100)

set @s = @str

if ( len(@str) < @totalwidth)

begin

declare @i int

declare @strlen int

declare @temp varchar(100)

set @i = 1;

set @strlen = @totalwidth - len(@str)

set @temp = '';

while(@i <= @strlen )

begin

set @temp = @temp + @paddingchar;

set @i = @i + 1;

end

set @s = @temp + @str

end

return (@s)

end

go

--测试示例

declare @table table (id nvarchar(20))

insert into @table

select '1' union all

select '2' union all

select '3' union all

select '4' union all

select '5' union all

select '6'

select dbo.padleft(id,2,'0') as id from @table

--运行结果

/*

id

-------

01

02

03

04

05

06

*/

go

--创建函数(第二版)(作者:maco_wang)

create function padleftV2

(

@sql varchar(200), --需填充的字符串

@char varchar(4), --填充使用的字符

@len int --填充后的长度

)

returns varchar(200)

as

begin

return (right(replicate(@char,@len)+@sql,@len))

end

go

--测试示例

declare @table table(id int)

insert into @table(id)

select 1 union all

select 3 union all

select 6

select dbo.padleftV2(cast(id as varchar),'0',10) as id from @table

--运行结果

/*

id

-------------

0000000001

0000000003

0000000006

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值