我需要编写一个基本的t-sql函数 f ,它接收以下参数:
(Id int, CustomerId int, Delay int)
并为 f(1,125,32)创建以下xml,稍后将其插入到表中的xml列中:
<content>
<column name="Id">1</column>
<column name="CustomerId">125</column>
<column name="Delay">125</column>
</content>
有关如何解决问题的任何想法?
答案 0 :(得分:1)
DECLARE @Id int, @CustomerId int, @Delay int
SELECT @Id = 1, @CustomerId = 125, @Delay = 32;
-- Solution #1
SELECT CONVERT(XML,N'').query(
N'<content>
<column name="Id">{sql:variable("@Id")}</column>
<column name="CustomerId">{sql:variable("@CustomerId")}</column>
<column name="Delay">{sql:variable("@Delay")}</column>
</content>');
-- Solution #2
SELECT 'Id' AS '@name', @Id AS 'text()'
UNION ALL SELECT 'CustomerId', @CustomerId
UNION ALL SELECT 'Delay', @Delay
FOR XML PATH('column'), ROOT('content');
-- Solution #3
SELECT *
FROM
(
SELECT @Id AS Id, @CustomerId AS CustomerId, @Delay AS [Delay]
) src
UNPIVOT( [@name] FOR [text()] IN ([Id], [CustomerId], [Delay]) ) unpvt
FOR XML PATH('column'), ROOT('content');
-- Solution #4
SELECT
(
SELECT @Id AS Id, @CustomerId AS CustomerId, @Delay AS [Delay]
FOR XML RAW, TYPE
).query
('
<content>
{for $i in //@*
return <column name="{local-name($i)}">{string($i)}</column>}
</content>
');
答案 1 :(得分:1)
select *
from (values
(@Id, 'Id'), (@CustomerId, 'CustomerId'), (@Delay, 'Delay')
) as a([@Name], [text()])
for xml path('column'), root('content')
<强> sql fiddle demo 强>