3

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')
1

1 Answer 1

1

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:

  • Build a dynamic SQL statement to allow dynamically filled in pieces like a file name (but you might hardcode this...)
  • Execute the statement with 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;
Sign up to request clarification or add additional context in comments.

7 Comments

Sir,Thank you so much fro the reply. Can I add multiple select above +queryout ?
@SteveTianqinGuo This should work with any SELECT which works on its own... It might be better (better to read and better to maintain) to create a VIEW or a FUNCTION and reduce the call within the BCP-command to a simple 'bcp.exe database.schema.ViewName out ...'. Note that a simple out instead of your queryout does not expect a SELECT but the name of an existing table or VIEW...
I am really appreciate.Thanks! I turn on the BCP and use the following code:
I did what you said. I have the error SQLState = S1000, NativeError = 0 Error = [Microsoft][ODBC Driver 11 for SQL Server]Unable to open BCP host data-file
@SteveTianqinGuo The filename you specify must be a complete and valid path ending with the file name. You might read this
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.