Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.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
Sql server 在SQL Server中为XML路径缩进子类别?_Sql Server_Sql Server 2019_For Xml Path - Fatal编程技术网

Sql server 在SQL Server中为XML路径缩进子类别?

Sql server 在SQL Server中为XML路径缩进子类别?,sql-server,sql-server-2019,for-xml-path,Sql Server,Sql Server 2019,For Xml Path,我需要将数据从SQLServer导出到XML文件中。我知道如何输出到文本文件,但我在XML格式方面遇到了困难 样本数据: CREATE TABLE dbo.testdata (accountid varchar(100), activeaccount bit, text1 varchar(100), text2 varchar(100)

我需要将数据从SQLServer导出到XML文件中。我知道如何输出到文本文件,但我在XML格式方面遇到了困难

样本数据:

CREATE TABLE dbo.testdata (accountid varchar(100),
                           activeaccount bit,
                           text1 varchar(100),
                           text2 varchar(100))

INSERT INTO dbo.testdata VALUES ('T00000001',0,'Fish' ,'Blue'),
                                ('T00000002',1,'Bread','Red' ),
                                ('T00000003',1,'Onion','Blue')
我的XML导出代码:

SELECT accountid AS '@ID',
       activeaccount,
       text1,
       text2
  FROM dbo.testdata
FOR XML PATH ('acccountid'), root ('detail')
该输出的输出:

<detail>
   <acccountid ID="T00000001">
      <activeaccount>0</activeaccount>
      <text1>Fish</text1>
      <text2>Blue</text2>
   </acccountid>
   <acccountid ID="T00000002">
      <activeaccount>1</activeaccount>
      <text1>Bread</text1>
      <text2>Red</text2>
   </acccountid>
   <acccountid ID="T00000003">
      <activeaccount>1</activeaccount>
      <text1>Onion</text1>
      <text2>Blue</text2>
   </acccountid>
</detail>

0
鱼
蓝色
1.
面包
红色
1.
洋葱
蓝色
我想要的是将“text1”和“text2”字段缩进accountid的子类别中,名为“preferences”,因此输出如下所示:

<detail>
   <acccountid ID="T00000001">
      <activeaccount>0</activeaccount>
      <preferences>
         <text1>Fish</text1>
         <text2>Blue</text2>
      </preferences>
   </acccountid>
   <acccountid ID="T00000002">
      <activeaccount>1</activeaccount>
      <preferences>
         <text1>Bread</text1>
         <text2>Red</text2>
      </preferences>
   </acccountid>
   <acccountid ID="T00000003">
      <activeaccount>1</activeaccount>
      <preferences>
         <text1>Onion</text1>
         <text2>Blue</text2>
      </preferences>
   </acccountid>
</detail>

0
鱼
蓝色
1.
面包
红色
1.
洋葱
蓝色

这应该是显而易见的,但我在FOR XML PATH命令中尝试的每一件事都是将字段按错误的顺序放置,根本不起作用,或者在我不需要的地方添加额外的内容。让我有点疯狂。

一种方法是在列的别名中定义它:

选择accountid作为'@ID',
activeaccount,
text1作为[首选项/text1],
text2作为[首选项/text2]
从dbo.testdata
对于XML路径('acccountid'),根('detail');

Legend,谢谢,效果非常好。只是我遗漏了一点简单的语法!