1
我試圖在SQL Server 2014中生成以下所需格式的XML。但是我無法做出這個向Param添加屬性名稱的小改變元素。我只是想使用值將「name」屬性添加到Param元素。sql server - 對於XML Raw - 向元素添加自定義屬性
當前SQL語句: -
Declare @requestMessage xml,
@P1 nvarchar(20)= 'Rocky', @P2 nvarchar(20) = 'Boxer', @P3 nvarchar(20) = 'SpaceX',
@P4 nvarchar(20)
select @requestMessage = (select 'dbo.usp_InsertUserPlay' as [SProc],
(select @P1 as [Param],
@P2 as [Param],
@P3 as [Param],
@P4 as [Param],
0 as [Param]
FOR XML RAW('ParamList'), TYPE, ELEMENTS XSINIL)
FOR XML PATH('AsyncRequest'), TYPE, ELEMENTS XSINIL)
select @requestMessage AS XML_Output
XML輸出: -
<AsyncRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SProc>dbo.usp_InsertUserPlay</SProc>
<ParamList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Param>Rocky</Param>
<Param>Boxer</Param>
<Param>SpaceX</Param>
<Param xsi:nil="true" />
<Param>0</Param>
</ParamList>
</AsyncRequest>
我期望中的XML輸出: -
<AsyncRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SProc>dbo.usp_InsertUserPlay</SProc>
<ParamList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Param name="P1">Rocky</Param>
<Param name="P2">Boxer</Param>
<Param name="P3">SpaceX</Param>
<Param name="P4" xsi:nil="true" />
<Param name="P5">0</Param>
</ParamList>
</AsyncRequest>
感謝您的幫助:-) – Karan
另一件事,我在這裏注意到。我們必須將基於非字符串的參數CAST轉換爲nvarchar(max)數據類型以防止運行時XML生成錯誤。例如,如果@ P4是int,那麼語句應該是('P4',CAST(@ P4 as nvarchar(max))) – Karan