[MSSQL]向左填充指定字符串

本文介绍了两种在SQL中实现字符串向左填充的方法,通过创建自定义函数`padleft`和`padleftV2`,分别用循环和`replicate`函数达到在字符串左侧填充指定字符的效果。并给出了测试示例及运行结果。
 
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(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

厦门德仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值