让我们看看这个SQL查询
SELECT *
FROM Customer
WHERE Id = 60
FOR XML PATH ('Customer'), ELEMENTS XSINIL, TYPE
它会像这样返回XML
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Id>60</Id>
<BranchId>5</BranchId>
<DocKind>3</DocKind>
<Document>SomeDoc</Document>
....
如何将Column_id
作为Xml属性添加到每个节点?
这是返回表Column_Id
Customer
的查询:
SELECT COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME),
COLUMN_NAME, 'ColumnID') AS COLUMN_ID, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customer'
我想要这样的结果:
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Id ColumnId=1>60</Id>
<BranchId ColumnId=2>5</BranchId>
<DocKind ColumnId=3>3</DocKind>
<Document ColumnId=4>SomeDoc</Document>
答案 0 :(得分:1)
这是解决方案:
DECLARE @s VARCHAR(MAX) =
'select ' + STUFF(( SELECT ',' + CAST(COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA +
'.' + TABLE_NAME), COLUMN_NAME, 'ColumnID') AS VARCHAR(10)) +
' as ''' + COLUMN_NAME + '/@ColumnID'', [' + COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customer'
FOR XML PATH('')), 1, 1, '') +
' from Customer FOR XML PATH(''Customer''),ELEMENTS XSINIL, TYPE'
EXEC (@s)
答案 1 :(得分:0)
如果您在SQL Server中,我认为您可以为每个字段创建相关子查询,例如:
(select top(1) COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME),
COLUMN_NAME, 'ColumnID') AS COLUMN_ID
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customer' AND COLUMN_NAME = 'BranchId') as 'BranchID/@Column_ID'
这是TSQL FOR XML PATH Attribute On , Type中提供的信息的快速应用。
通过一些样本数据,可以更容易地看出它是否有效......
CREATE TABLE Customer (ID INT IDENTITY(1,1), BranchID INT)
GO
INSERT INTO Customer SELECT ID FROM (VALUES (1),(2)) x(id)
GO
SELECT (SELECT TOP(1) COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME),COLUMN_NAME, 'ColumnID')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customer'
AND COLUMN_NAME = 'ID') AS 'ID/@Column_ID'
,ID
,(SELECT TOP(1) COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME), COLUMN_NAME, 'ColumnID')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customer' AND COLUMN_NAME = 'BranchId') AS 'BranchID/@Column_ID'
,BranchID
FROM Customer
WHERE Id = 1 FOR XML PATH ('Customer'), ELEMENTS XSINIL, TYPE
这让我:
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID Column_ID="1">1</ID>
<BranchID Column_ID="2">1</BranchID>
</Customer>