Cast any string directly to XML with auto-escaping characters in SQL Server

Table of Contents

Recently I had to look up the definition for a bunch of SQL objects and didn’t want to manually retrieve them manually in SSMS (with Create Scripts) or Visual Studio (by searching the object name in my TFS repository).

Since lazyness and automation are the basis of a well done engineering work, I wanted to create a list, where I could basically click on the object that I needed and see the definition right away, without any tool or having to code something externally, of course.

The issue

DMVs and XML came to the rescue here, since everybody remembers that a XML field in SSMS (or AZDS) is clickable and opens up the XML Code in a new window; BUT, you cannot cast everything right away in XML, as some characters needs to be escaped, and most of those characters are often used in object definitions (<,>,etc…)

Here is what happens if you try to cast something to XML directly

How to deal with it

By first creating a XML document with the FOR XML statement, and then casting it as XML in the result set, we obtain what we were looking for:

SELECT s.name AS Schema_Name
    ,  o.name AS Object_Name
    ,  CAST((SELECT m.definition FOR XML PATH('')) as XML) Object_Definition
    ,  o.type_desc
FROM sys.sql_modules m
INNER JOIN sys.objects o
    ON m.object_id = o.object_id
INNER JOIN sys.schemas s
    ON o.schema_id = s.schema_id

It’s as easy as this

Of course it works in SSMS too

As you can see in the ouput XML, special XML characters are escaped automatically, no need to REPLACE(REPLACE(REPLACE(REPLACE
Enjoy!

comments powered by Disqus

Related Posts

How to lose hundreds of thousands of dollars by using functions in SQL Server

Ahh, functions, the greatest tool at a programmer’s disposal, they make code reusable and easy to read, they’ve been essential since the first function call was made in the last century…

Read More

SQL Server 2017 CU5 enhances troubleshooting for Intra-Query Parallelism Deadlock

Do you remember this post from not long ago ? Apparently, other than still being an issue, with the latest SQL Server 2017 CU there are additional tools to see what’s going on and troubleshoot.

Read More

Scan Performance Showdown: INROW Predicate pushdown VS Batch Mode Adaptive Join vs Columnstore indexes

I was reading Paul White’s post about bitmaps in SQL Server and, other than realizing that I basically know nothing about anything (like a Socrate’s epiphany) I wanted to at least see how this good stuff added up in the latest 7 years.

Read More