كيفية الاستعلام عن الصفوف مع تمثيل XML الخاص بها؟
-
06-07-2019 - |
سؤال
أحتاج إلى شيء من هذا القبيل
select * from tb_listings for xml auto
لكنني أحتاج إلى أن يكون كل صف منفصلاً، وليس مستند xml كبير واحد.
لقد حاولت شيئًا مثل ما يلي:
select id, (select * from tb_listings a where a.id=id for xml auto) as xmldata from tb_listings
الإخراج المتوقع مثل:
id xmldata
------------------------------------------------------------
1 <listing><name>ABC</name><xyz>123</xyz></listing>
ولكن يبدو أنه لا يفعل ما أريد، ويستغرق تشغيله وقتًا طويلاً أيضًا.
سيكون موضع تقدير أي أفكار.:)
يحرر: اكتشفه:
select id, (select top 1 * from tb_listings a where a.id=b.id for xml auto) from tb_listings b
إغلاق.
المحلول
جرب شيئًا مثل هذا:
DECLARE @YourTable table (PK1 int, c1 int, c2 varchar(5), c3 datetime)
INSERT INTO @YourTable VALUES (1,2,'abcde','1/1/2009')
INSERT INTO @YourTable VALUES (100,200,'zzz','12/31/2009 23:59:59')
--list all columns in xml format
SELECT
t2.PK1 --optional, can remove this column from the result set and just get the XML
,(SELECT
*
FROM @YourTable t1
WHERE t1.PK1= t2.PK1
FOR XML PATH('YourTable'), TYPE
) as Row
FROM @YourTable t2
انتاج:
PK1 Row
----------- ------------------------------------------------------------------------------------------
1 <YourTable><PK1>1</PK1><c1>2</c1><c2>abcde</c2><c3>2009-01-01T00:00:00</c3></YourTable>
100 <YourTable><PK1>100</PK1><c1>200</c1><c2>zzz</c2><c3>2009-12-31T23:59:59</c3></YourTable>
(2 row(s) affected)
لا تنتمي إلى StackOverflow