5

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?

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
Eric
  • 1,321
  • 2
  • 15
  • 30

2 Answers2

4

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 
Eric
  • 1,321
  • 2
  • 15
  • 30
  • It is a problem with this solution. – sammybar Nov 11 '14 at 15:47
  • 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 , 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. – sammybar Nov 11 '14 at 15:59
  • 1
    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 http://msdn.microsoft.com/en-us/library/ms190312.aspx – sammybar Nov 11 '14 at 16:19
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
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197