有两个表wan和wan1,表wan中有字段result(内容是一篇文章),表wan1中有字段A(里面是一些词如:“药”)、字段B(里面有很多词。比如:“yao”)和字段ID(数字)
比如我想替换表wan中的字段replace可以用下面的代码
UPDATE wan SET result=replace(result,'药','yao')
这个只能单个替换,怎么才能实现批量替换呢?也就是如果result内容中出现A的内容,就把result中的那个A的词语换成对应的B的词语?只替换result中的词语,不是全部内容都替换
小弟是新手 还请各位大哥大姐不吝赐教!谢谢了!

解决方案 »

  1.   

    update wan set result=(select replace(wan,字段A,字段B) from wan1)
      

  2.   

    update wan set result=(select replace(wan.result,字段A,字段B) from wan1)
      

  3.   


    declare @wan table (result varchar(30))
    insert into @wan
    select '这是一篇文章,内容省略一万个字'declare @wan1 table (id int,字段A varchar(2),字段B varchar(3))
    insert into @wan1
    select 1,'一','yi' union all
    select 2,'内','nei' union all
    select 3,'个','ge'declare @i int
    set @i=1
    while(@i<=(select count(*) from @wan1))
    begin
    update @wan
    set result=replace(result,a.字段A,a.字段B)
    from @wan1 a where id=@i
    set @i=@i+1
    endselect * from @wan
    /*
    result
    ------------------------------
    这是yi篇文章,nei容省略yi万ge字
    */
      

  4.   

    错啦create function f_name(@str varchar(100))
    returns varchar(100)
    as
    begin
         declare @str1 varchar(100)     
         set @str1=@str
         select @str1=replace(@str1,字段A,字段B) from wan1
         return @str1
    endupdate wan set result=dbo.f_name(result)
      

  5.   

    'SQL Server 2005'use test
    go
    if object_id('test.dbo.wan') is not null drop table wan
    -- 创建数据表
    create table wan
    (
    id int,
    txt varchar(1000)
    )
    go
    --插入测试数据
    insert into wan select 1,'中国软件社区中心'
    union all select 2,'论坛中心,软件,贴吧'
    union all select 3,'数据库管理系统'
    go
    if object_id('test.dbo.wan1') is not null drop table wan1
    -- 创建数据表
    create table wan1
    (
    id int,
    a varchar(100),
    b varchar(100)
    )
    go
    --插入测试数据
    insert into wan1 select 1,'软件','^_^'
    union all select 2,'中心','(*^__^*)'
    union all select 3,'管理','aaaaaaaaaa'
    go
    --代码实现with t as(
    select * from wan
    union all
    select t.id,txt=cast(replace(txt,a,b) as varchar(1000)) from t,wan1 where charindex(a,txt)>0
    )
    update wan set txt=t2.txt
    from wan t1,t t2
    where t1.id=t2.id and not exists (select 1 from wan1 where charindex(a,t2.txt)>0)select * from wan/*测试结果id txt
    --------------------------------
    1 中国^_^社区(*^__^*)
    2 论坛(*^__^*),^_^,贴吧
    3 数据库aaaaaaaaaa系统(3 行受影响)
    */