1

Is there a way to cause the result set of a SQL Server stored procedure (or any result set, after the fact) to be encoded in XML format?

I want the result set to be encoded in XML as if the FOR XML RAW clause was used during selection.

However the complex stored procedure logic and its internal SELECT statements should not be modified to return XML because the procedure is used for its standard/non-XML result set most of the time.

Update: Emphasis on the fact I'm looking for an answer in the SQL Server environment - the results should be returned as if SQL Server has directly encoded them itself, as XML, just like it does when using the built-in XML features like the FOR XML clause.

John K
  • 28,441
  • 31
  • 139
  • 229

4 Answers4

1

You would insert the data from the SP into a temp table, then select from that FOR XML

This won't work if the SP itself already does a INSERT .. EXEC SPROC because you cannot nest them

Working examples

use tempdb;
create proc giveme
as
select a = 1, b = GETDATE()
union all
select 2, b = '20100101'

Using INSERT.. EXEC

declare @t table (a int, b datetime)
insert @t
exec giveme
select * from @t for xml raw

Using OPENQUERY

exec sp_addlinkedserver 'localhost'

exec sp_serveroption @server = 'localhost' 
   ,@optname = 'DATA ACCESS' 
   ,@optvalue = 'TRUE' 

select *
from openquery(localhost, 'exec tempdb..giveme')
for xml raw
Community
  • 1
  • 1
RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262
0

You could try using OPENROWSET in cooperation with FOR XML to do the transformation.

squillman
  • 13,363
  • 3
  • 41
  • 60
0

By 'after the fact', do you mean still within the SQL Server environment? Or are you talking about a client program?

Within SQL, you could probably write a sproc that acts as a wrapper for your other sprocs, along these lines. The wrapper sproc would handle the FOR XML work.

In .NET, there are a number of ways to do this.

Community
  • 1
  • 1
Carter Wickstrom
  • 176
  • 2
  • 10
  • By after the fact I mean inside the SQL Server environment, I want SQL to encode the results as XML as it normally does. – John K Mar 17 '11 at 21:21
  • I was suggesting Richard's approach, but he was far more thorough than I was... In addition to his approaches, you can also select directly from an `exec` statement. – Carter Wickstrom Mar 17 '11 at 21:39
0

You can try inserting the result set from the stored procedure into a table variable( or temporary table) and selecting the table rows with the FOR XML clause.

Here is an example:

DECLARE @MyDataTable AS TABLE ( col1 int,...., colN int)

Make sure that the @MyDataTable has the same columns as the stored procedure result set(s).

INSERT INTO @MyDataTable 
EXECUTE mysp_GetData @param1=value,....,@paramN;

SELECT * FROM  @MyDataTable
FOR XML AUTO
Iliyan
  • 81
  • 3