2

对于我的情况,我有与以下类似的 XML:

DECLARE @MyXML XML

SET @MyXML = 
  '
  <Students>
    <Student>
      <Nickname>Cat</Nickname>
      <Name>Catherine</Name>
    </Student>
    <Student>
      <Nickname>Cat</Nickname>
      <Name>Joseph</Name>
    </Student>
  </Students>
  '

SELECT  T.Students.value('Nickname[1]', 'varchar(20)')
FROM    @MyXML.nodes('/Students/Student[Nickname = "Cat"]') T(Students)
JOIN    dbo.MyStudents CLASS ON T.Students.value('Name[1]', 'varchar(20)') = CLASS.StudentName

我想更新从此 SELECT 语句返回的记录,用 CLEARED 替换昵称。因此,如果 dbo.MyStudents 有 Joseph 但没有 Catherine,则生成的 @MyXML 变量将是:

  <Students>
    <Student>
      <Nickname>Cat</Nickname>
      <Name>Catherine</Name>
    </Student>
    <Student>
      <Nickname>CLEARED</Nickname>
      <Name>Joseph</Name>
    </Student>
  </Students>

有没有办法通过直接修改 XML 变量来做到这一点?或者我是否需要将 XML 变量放入临时表并在临时表上执行 .modify?

到目前为止,我发现的示例没有基于连接的 .modify 条件更新。

4

1 回答 1

0

试试这个例子。有关详细信息,请参阅FOR XML 子句的语法

-- sample @MyStudents table
declare @MyStudents table (StudentName varchar(90), NickName varchar(90));
insert @MyStudents values('Kent', '');
insert @MyStudents values('Robert', 'Bobby');
insert @MyStudents values('Lisa', 'LB');
insert @MyStudents values('Venkat', 'Big Cat');
insert @MyStudents values('Catherine', 'Cat');
insert @MyStudents values('Joseph', 'Joey');

DECLARE @MyXML XML
SET @MyXML = 
  '<Students>
    <Student>
      <Nickname>Cat</Nickname>
      <Name>Catherine</Name>
    </Student>
    <Student>
      <Nickname>Joey</Nickname>
      <Name>Joseph</Name>
    </Student>
    <Student>
      <Nickname>Bonzo</Nickname>
      <Name>Clifford</Name>
    </Student>
  </Students>'

select @MyXML = (
    select ( 
        select * from (
            -- set existing @MyStudent records to CLEARED
            select 
                'CLEARED' as NickName,
                T.Students.value('Name[1]', 'varchar(20)') as Name
            from @MyXML.nodes('/Students/Student') T(Students)
            join @MyStudents CLASS ON T.Students.value('Name[1]', 'varchar(20)') = CLASS.StudentName
            union
            -- get students that aren't in @MyStudents table
            select 
                T.Students.value('Nickname[1]', 'varchar(20)') as NickName,
                T.Students.value('Name[1]', 'varchar(20)') as Name
            from @MyXML.nodes('/Students/Student') T(Students)
            where not exists(select 1 from @MyStudents s where s.StudentName = T.Students.value('Name[1]', 'varchar(20)'))
    ) as t1
    for xml path('Student'), type)
for xml path('Students'), type)
于 2013-04-25T20:09:41.237 回答