sql >> データベース >  >> RDS >> Sqlserver

別の列値の属性を使用して XML 列を追加/変更し、結果を他のフィールドを含む列として返す

    declare @TableX table (ID int identity, XmlField xml)
    
    insert into @TableX values
    (
    '<Node Attrib="9">Name1</Node>
     <Node Attrib="100">Name2</Node>
     <Node Attrib="101">Name2</Node>'
    )
    
    insert into @TableX values
    (
    '<Node Attrib="9">Name1</Node>
     <Node Attrib="101">Name2</Node>'
    )
    
    insert into @TableX values
    (
    '<Node Attrib="1">Name1</Node>'
    )
    
    declare @TableY table (IntField int, OtherField varchar(15))
    
    insert into @TableY values 
    (9, 'SomeOtherValue1'),
    (100, 'SomeOtherValue2'),
    (101, 'SomeOtherValue3')
    
    ;with C as
    (
      select X.ID,
             Y.IntField as Attrib,
             Y.OtherField as OtherField
      from @TableX as X
        cross apply X.XmlField.nodes('/Node') as T(N)
        inner join @TableY as Y
          on T.N.value('@Attrib', 'int') = Y.IntField
    )
    select (select C2.Attrib as '@Attrib',
                   C2.OtherField as '@OtherField'
            from C as C2
            where C1.ID = C2.ID
            for xml path('Node'), type) as XMLField       
    from C as C1
    group by ID
    

    結果:

    XMLField
    <Node Attrib="9" OtherField="SomeOtherValue1" /><Node Attrib="100" OtherField="SomeOtherValue2" /><Node Attrib="101" OtherField="SomeOtherValue3" />
    <Node Attrib="9" OtherField="SomeOtherValue1" /><Node Attrib="101" OtherField="SomeOtherValue3" />
    



    1. MySQLはLIMIT付きの結果の合計を選択します

    2. SQLServerで条件が満たされた場合にのみ起動するトリガー

    3. Sql Serverの単一のcaseステートメントで複数の条件を組み合わせる

    4. C#データテーブルからのSQLServerテーブルの作成