sql-server-2005
  • replace
  • xquery-sql
  • 2011-05-03 6 views 5 likes 
    5

    내가하고 싶은 다음 예는 XQuery에게는 내가 좋아하는 것 2005

    를 사용하여 SQL Server 2005의 XML 노드의 텍스트의 일부를 업데이트 할 수있는 방법을 알고 "매우"와 "우수"라는 단어를 대체하는

    declare @xml as xml 
        set @xml = '<root><info>well hello this is a very good example</info></root>' 
        declare @replacement as varchar(50) 
        set @replacement = 'excellent' 
        declare @search as varchar(50) 
        set @search = 'very' 
    
        set @xml.modify('replace value of (/root/info/text())[1] 
            with replace((/root/info/text())[1],sql:variable("@search"),sql:variable("@replacement"))' 
         ) 
        select @xml 
    

    교체 할이 단어가되지는 A XML 태그의 내용이기 때문에 어떤 도움을

    답변

    2

    을 감상 할 수있다 - 그러나 그 내용의 일부 - 텍스트 기반 대체 옵션을 확인하고 싶을 수도 있습니다.

    이 같은이 있다면 그것은 작동합니다 :

    declare @xml as xml 
    
    set @xml = '<root><info>well hello this is a <rating>very good</rating> example</info></root>' 
    

    다음을, 당신은 XML에 도달하고 다른 뭔가 <rating>....</rating>의 내용을 대체 할 수 있습니다 : 그것은 약자로

    declare @replacement as varchar(50) 
    set @replacement = 'excellent' 
    
    set 
        @xml.modify('replace value of (/root/info/rating/text())[1] 
           with sql:variable("@replacement")') 
    
    select @xml 
    

    을하지만, 이제 <info>의 텍스트 콘텐츠를 가져 와서 텍스트 대체를해야합니다.

    DECLARE @xml as XML 
    SET @xml = '<root><info>well hello this is a very good example</info></root>' 
    
    DECLARE @newcontent VARCHAR(1000) 
    SELECT @newcontent = @xml.value('(/root/info/text())[1]', 'VARCHAR(1000)') 
    
    -- replace "very" with "excellent"  
    SELECT @newcontent = REPLACE(@newcontent, 'very', 'excellent') 
    
    SET 
    @xml.modify('replace value of (/root/info/text())[1] 
           with sql:variable("@newcontent")') 
    
    SELECT @xml 
    
    +0

    하지만 정보 태그의 내용이 varchar (1000)보다 크면 nvarchar (max)와 비슷하지만 어떻게 처리합니까? (예 : 정보의 내용이 html 블록이고 데이터베이스를 통해 html 블록의 값을 대체 할 것임) – Peter

    +0

    @peter : 내용이 실제로 XML 태그 (또는 XML 속성)의 전체 내용이 아니라면, 어쨌든이 방법은 나쁘다고 생각합니다. SQL Server 자체가 아닌 해당 데이터를 사용하는 응용 프로그램에서이 작업을 수행합니다. 필자가 전체 XML 태그의 컨텐트를 새로운 컨텐트로 대체 할 수있는 경우에만이 접근법을 제안하는 것이 제 생각입니다. –

    관련 문제