我从SQL表创建了一个XML对象,但仍然需要插入一个标记,并为我的每一列硬编码一个值。
这是我的查询和结果
SELECT
EmployeeName, RequestStatus
FROM K2.SmartBoxData.Akin_LeaveRequest_Header_SMO
WHERE ID =32
FOR XML PATH ('Message')
<Message>
<EmployeeName>Developer</EmployeeName>
<RequestStatus>Line Manager Approval</RequestStatus>
</Message>
这是我想要的结果
<Message>
<tag>
<hardcode> my value </hardcode>
<EmployeeName>Developer</EmployeeName>
</tag>
<tag>
<hardcode> my value 2 </hardcode>
<RequestStatus>Line Manager Approval</RequestStatus>
</tag>
</Message>
您可以使用嵌套的FOR XML
子查询来执行此操作。请确保将,TYPE
添加到嵌套的FOR XML
中,否则它将尝试对其进行转义。
不要为子查询指定列名
SELECT
(
SELECT
hardcode = ' my value ',
lrh.EmployeeName
FOR XML PATH('tag'), TYPE
),
(
SELECT
hardcode = ' my value 2 ',
lrh.RequestStatus
FOR XML PATH('tag'), TYPE
)
FROM SmartBoxData.Akin_LeaveRequest_Header_SMO lrh
WHERE ID =32
FOR XML PATH ('Message'), TYPE;
或者指定列名,但指定一个空的PATH
SELECT
tag = (
SELECT
hardcode = ' my value ',
lrh.EmployeeName
FOR XML PATH(''), TYPE
),
tag = (
SELECT
hardcode = ' my value 2 ',
lrh.RequestStatus
FOR XML PATH(''), TYPE
)
FROM SmartBoxData.Akin_LeaveRequest_Header_SMO lrh
WHERE ID =32
FOR XML PATH ('Message'), TYPE;
db<gt;小提琴