3

私のxmlはffのように見えます:

<root>
  <TemplateQuestion>
    <Row rfqID="1" rftID="1" questionDesc="Question 1" responseType="1" rfqDisplayOrder="1" deletedBit="0" />
    <Row rfqID="2" rftID="1" questionDesc="Question 2" responseType="2" rfqDisplayOrder="2" deletedBit="0" />
    <Row rfqID="3" rftID="1" questionDesc="Question 3" responseType="3" rfqDisplayOrder="3" deletedBit="0" />
  </TemplateQuestion>
</root>

ここでの目標は、rfqID の前に文字 "q" を付けることです。したがって、結果は次のようになります。

<root>
  <TemplateQuestion>
    <Row rfqID="q1" rftID="1" questionDesc="Question 1" responseType="1" rfqDisplayOrder="1" deletedBit="0" />
    <Row rfqID="q2" rftID="1" questionDesc="Question 2" responseType="2" rfqDisplayOrder="2" deletedBit="0" />
    <Row rfqID="q3" rftID="1" questionDesc="Question 3" responseType="3" rfqDisplayOrder="3" deletedBit="0" />
  </TemplateQuestion>
</root>

私はこれを行うことでそれを達成しています:

    declare @xml XML
    set @xml = (select dbo.udfGetXMLVal(1))

    declare @nodeCount int
    declare @i int
    declare @qid nvarchar(20)

    set @i = 1
    select @nodeCount = @xml.value('count(/root/TemplateQuestion/Row/@rfqID)','int')
    while(@i <= @nodeCount)
    begin
    select @qid = x.value('@rfqID[1]', 'VARCHAR(20)') 
    from @xml.nodes('/root/TemplateQuestion/Row[position()=sql:variable("@i")]') e(x)
    set @qid = 'q' + @qid
    select @qid

    Set @xml.modify('replace value of (/root/TemplateQuestion/Row/@rfqID)[1] with sql:variable("@qid")')

    set @i = @i + 1 
end

この行に問題があります:

Set @xml.modify('replace value of (/root/TemplateQuestion/Row/@rfqID)[1] with sql:variable("@qid")')

[1] を変数 @i に置き換えるにはどうすればよいですか? sql:variable を使用しようとすると、文字列リテラルでエラーが発生します。

あなたが提供できるどんな助けも大歓迎です。ありがとうございました

4

2 に答える 2

3

素早く汚い:-)

SELECT CAST(REPLACE(CAST(@x AS VARCHAR(MAX)),' rftID="',' rftID="q')  AS XML);

そして、ここにきれいなアプローチがあります:

DECLARE @x  XML='<root>
  <TemplateQuestion>
    <Row rfqID="1" rftID="1" questionDesc="Question 1" responseType="1" rfqDisplayOrder="1" deletedBit="0" />
    <Row rfqID="2" rftID="1" questionDesc="Question 2" responseType="2" rfqDisplayOrder="2" deletedBit="0" />
    <Row rfqID="3" rftID="1" questionDesc="Question 3" responseType="3" rfqDisplayOrder="3" deletedBit="0" />
  </TemplateQuestion>
</root>';

SELECT
(
    SELECT 'q' + R.value('@rfqID','varchar(max)') AS [@rfqID]
          ,R.value('@rftID','int') AS [@rftID]
          ,R.value('@questionDesc','varchar(max)') AS [@questionDesc]
          --other attributes similar    
    FROM @x.nodes('/root/TemplateQuestion/Row') AS A(R)
    FOR XML PATH('Row'),ROOT('TemplateQuestion'),TYPE
)
FOR XML PATH('root');   
于 2016-04-06T11:26:31.573 に答える