2013-04-02 70 views
2

我的情況在XML變量替換文本,我也有類似的XML以下內容:SQL服務器 - 基於加入

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已經約瑟夫而不是凱瑟琳,產生的@MyXML變量爲:

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

有沒有辦法通過直接修改XML變量來做到這一點?或者我需要將XML變量放入臨時表中並在臨時表上執行.modify?

到目前爲止,我發現的例子沒有基於連接的.modify條件更新。

回答

0

試一試這個例子。欲瞭解更多信息,請參閱Syntax of the FOR XML Clause

-- 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)