在论坛中出现的比较难的sql问题:41(循环替换 循环替换关键字)

最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。

所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。


为什么replace函数替换不了 ,请高手指点:http://bbs.csdn.net/topics/390625259

想把一个字符串中所有出现在delete_author表中的字符都删除掉(也就是替换成空)
delete_author表中的内容是:


我写成一个存储过程:(有些输出是为了测试)
create proc proc_del_special 
@input_str varchar(100),@output_str varchar(100) output
as
declare @author  varchar(256),@delsym varchar(10),@temp_str varchar(100)
declare del_cur scroll cursor for select del_author from delete_author
open del_cur
fetch next from del_cur into @delsym
set @author=@input_str
while @@fetch_status=0
     begin 
         print replace(@author,@delsym,'')
        set @temp_str=replace(@author,@delsym,'')
         set @author=@temp_str
         print @author
         print @delsym
         fetch next from del_cur into @delsym
     end 
set @output_str=@author
close del_cur
deallocate del_cur

测试例子:
declare @a1 varchar(100),@a2 varchar(100)
set @a1='(美)啊那编译'
exec proc_del_special @a1,@a2 output
select @a2
 
执行结果还是:(美)啊那编译 
执行过程中的消息:
美)啊那编译
(美)啊那编译
主编      
(美)啊那编译
(美)啊那编译
编译      
(美)啊那编译
(美)啊那编译
(美)      
(美)啊那编译
(美)啊那编译
(英)      
(美)啊那编译
(美)啊那编译
(苏)      
(美)啊那编译
(美)啊那编译
[等]      
(美)啊那编译
(美)啊那编译
(日)      
(美)啊那编译
(美)啊那编译
编著      
(美)啊那编译
(美)啊那编译
(西)      
(1 行受影响)
就是replace函数没有替换成功,这是为什么啊 ,请哪位大侠指点一下 ,在线等,非常感谢了
我的解法, 尽量少用游标,用函数也可以实现
--drop table tb

create table tb(v nvarchar(100))

insert into tb
select '(英)啊那编译' union all
select '小泉纯一郎(日)' union all
select '皇家马德里对(西)主编' union all
select '奥巴马(美)编著' union all
select '中国[等]'


create table delete_author (del_author nvarchar(50))

insert into delete_author
select '主编' union all
select '编译' union all
select '(美)' union all
select '(英)' union all
select '(苏)' union all
select '[等]' union all
select '(日)' union all
select '编著' union all
select '(西)' 



if exists(select * from sys.objects where name = 'fn_replace_symbol')
   drop function dbo.fn_replace_symbol;
go

create function dbo.fn_replace_symbol(@n nvarchar(1000))
returns nvarchar(1000)
as
begin
declare @i int;
declare @count int;

set @i = 1
set @count = (select count(*) from delete_author);
       
while @i <= @count
begin
   ;with t
   as
   (
   select del_author,
          row_number() over(order by @@servername) as rownum
   from delete_author
   )
    
   select @n = replace(@n,(select del_author from t where rownum = @i),'')
   set @i = @i + 1
end

return @n
end
go

--替换效果
select * ,
       dbo.fn_replace_symbol(v) as 替换完后的字符
from tb
/*
v	                替换完后的字符
(英)啊那编译	         啊那
小泉纯一郎(日)	    小泉纯一郎
皇家马德里对(西)主编	皇家马德里对
奥巴马(美)编著	    奥巴马
中国[等]	            中国
*/


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值