有个表A
有BC字段 如下:
B C
14254 adaskj
243255 jdkss
25145 dfdtv
把B列2出现的位置在C列里换成H
B C
14254 adHskj
243255 HdkHs
25145 Hfdtv
用SQL语句实现
创建一个函数:
create function getnewstr(@str1 varchar(10),@str2 varchar(10))
returns varchar(10)
as
begin
declare @i int
set @i = 1
while @i <= len(@str1)
if substring(@str1, @i, 1)='2'
set @str2 = replace(@str2, substring(@str2, @i, 1), 'H')
else
set @i = @i +1
return @str2
end
go
执行函数:select dbo.getnewstr(B,C)
create function f(@b varchar(10),@c varchar(10)) returns varchar(10)
as
begin
declare @i int
set @i=1
while charindex('2',@b,@i)>0
begin
set @i=charindex('2',@b,@i)
set @c=substring(@c,1,@i-1)+'H'+substring(@c,@i+1,len(@c)-@i)
set @i=@i+1
end
return @c
end
declare @t table(b varchar(10),c varchar(10))
insert @t
select '14254', 'adaskj'
union all
select '243255', 'jdkss'
union all
select '25145', 'dfdtv'
select dbo.f(b,c),c from @t
善用SQL提供的字符串函数
update t_test set C = SUBSTRING(C,0,charindex('2',B))+'H'+SUBSTRING(C,(charindex('2',B)+1),9999)
学习了。