字段按位数自动加空格

 SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
ALTER FUNCTION [dbo].[f_chgstr]
(
@str varchar(200), --传入的字符串,如'123456789'
@char varchar(10), --分割的字符,如' '
@len int --相隔的位数,如 4
)
RETURNS varchar(300) --格式'1234 5678 9'
AS
BEGIN

declare @a varchar(100)=@str,@temp varchar(100)='',@i int=1,@lenth int=0

if LEN(@a)<=@len return @a
if ISNULL(@char,'')='' set @char=' '
if @len<=0 return @a

set @lenth=LEN(@a)/@len

while(@i<=@lenth)
begin
set @temp = @temp + left(@a,@len)+@char

set @a=SUBSTRING(@a,@len+1,len(@a))

if(len(@a)<@len) 
begin 
set @temp=@temp+@a
set @i=@i+1
break
end


end
RETURN @temp

END 
posted @ 2014-10-30 15:37  那只爱哭的鱼  阅读(224)  评论(0编辑  收藏  举报