6

I would like to know, how can I load the XML content from an arbitrary file into a local variable?

This works for a fixed file:

DECLARE @xml XML
SET @xml = 
(
  SELECT *
  FROM OPENROWSET(BULK 'C:\data.xml', SINGLE_BLOB) AS data
)

However, I would like to load the data from any arbitrary file.

This does not work (as BULK seems to only support String arguments)

DECLARE @file NVARCHAR(MAX) = 'C:\data.xml'
DECLARE @xml XML
SET @xml = 
(
  SELECT *
  FROM OPENROWSET(BULK @file, SINGLE_BLOB) AS data
)

I've also tried the following (without success, as the local variable (@xml) seems to be out of scope when the EXEC is performed):

DECLARE @file NVARCHAR(MAX) = 'C:\data.xml'
DECLARE @xml XML
DECLARE @bulk NVARCHAR(MAX) = 'SET @xml = (SELECT * FROM OPENROWSET(BULK ''' + @file + ''', SINGLE_BLOB) AS data)'
EXEC (@bulk)

I'm guessing I need to use a temporary table, but how?

2 Answers 2

5

Found a solution:

DECLARE @results table (result XML)
DECLARE @sqlstmt NVARCHAR(MAX)

SET @sqlstmt= 'SELECT * FROM OPENROWSET ( BULK ''' + @file + ''', SINGLE_CLOB) AS xmlData'

INSERT INTO @results EXEC (@sqlstmt)
SELECT @xml = result FROM @results 
Sign up to request clarification or add additional context in comments.

3 Comments

It is a problem with this solution.
It is a problem with this solution. If the xml file is utf-8 encoded and contains international characters (like Ó) AND the xml file DOES NOT starts with the prolog <?xml version="1.0" encoding="UTF-8"?>, in this case sql server 2005 misinterprets the file encoding and the Ó is interpreted like Ó. According to standards in such a case the xml should be considered by default utf-8 encoded but the sql 2005 fails to do that.
I found the solution: use SINGLE_BLOB instead SINGLE_CLOB. Microsoft says: "We recommend that you import XML data only using the SINGLE_BLOB option, rather than SINGLE_CLOB and SINGLE_NCLOB, because only SINGLE_BLOB supports all Windows encoding conversions." at msdn.microsoft.com/en-us/library/ms190312.aspx
3

you can also use sp_executesql:

declare @stmt nvarchar(max), @xml xml

select @stmt = '
    set @xml = (select * from openrowset(bulk ''' + @file + ''', single_clob) as data)
'

exec dbo.sp_executesql
    @stmt = @stmt,
    @params = '@xml xml output',
    @xml = @xml output

Comments

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.