在SQL Sever数据库表中,我有这个 这里Student属性的类型为XML
ClassName Student (XML)
A
B
C
以下是EACH行中的XML结构
<Students>
<Class>A</Class>
<Student>
<Name>John</Name>
<Hobbies>Music,Reading,Baseball</Hobbies>
</Student>
<Student>
<Name>David</Name>
<Hobbies></Hobbies>
</Student>
<Student>
<Name>Sofiya</Name>
<Hobbies>Surfing,Basketball</Hobbies>
</Student>
</Students>
在这里,我想通过用';'替换','来更新爱好节点。我想在每一行中做所有行和所有业余爱好。
我的查询应该是什么来实现这一目标? 我尝试了这个,但不是替换','而是用';'替换整个文本
declare @i int
select top 1 @i = count(*)
from @table as o
outer apply o.data.nodes('
Students/
Student[
Hobbies[contains(., ",")]]/Hobbies/text()
') as T(C)
order by count(*)
print @i
while @i > 0
begin
update @table set
data.modify('
replace value of
(
Students/
Student[
Hobbies[contains(., ",")]]/Hobbies/text()
)[sql:variable("@i")][1]
with ";"
')
set @i = @i - 1
end;
答案 0 :(得分:0)
这对你有用吗</ p>
declare @table table (classname varchar(10), students xml)
insert into @table values
('A','<Students>
<Class>A</Class>
<StudentA>
<Name>John</Name>
<Hobbies>Music,Reading,Baseball</Hobbies>
</StudentA>
<StudentB>
<Name>David</Name>
<Hobbies></Hobbies>
</StudentB>
<StudentC>
<Name>Sofiya</Name>
<Hobbies>Surfing,Basketball</Hobbies>
</StudentC>
</Students>');
SELECT * from @table
update @table
set students=convert(xml,replace(convert(varchar(max),students),',',';'))
select * from @table;
假设不,出现在爱好以外的任何地方