Chinh Do

SQL Server Implicit String Conversion/Concatenation (XML parsing: line <x>, character <y>, unexpected end of input)

20th February 2010

SQL Server Implicit String Conversion/Concatenation (XML parsing: line <x>, character <y>, unexpected end of input)

posted in Database, Programming |

If you are getting this error in your SQL Server T-SQL script:, you may be running into an issue with implicit string conversion in SQL Server:

declare @xml varchar(max), @doc XML, @stringVariable varchar(256)
set @stringVariable = 'a string value'

-- @doc is set by concatenating multiple string literals
-- and string variables, with all the variables having less than
-- or equal to 8000 characters
set @xml = '<root>' +
... + @stringVariable +
...
'</root>'

print len(@xml)

set @doc = @xml

Output

8000
Msg 9400, Level 16, State 1, Line 4
XML parsing: line 64, character 74, unexpected end of input

As you can see in the output, the @xml variable was truncated to 8000 characters, resulting in an invalid XML. This is due to the way SQL Server performs implicit string conversions when concatenating strings. When all the string literals/variables involved in the concatenation are 8000 characters or less, the resulting string will be exactly 8000 characters.

The same issue occurs with NVARCHAR data type. Instead of the 8000-character limit, it’s 4000 characters.

A simple fix is to make sure at least one of the string variables is of type VARCHAR(MAX):

declare @xml varchar(max), @doc XML, @stringVariable varchar(256)
declare @x varchar(max)

set @stringVariable = 'a string value'
set @x = ''

set @xml = @x + '<root>' +
... + @stringVariable +
...
'</root>'

print len(@xml)

set @doc = @xml

 

More Info

This entry was posted on Saturday, February 20th, 2010 at 2:32 pm and is filed under Database, Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

There are currently 3 responses to “SQL Server Implicit String Conversion/Concatenation (XML parsing: line <x>, character <y>, unexpected end of input)”

  1. 1 On July 31st, 2012, Paul said:

    excellent response to a specific problem, congratulations

  2. 2 On September 28th, 2012, shiva said:

    Nice….one saved my time..

  3. 3 On September 28th, 2012, Chinh Do said:

    Shiva: Thanks for leaving a note.

Leave a Comment