6

I have a SQL Server column of type XML containing some records with more than 8000 characters.

I would like to convert this column into a varchar.

I am not concerned about truncation (the first 8000 characters is fine).

However, whenever I try CONVERT(varchar(8000), Content) I get an error:

Target string size is too small to represent the XML instance

When I try CONVERT(varchar(MAX), Content) I get an error:

String or binary data would be truncated

When I try CONVERT(varchar(20000), Content) I get an error:

The size (20000) given to the type 'varchar' exceeds the maximum allowed for any data type (8000)

When I try CONVERT(text, Content) I get an error:

Explicit conversion from data type xml to text is not allowed

Is there a workaround?

2

3 Answers 3

11

Cast to varchar(max) should work just fine. You probably have an issue elsewhere. You would get that error if you try to insert/update a column with datatype varchar(8000).

2
2

The issue that you are running into has to do with attempting to convert the XML into VARCHAR. I have run into a similar issue before when trying to convert an XML string that is much smaller than yours into NVARCHAR. Switching from a CONVERT to a CAST should solve your problem. As far as the size, you are better off just setting it to MAX.

1

I have never had this particular need, but another way I would try would be:

SUBSTRING(CAST(Content AS VARCHAR), 1, 8000)

This will obviously truncate the content, so you should be aware of that if that's not appropriate for your use case.

3
  • 2
    This will truncate the string, which is probably not the desired result. Jul 17, 2012 at 7:18
  • 1
    Unfortunately not, it tries to cast before you have a chance to substring it > Target string size is too small to represent the XML instance Jul 17, 2012 at 7:22
  • Ignore my comment, this would probably work although the substring is unnecessary. Jul 17, 2012 at 7:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.