Reputation: 83
If I have following SQL statement which I can actually use to generate XML by the data from two tables. I got the results, but I have to right click it, click "Save As," then choose a location (e.g. C:\Users\my\Documents
) for saving this XML. Is there a way to automate this?
SELECT
(SELECT y.* FROM dbo.TableY FOR XML PATH('y'), TYPE) AS 'YElements',
(SELECT a.* FROM dbo.TableA FOR XML PATH('a'), TYPE) AS 'AElements'
FOR XML PATH(''), ROOT('root')
Upvotes: 3
Views: 314
Reputation: 67291
You can use BCP, but you might have to enable XP_CMDSHELL
using SP_CONFIGURE
...
Furthermore there are some riddles to solve, as BCP has some rather weird attitudes (escaping characters, internal multiple quotes, fully qualified names...).
The main idea is:
xp_cmdshell
This will - at least - show you the general approach:
DECLARE @FileName VARCHAR(50)='C:\Users\...';
DECLARE @SQLCmd VARCHAR(2000)=
(
SELECT 'bcp.exe '
+ '"SELECT ''Just a test'' AS TestColumn FOR XML PATH(''''), ROOT(''root'')"'
+ ' queryout '
+ @FileName
+ ' -w -T -S ' + @@SERVERNAME
);
-- display command, for visual check
SELECT @SQLCmd AS 'Command to execute'
-- create the XML file
EXEC xp_cmdshell @SQLCmd;
Upvotes: 1