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

mssql中如何合并两个ntext字段?
目标:将db2的content1、content2两个字段合并到db1的content字段,条件是两个数据库的title相同  
出错:对数据类型而言运算符无效。运算符为   add,类型为   ntext。  

update   db1  
set   cb1.content=db2.content1+db2.content2  
from   cb1,cb2   where   db1.title=db2.title  


------解决方案--------------------
/*将表test_text1 的content列追加到 表test_text2的id相同的content列*/
if exists(select * from sysobjects o where o.xtype = 'u ' and o.name = 'test_text1 ')
drop table test_text1

if exists(select * from sysobjects o where o.xtype = 'u ' and o.name = 'test_text2 ')
drop table test_text2

create table test_text1(
id int,
content ntext)

create table test_text2(
id int,
content ntext)

insert test_text1
select 1, 'abc ' union all
select 2, 'def '

insert test_text2
select 1, 'ghi ' union all
select 2, 'jkl '


select * from test_text1
select * from test_text2

declare @ptr_src binary(16)
declare @ptr_des binary(16)

declare test_cur cursor for
select textptr(a.content),textptr(b.content)
from test_text1 a,test_text2 b
where a.id = b.id

open test_cur
fetch next from test_cur into @ptr_src,@ptr_des
while(@@fetch_status = 0)
begin
updatetext test_text2.content @ptr_des null 0 test_text1.content @ptr_src

select @ptr_src = null,@ptr_des = null

fetch next from test_cur into @ptr_src,@ptr_des
end

close test_cur
deallocate test_cur

select * from test_text1
select * from test_text2
===========================================
test_text1
1 abc
2 def
test_text2
1 ghi
2 jkl
后来的test_table2
1 ghiabc
2 jkldef