【问题标题】:SQL Server FOR XML formatSQL Server FOR XML 格式
【发布时间】:2023-03-03 04:06:01
【问题描述】:

请问,如果 XML 输出需要这样,有人知道如何编写 SQL FOR XML 子句:

<element attribute="attribute_value">sub_element_or_value</element>

更多信息是关于这个问题https://dba.stackexchange.com/questions/163658/ms-sql-db-design-help

*DB 在 Azure SQL 数据库中。

【问题讨论】:

  • 不要发布更多信息链接到另一个问题。将内容添加到您的问题中。

标签: sql sql-server for-xml-path for-xml


【解决方案1】:

这是你要找的吗?

DECLARE @table TABLE(ID INT IDENTITY, code VARCHAR(100),val VARCHAR(100));
INSERT INTO @table  VALUES
 ('Code 1','Value 1')
,('Code 2','Value 2')
,('Code 3','Value 3')
,('Code 4','Value 4');

SELECT t.code AS [@code]
      ,t.val AS [*] 
FROM @table AS t
FOR XML PATH('element'),ROOT('elements');

结果

<elements>
  <element code="Code 1">Value 1</element>
  <element code="Code 2">Value 2</element>
  <element code="Code 3">Value 3</element>
  <element code="Code 4">Value 4</element>
</elements>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-05
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多