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

来源:互联网 发布:司法拍卖淘宝网怎么进 编辑:程序博客网 时间:2024/06/09 04:08

最近,在论坛中,遇到了不少比较难的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 tbcreate table tb(v nvarchar(100))insert into tbselect '(英)啊那编译' union allselect '小泉纯一郎(日)' union allselect '皇家马德里对(西)主编' union allselect '奥巴马(美)编著' union allselect '中国[等]'create table delete_author (del_author nvarchar(50))insert into delete_authorselect '主编' union allselect '编译' union allselect '(美)' union allselect '(英)' union allselect '(苏)' union allselect '[等]' union allselect '(日)' union allselect '编著' union allselect '(西)' if exists(select * from sys.objects where name = 'fn_replace_symbol')   drop function dbo.fn_replace_symbol;gocreate function dbo.fn_replace_symbol(@n nvarchar(1000))returns nvarchar(1000)asbegindeclare @i int;declare @count int;set @i = 1set @count = (select count(*) from delete_author);       while @i <= @countbegin   ;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 + 1endreturn @nendgo--替换效果select * ,       dbo.fn_replace_symbol(v) as 替换完后的字符from tb/*v                替换完后的字符(英)啊那编译         啊那小泉纯一郎(日)    小泉纯一郎皇家马德里对(西)主编皇家马德里对奥巴马(美)编著    奥巴马中国[等]            中国*/


0 0
原创粉丝点击