Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在xml的所有节点中包含属性值的T-sql查询_Sql_Sql Server_Xml_Tsql - Fatal编程技术网

在xml的所有节点中包含属性值的T-sql查询

在xml的所有节点中包含属性值的T-sql查询,sql,sql-server,xml,tsql,Sql,Sql Server,Xml,Tsql,希望你们都做得很好。我要求sql查询在xml的所有节点中包含属性值。在下面的脚本中,ID值应作为属性出现在所有节点中。示例代码并尝试供您参考 示例脚本: CREATE TABLE XMLGEN(ID INT,A VARCHAR(255),B VARCHAR(255)) INSERT INTO XMLGEN SELECT 1,'a1','b1' union all SELECT 2,'a2','b2' un

希望你们都做得很好。我要求sql查询在xml的所有节点中包含属性值。在下面的脚本中,ID值应作为属性出现在所有节点中。示例代码并尝试供您参考

示例脚本:

CREATE TABLE XMLGEN(ID INT,A VARCHAR(255),B  VARCHAR(255))

INSERT INTO XMLGEN  SELECT 1,'a1','b1' 
                    union all SELECT 2,'a2','b2'  
                    union all SELECT 3,'a3','b3'  
                    union all SELECT 4,'a4','b4'
                    union all SELECT 5,'a5','b5'
我尝试的查询:

select ID as '@Attribute', * from XMLGEN  FOR XML PATH('ImportData'), TYPE,root('root')
输出:

<root>
  <ImportData Attribute="1">
    <ID>1</ID>
    <A>a1</A>
    <B>b1</B>
  </ImportData>
  <ImportData Attribute="2">
    <ID>2</ID>
    <A>a2</A>
    <B>b2</B>
  </ImportData>
  <ImportData Attribute="3">
    <ID>3</ID>
    <A>a3</A>
    <B>b3</B>
  </ImportData>
  <ImportData Attribute="4">
    <ID>4</ID>
    <A>a4</A>
    <B>b4</B>
  </ImportData>
  <ImportData Attribute="5">
    <ID>5</ID>
    <A>a5</A>
    <B>b5</B>
  </ImportData>
</root>

1.
a1
b1
2.
a2
b2
3.
a3
b3
4.
a4
b4
5.
a5
b5
预期产出:

<root>
  <ImportData>
    <ID Attribute="1">1</ID>
    <A Attribute="1">a1</A>
    <B Attribute="1">b1</B>
  </ImportData>
  <ImportData>
    <ID Attribute="2">2</ID>
    <A Attribute="2">a2</A>
    <B Attribute="2">b2</B>
  </ImportData>
  <ImportData>
    <ID Attribute="3">3</ID>
    <A Attribute="3">a3</A>
    <B Attribute="3">b3</B>
  </ImportData>
  <ImportData>
    <ID Attribute="4">4</ID>
    <A Attribute="4">a4</A>
    <B Attribute="4">b4</B>
  </ImportData>
  <ImportData>
    <ID Attribute="5">5</ID>
    <A Attribute="5">a5</A>
    <B Attribute="5">b5</B>
  </ImportData>
</root>

1.
a1
b1
2.
a2
b2
3.
a3
b3
4.
a4
b4
5.
a5
b5

任何人都可以帮助建立查询吗????

只有代码答案可以解决问题,但是一些解释会使它更容易理解,对未来的用户有用。
select 
    ID as [ID/@Attribute]
    ,ID as [ID]
    ,ID as [A/@Attribute]
    ,A as [A]
    ,ID as [B/@Attribute]  
    ,B as [B]
from XMLGEN  FOR XML PATH('ImportData'), TYPE,root('root')