How To Save XML Query Results to a File

前端 未结 1 1078
孤街浪徒
孤街浪徒 2021-01-20 14:53

I have an SQL query and I am using For XML Path to generate the result as an XML.

Can anyone help me about converting that XML output into \"a.xml

1条回答
  •  逝去的感伤
    2021-01-20 15:15

    You could try using xp_cmdshell....

    -- Read your query results into an XML variable
    DECLARE @xml AS XML = (SELECT * FROM YourTable FOR XML PATH)
    
    -- Cast the XML variable into a VARCHAR
    DECLARE @xmlChar AS VARCHAR(max) = CAST(@xml AS VARCHAR(max))
    
    -- Escape the < and > characters
    SET @xmlChar = REPLACE(REPLACE(@xmlChar, '>', '^>'), '<', '^<')
    
    -- Create command text to echo to file
    DECLARE @command VARCHAR(8000) = 'echo ' + @xmlChar + ' > c:\test.txt'
    
    -- Execute the command
    EXEC xp_cmdshell @command
    

    You could also try a Powershell command if you wanted a bit more control e.g. to set encoding...

    DECLARE @command VARCHAR(8000) = 'powershell -Command "Set-Content -Encoding UTF8 C:\test.txt \"' + @xmlChar + '\""'
    

    A few notes...

    There is an 8000 character length limit on the command, so it's no good for large files.

    If you save the file to a mapped drive, it will look for that drive on the database server. So, C:\ will be referring to the C:\ drive of the server, not where you are running Management Studio.

    Special permissions are required to run xp_cmdshell.

    Click here for more details.

    0 讨论(0)
提交回复
热议问题