select @[email protected]('*')
for xml raw,type
Above statement will generate following alert:
Msg 6819, Level 16, State 3, Line 2
The FOR XML clause is not allowed in a ASSIGNMENT statement.
views:
2030answers:
2
+1
A:
For example
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
)
refer to : http://blogs.msdn.com/sqlprogrammability/articles/576095.aspx
sesame
2009-05-27 04:59:34
Beware this does not work in SQL SERVER 2000.
joedotnot
2009-09-16 07:45:13
A:
For those using SQL SERVER 2000, FOR XML is next to useless; You cannot assign the generated XML into a variable, insert into a table, etc. I had to do it manually when required, here's my sample:
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
joedotnot
2009-09-16 23:19:32