A simple cast will suffice:

select cast(XMLCol as nvarchar(max)) as XMLCol 

Or for non-unicode:

select cast(XMLCol as varchar(max)) as XMLCol 

You can't convert explicitly to a 'text' data type.

I've added the as XMLCol to ensure that the converted data has the the same name as the column. You needn't have this, of course.

EDIT:

A few links. You are encouraged to use nvarchar(max) instead of text regardless. Microsoft have said they will be deprecating these types in future releases. nvarchar(max) ought to offer you 2GB:

http://www.petefreitag.com/item/734.cfm

http://www.teratrax.com/articles/varchar_max.html

http://msdn.microsoft.com/en-us/library/ms187752(v=SQL.90).aspx

Answer from Mutation Person on Stack Overflow
๐ŸŒ
Red Gate Software
red-gate.com โ€บ home โ€บ converting string data to xml and xml to string data
Converting String Data to XML and XML to String Data | Simple Talk
August 24, 2021 - I assign a string value-an XML fragment-to the @string data type, then set the value of @xml to equal @string. Because SQL Server can implicitly convert an NVARCHAR value to an XML value, the assignment is very straightforward, which I confirm ...
๐ŸŒ
SQL Team
sqlteam.com โ€บ forums โ€บ topic.asp
Converting XML column to string and searching it - SQL Server Forums
January 13, 2009 - Microsoft SQL Server articles, forums and blogs for database administrators (DBA) and developers.
Discussions

