简体   繁体   English

创建时在一个短表达式内将元素转换为属性 XML

[英]Convert elements into attributes within one short expression when creating XML

I found a common method to create XML from tables where elements' names changed into attributes' names.我找到了一种常用方法,可以从元素名称更改为属性名称的表中创建 XML。 It looks like看起来像

SELECT  ElementName_1 as "@AttName_1", ElementName_2 as "@AttName_2", ElementName_3 as "@AttName_3", etc..
from table
for XML PATH

Is there a method to shorten this kind of converting entry?有没有办法缩短这种转换条目? For example i have dozens of fields\columns and need co convert all of them except one.例如,我有几十个字段\列,需要共同转换除一个之外的所有字段。 So, formally it would looks like所以,正式它看起来像

 (SELECT table.* --> all @attributes --> except 'OneFieldName'

If it possible, how it would be noted correctly?如果可能的话,如何正确记录?

It will be better to specify the columns.指定列会更好。 What if someone add new columns and you are using SELECT * ?如果有人添加新列并且您使用的是SELECT *怎么办?

If you do not want to write the definition itself, you can build it using the sys.columns system view.如果不想自己编写定义,可以使用sys.columns系统视图构建它。 It will be something like this:它将是这样的:

SELECT CONCAT(QUOTENAME([name]), ' AS "AttName_', [column_id], '"') 
FROM 
(
    SELECT ROW_NUMBER() OVER (ORDER BY [column_id]) AS [column_id]
          ,[name]
    FROM sys.columns
    WHERE [object_id] = OBJECT_ID('dbo.table')
        AND [name] NOT IN ('OneFieldName')
) DS

and you can even use STRING_AGG to build the whole SELECT :您甚至可以使用STRING_AGG构建整个SELECT

SELECT STRING_AGG(CAST(CONCAT(QUOTENAME([name]), ' AS "AttName_', [column_id], '"') AS NVARCHAR(MAX)), ', ') WITHIN GROUP (ORDER BY [column_id])
FROM 
(
    SELECT ROW_NUMBER() OVER (ORDER BY [column_id]) AS [column_id]
          ,[name]
    FROM sys.columns
    WHERE [object_id] = OBJECT_ID('dbo.table')
        AND [name] NOT IN ('OneFieldName')
) DS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM