sql - SQL Server 中带有 XML 列的临时表

标签 sql sql-server xml

我在 SQL Server 中有一个表,我将表中结果集的值放入 XML 中,如下所示:

select 
  lAccountID,
  sName,
  sAge
from 
  AccountDVDetails 
where 
  laccountID = 10 
for xml raw ('Values'), ROOT ('Accounts'), ELEMENTS 

此查询为我提供了 XML ,例如

<Accounts>
<Values>
  <lAccountID>10</lAccountID>
  <sName>A</sName>
  <sAge>21</sAge>
</Values>
<Values>
  <lAccountID>10</lAccountID>
  <sName>B</sName>
  <sAge>22</sAge>
</Values>
<Values>
  <lAccountID>10</lAccountID>
  <sName>C</sName>
  <sAge>23</sAge>
</Values>
</Accounts>

现在我想将这个 XMLlAccountId 存储在临时表 #tmpAccount 中,例如

   lAccountId     XMLValue
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     10           <Accounts><Values><lAccountID>10</lAccountID><sName>A</sName><sAge>21</sAge></Values><Values><lAccountID>10</lAccountID><sName>B</sName><sAge>22</sAge></Values><Values><lAccountID>10</lAccountID><sName>C</sName><sAge>23</sAge></Values></Accounts> 

我怎样才能实现这个目标?我尝试将 XML 放入 string 变量中,但 XML 被截断到一定限制。

任何帮助将不胜感激。谢谢。

最佳答案

尝试为多个帐户创建嵌套的分层 XML

首先,我声明一些表变量来模拟测试场景。我假设有一个包含帐户的父表:

DECLARE @dummyAccount TABLE(lAccountID INT IDENTITY,SomeData VARCHAR(100));
DECLARE @dummyAccountDetail TABLE(lAccountDetail INT IDENTITY,lAccountID INT,sName VARCHAR(100),sAge INT);--do not store the age as int but the DoB!!!

INSERT INTO @dummyAccount VALUES('Account 1'),('Account 2');
INSERT INTO @dummyAccountDetail VALUES(1,'Jane',20),(1,'John',30)
                                     ,(2,'Tim',40),(2,'Tom',50);

查询会将帐户列为第一级(我添加了一些描述属性只是为了展示原理,但您可以轻松地让它们离开。子选择将为每个帐户单独创建一个 XML。

SELECT A.lAccountID 
      ,A.SomeData 
      ,(
        SELECT D.lAccountID
              ,D.sName
              ,D.sAge
        FROM @dummyAccountDetail AS D
        WHERE D.lAccountID=A.lAccountID
        FOR XML PATH('Values'),ROOT('Accounts'),TYPE
       )

FROM @dummyAccount AS A     

您只需使用

即可轻松创建表#tmpAccount
SELECT ...
INTO #tmpAccount
FROM ...

...或者,如果它已经存在,只需使用

INSERT INTO #tmpAccount
SELECT ...

关于sql - SQL Server 中带有 XML 列的临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41800231/

相关文章:

sql - 如何在 SQL Server 2005 中插入没有可写列的表?

java - 表中的更多名称属性

java - 将 http url 传递到 SAXParser XML 中

php - 使用 mysqli_fetch_array 多次循环查询结果?

c# - 如何在 C# .NET (SQL Server) 中正确有效地重用准备好的语句?

mysql - 将 csv 导入到 sql bash

javascript - 在 HTML 中嵌入 XML

xml - 如何将 xpath 传递到 xquery 函数声明中

php - 从数据库中的字段中减去值

sql - 在 SQL 查询中连接 Azure 数据工厂管道参数