sql server - ms sql xml data type convert to text - Stack Overflow
in MS Sql there are data types that are not supported by delphi 7, the xml datatype is one example. I wish to convert the XML datatype to Text datatype, so that i could handle it in delphi. Is ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
sql server - T-SQL: Convert XML to string without self-closing tags - Database Administrators Stack Exchange
We have a weirdo system we're integrating with which consumes XML, but it does not understand self-closing tags, so 56812 More on dba.stackexchange.com
๐ŸŒ dba.stackexchange.com
sql server - How to create xml string for each row of table? - Database Administrators Stack Exchange
I have below sql table. I need to add a column xmls to my table such that the table looks like below. CREATE TABLE employees( id integer, name VARCHAR(MAX), design... More on dba.stackexchange.com
๐ŸŒ dba.stackexchange.com
July 31, 2023
Using SQL Server "FOR XML": Convert Result Datatype to Text/varchar/string whatever? - Stack Overflow
And Lotus Script (pretty much VBScript) ... to handle this xml datatype. I tried every way i could find getting the result - Lotus built in ODBC class, LCConnection via OleDB, ADO Connection via OleDB... but every try ends in a bunch of unreadable data. I could imagine a webservice between domino and SQL Server, preparing the data as string for my domino ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
People also ask

How do you convert XML to a string in SQL Server?

Use CAST or CONVERT to transform an XML-typed value to a string: SELECT CAST(XmlColumn AS NVARCHAR(MAX)) FROM YourTable. For the reverse (string to XML), use CAST(StringColumn AS XML). Note that CAST to NVARCHAR(MAX) preserves the full XML content, while NVARCHAR(4000) may truncate large documents. You can also use the .value() method with a specific XPath to extract individual text values directly.

๐ŸŒ
red-gate.com
red-gate.com โ€บ home โ€บ effective strategies for storing and parsing xml in sql server
Store, Parse & Convert XML in SQL Server | Simple Talk
Should you store XML in an XML column or VARCHAR in SQL Server?

Always prefer the native XML data type over VARCHAR. XML-typed columns provide automatic validation (ensuring only well-formed XML is stored), support for XQuery methods (.value, .query, .nodes, .modify), XML-specific indexing, and schema collection binding. Storing XML as VARCHAR loses all these benefits and forces frequent CAST operations. The only exception is when XML content will never be queried by SQL Server and is purely written/read by the application.

๐ŸŒ
red-gate.com
red-gate.com โ€บ home โ€บ effective strategies for storing and parsing xml in sql server
Store, Parse & Convert XML in SQL Server | Simple Talk
What is the fastest way to parse XML in SQL Server?

For querying individual values from XML, the .value() XQuery method is generally fastest. For shredding XML into rows, the .nodes() method outperforms OPENXML for most use cases. OPENXML with sp_xml_preparedocument is better suited for very large documents processed once. For repeated queries against the same XML column, create a primary XML index followed by secondary indexes (PATH, VALUE, or PROPERTY) matching your query patterns. Avoid repeated CAST operations between XML and string types.

๐ŸŒ
red-gate.com
red-gate.com โ€บ home โ€บ effective strategies for storing and parsing xml in sql server
Store, Parse & Convert XML in SQL Server | Simple Talk
๐ŸŒ
SQLServerCentral
sqlservercentral.com โ€บ forums โ€บ topic โ€บ converting-a-xml-datatype-to-varcharmax
Converting a XML datatype to varchar(max). โ€“ SQLServerCentral Forums
August 23, 2016 - Just to expand on this (I began my explanation before Matt's reply). From BOL - TYPE Directive in FOR XML Queries: SQL Server support for the xml (Transact-SQL) enables you to optionally request that the result of a FOR XML query be returned as xml data type by specifying the TYPE directive.
๐ŸŒ
Red Gate Software
red-gate.com โ€บ home โ€บ effective strategies for storing and parsing xml in sql server
Store, Parse & Convert XML in SQL Server | Simple Talk
June 3, 2024 - 10 ingeniously simple tools for ... Use CAST or CONVERT to transform an XML-typed value to a string: SELECT CAST(XmlColumn AS NVARCHAR(MAX)) FROM YourTable....
Find elsewhere
๐ŸŒ
SQL Server Guides
sqlserverguides.com โ€บ sql-server-convert-xml-to-string
SQL Server Convert XML to String - SQL Server Guides
April 12, 2024 - Learn about SQL Server convert XML to string using the CAST() and CONVERT() function of SQL Server.
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ sql โ€บ relational-databases โ€บ xml โ€บ for-xml-support-for-string-data-types
FOR XML Support for String Data Types - SQL Server | Microsoft Learn
CREATE TABLE T ( c1 INT identity PRIMARY KEY, c2 VARCHAR(100) ); GO INSERT T (c2) VALUES ('Special character 0xD for carriage return ' + CONVERT(VARCHAR(10), 0xD) + ' after carriage return'); INSERT T (c2) VALUES ('Special character 0x9 for tab ' + CONVERT(VARCHAR(10), 0x9) + ' after tab'); INSERT T (c2) VALUES ('Special character 0xA for line feed ' + CONVERT(VARCHAR(10), 0xA) + ' after line feed'); GO SELECT * FROM T FOR XML AUTO; GO
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ sql โ€บ t-sql โ€บ functions โ€บ cast-and-convert-transact-sql
CAST and CONVERT (Transact-SQL) - SQL Server | Microsoft Learn
Large-value data types can't be converted to the sql_variant data type. For more information about conversion from the xml data type, see Create Instances of XML Data. When you explicitly or implicitly cast the xml data type to a string or binary data type, the content of the xml data type ...
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ sql โ€บ t-sql โ€บ xml โ€บ value-method-xml-data-type
value() method (xml data type) - SQL Server | Microsoft Learn
Performs an XQuery against XML and returns a value of SQL type. This method returns a scalar value. You typically use this method to extract a value from an XML instance stored in an xml type column, parameter, or variable.
๐ŸŒ
Table Convert
tableconvert.com โ€บ home โ€บ convert xml to insert sql online
Convert XML to Insert SQL Online - Table Convert
January 11, 2019 - The tool automatically parses XML structure and converts it to table format, supporting namespace, attribute handling, and complex nested structures. ... Edit data using our advanced online table editor with professional features. Supports deleting empty rows, removing duplicates, data transposition, sorting, regex find & replace, and real-time preview. All changes automatically convert to SQL format with precise, reliable results.
๐ŸŒ
Reddit
reddit.com โ€บ r/sql โ€บ how to create xml string for each row of table?
r/SQL on Reddit: How to create xml string for each row of table?
July 31, 2023 -

I have below sql table. I need to add a column `xmls` to my table such that the table looks like below.

    CREATE TABLE employees(
          id          integer,
          name        VARCHAR(MAX),
          designation VARCHAR(MAX),
          manager     integer,
          hired_on    date,
          salary      integer,
          commission  float,
          dept        integer);
    INSERT INTO employees VALUES (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4);
    INSERT INTO employees VALUES (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3);
    INSERT INTO employees VALUES (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3);
    INSERT INTO employees VALUES (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3);
    SELECT * FROM employees;

The new column xmls should look like below(last column below), I know I can do it with the help of string utilities but cannot figure the simple yet effective and optimal solution.

This is what I tried but this does not give me the end tag `summary`.

    SELECT (
    SELECT id AS '@id',
    designation AS '@type',
    salary AS '@salary'
    FROM employees b 
    WHERE b.id = a.id
    FOR XML PATH('summary'))
    FROM employees a

๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ sql โ€บ relational-databases โ€บ xml โ€บ create-instances-of-xml-data
Create instances of XML data - SQL Server | Microsoft Learn
August 8, 2024 - SQL Server returns xml data type instances to the client as a result of different server constructs such as FOR XML queries that use the TYPE directive, or where the xml data type is used to return XML from SQL Server Database Engine columns, variables, and output parameters. In client application code, the ADO.NET provider requests that this xml data type information be sent in a binary encoding from the server. However, if you're using FOR XML without the TYPE directive, the XML data returns as a string type.
๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ UploadFile โ€บ vivekbritish โ€บ how-to-read-xml-file-and-xml-string-through-sql-stored-procedure
How to Read XML file and XML String through SQL Stored Procedure
It's also important to note that this stored procedure expects an XML data type as a parameter, so while calling this stored procedure, you need to pass the XML as a string and convert it to XML data type. This article taught us about reading XML data from XML String \ XML File through SQL Stored Procedure.
Top answer
1 of 3
8

If Queries against the XML will happen by sql server xml capabilities, then use XML type to store a xml to avoid casting

And

keep in mind, that XML type may be stored little bit slower due to xml validation, but underlying type of XML is ordinary varbinary(max)

2 of 3
19

what factors should I be considering when trying to decide between storing XML in an xml column vs. a varchar(MAX) column

The factors are:

  1. The XML type is queryable / parseable through XQuery expressions, including being able to use FLWOR Statement and Iteration

  2. Data in XML variables and columns can be modified inline using XQuery expressions via XML DML.

  3. XML data is stored as UTF-16 LE (Little Endian), so VARCHAR(MAX) would be a poor choice as it could result in data loss. Hence, the true decision should be between XML and NVARCHAR(MAX), given that NCHAR / NVARCHAR is also UTF-16 LE.

  4. XML data can be validated against an XSD / XML SCHEMA COLLECTION. No validation (outside of ensuring well-formedness) is done if no XML Schema Collection is specified, but this option is not available when using NVARCHAR(MAX).

  5. One major benefit of the XML type is that it is stored in a highly optimized format (not VARBINARY(MAX) as stated in @Oleg's answer) that does not store the exact string representation that you see, but instead has a dictionary of Element and Attribute names and refers to them by their ID. It also removes whitespace. Try the following:

    DECLARE @Test1 XML = N'<Test><TagName>1</TagName><TagName>2</TagName></Test>';
    
    DECLARE @String1 NVARCHAR(MAX) = CONVERT(NVARCHAR(MAX), @Test1);
    
    SELECT DATALENGTH(@Test1) AS [XmlBytes],
           LEN(@String1) AS [StringCharacters],
           DATALENGTH(@String1) AS [StringBytes];
    
    SET @Test1 = N'<Test><TagName>1</TagName><TagName>2</TagName><TagName>3</TagName>
    <TagName>4</TagName><TagName>5</TagName><TagName>6</TagName></Test>';
    
    SET @String1 = CONVERT(NVARCHAR(MAX), @Test1);
    
    SELECT DATALENGTH(@Test1) AS [XmlBytes],
           LEN(@String1) AS [StringCharacters],
           DATALENGTH(@String1) AS [StringBytes];
    

    Returns:

    XmlBytes   StringCharacters   StringBytes
    56         53                 106
    
    XmlBytes   StringCharacters   StringBytes
    84         133                266
    

    As you can see in the example output above, adding four elements (#s 3, 4, 5, and 6) added 80 characters (hence 80 bytes if using VARCHAR) and 160 bytes to the NVARCHAR variable. Yet, it only added 28 bytes to the XML variable, which is less than it added for VARCHAR (just in case someone was going to argue in favor of VARCHAR over XML because XML is UTF-16 which is [mostly] double-byte). This optimization can save tons of space, and is reason enough by itself to use the XML datatype.

  6. XML data can be indexed via specialized XML indexes