日期:2014-05-18  浏览次数:20662 次

高分求SQL中分解组合字串,在线等.急急.....
我想把IP地址分解成字符串,如果长度小于3位的前面补0,SQL语句怎么写?
例如:202.96.209.5
分解:202
          96
          209
          5
补零后还原且写到数据库:202.096.209.005

------解决方案--------------------
CREATE function uf_splitstring
(
@str varchar(8000) --要分拆的字符串
,@spli varchar(10) --字符串分隔符
)
returns @retab table(istr varchar(8000))
as
begin
declare @i int
declare @splen int
select @splen=len(@spli),@i=charindex(@spli,@str)
while @i > 0
begin
insert into @retab
values(left(@str,@i-1))
select @str=substring(@str,@i+@splen,8000)
select @i=charindex(@spli,@str)
end
if @str <> ' ' insert into @retab values(@str)
return
end

select right( '000 '+istr,3) from uf_splitstring( '202.96.209.5 ', '. ')
/*

------
202
096
209
005

(所影响的行数为 4 行)
*/
------解决方案--------------------
create table #tmp (id int identity(1,1),a varchar(10))
insert #tmp(a) select top 100 ' ' as y from sysobjects

declare @a table(a varchar(100),b varchar(100))
declare @b varchar(100)
set @b= ' '
insert @a select '202.96.209.5 ', ' '
select
id,right( '00 '+ substring(a.a,b.id,charindex( '. ',a.a+ '. ',b.id)-b.id),3) gg into #t
from #tmp b,@a a
where substring( '. '+a.a,b.id,1)= '. '
select @b=@b+gg+ '. ' from #t
update @a set b=left(@b,len(@b)-1)
select * from @a
drop table #tmp,#t
------解决方案--------------------
用表变量
declare @a table(id int,a varchar(3))
declare @str varchar(20),@i int
set @i=1
set @str= '202.96.209.5 '+ '. '
while @i <=4--charindex( '. ',@str)> 0
begin
insert @a select @i,left(@str,charindex( '. ',@str)-1)
set @str=right(@str,len(@str)-charindex( '. ',@str))
set @i=@i+1
end
select * from @a

select right( '00 '+a.a,3)+ '. '+right( '00 '+b.a,3)+ '. '+right( '00 '+c.a,3)+ '. '+right( '00 '+d.a,3) from @a a,@a b,@a c,@a d where a.id=1 and b.id=2 and c.id=3 and d.id=4

------解决方案--------------------
参照如下函数来改就行了
CREATE FUNCTION f_splitSTR(@s varchar(8000),@split varchar(10))RETURNS @re TABLE(col varchar(100))
AS
BEGIN
DECLARE @splitlen int
SET @splitlen=LEN(@split+ 'a ')-2
WHILE CHARINDEX(@split,@s)> 0
BEGIN
INSERT @re VALUES(LEFT(@s,CHARINDEX(@split,@s)-1))
SET @s=STUFF(@s,1,CHARINDEX(@split,@s)+@splitlen, ' ')
END
INSERT @re VALUES(@s)
RETURN
END
GO
------解决方案--------------------
Declare @s1 varchar(100),@s2 varchar(100),@i int
Select @s1= '202.96.209.5 ',@s2= ' '
Set @i=charindex( '. ',@s1)
while @i> =1
begin
set @s2=@s2 +right( '000 ' +left(@s1,@i-1),3) + '. '
set @s1=substring(@s1,@i+1,len(@s1)-@i)
set @i=charindex( '. ',@s1)
end
Select @s2+right( '000 ' + @s1,3)
------解决方案--------------------
alter function uf_splitstring