select @result=@input.query('*')
for xml raw,type
上述声明将生成以下警告:
Msg 6819,Level 16,State 3,Line 2
ASSIGNMENT语句中不允许使用FOR XML子句。
答案 0 :(得分:38)
例如
DECLARE @xml_var XML
SET @xml_var =
(
SELECT *,
(
SELECT *
FROM Orders
WHERE Orders.CustomerID=Customers.CustomerID
FOR XML AUTO, TYPE
)
FROM Customers WHERE CustomerID='ALFKI'
FOR XML AUTO, TYPE
)
参考: http://blogs.msdn.com/sqlprogrammability/articles/576095.aspx
答案 1 :(得分:1)
DECLARE @RESULTS XML
SET @RESULTS = (SELECT * FROM Table_Name FOR XML AUTO)
SELECT @RESULTS
答案 2 :(得分:0)
对于那些使用SQL SERVER 2000的人来说,FOR XML几乎没用;你不能将生成的XML分配给变量,插入表格等等。我必须在需要时手动完成,这是我的样本:
SET NOCOUNT ON
create table #parcelData (
parcelID int
, [description] varchar(20)
)
--insert sample data
insert into #parcelData
select 1, 'apples' UNION
select 3, 'oranges' UNION
select 25, 'bananas' UNION
select 69, 'maracuja'
print '-- Example 1: FOR XML RAW --'
select parcelID as pID
from #parcelData
ORDER BY parcelID
FOR XML RAW
--> <row pID="17"/><row pID="25"/><row pID="26"/><row pID="333"/>
print '-- Example 2: Build XML Manually --'
declare @parcelRow varchar(50), @dummy int
, @xmlRowStr varchar(8000)
set @xmlRowStr = '' -- initialize.
DECLARE parcel_cursor CURSOR FOR
select DISTINCT '<row pID="' + cast(parcelID as varchar(10)) + '"/>', parcelID as parcelRow
from #parcelData
ORDER BY parcelID
OPEN parcel_cursor
FETCH NEXT FROM parcel_cursor
INTO @parcelRow, @dummy
WHILE @@FETCH_STATUS = 0 BEGIN
-- build the xml row by row.
set @xmlRowStr = @xmlRowStr + @parcelRow
-- Get next row
FETCH NEXT FROM parcel_cursor
INTO @parcelRow, @dummy
END
CLOSE parcel_cursor
DEALLOCATE parcel_cursor
--print @xmlRowStr
-- wrap a root element around
if @xmlRowStr != '' begin
set @xmlRowStr = '<ROOT>' + @xmlRowStr + '</ROOT>'
end
select @xmlRowStr as XmlOut
DROP TABLE #parcelData
SET NOCOUNT OFF