SQL: Making T-SQL Scripts Easier to Read

SQL: Making T-SQL Scripts Easier to Read

When creating tools that script out SQL Server objects, the normal behavior is to quote object names, in case the names wouldn’t otherwise be valid. The problem with that, is that many scripts then become an amazing mess of square brackets that makes the scripts far less readable. And often, there’s no need for the quoting in the first place.

If you avoid things like spaces in object names, you can mostly get away without quoting i.e. Sales.Customers is just fine and doesn’t need to be [Sales].[Customers]. That’s just far less readable IMHO.

Even if you don’t include spaces or other special characters in names, etc. you could still run into problems. For example, a name you had used in your code could become a SQL reserved word. So quoting by default is always a safe option. However, it makes the scripts much harder to read due to visual noise.

There needs to be a better way

What I feel is really needed is some way to determine if a name needs quoting i.e. a function such as:

IS_VALID_AS_OBJECTNAME()

So for example:

IS_VALID_AS_OBJECTNAME(‘Sales’) would return 1 but IS_VALID_AS_OBJECTNAME(‘Sales Targets’) would return 0.

This wouldn’t just be based on the characters in the name. It would also check for reserved words in the language. You might have created a table name Order and that’s fine, but it would need quoting.

What about QUOTENAME ?

For years, I’ve said I’d like to see the QUOTENAME function extended with an optional parameter that says whether or not to quote only when necessary:

In QUOTENAME(‘Sales Targets’, 0), the 0 would be the default, and would also be optional, so the function would work the same as it does today, without code changes.

But in QUOTENAME(‘SalesTargets’, 1), the 1 would indicate that quoting is only returned when needed. So QUOTENAME(‘SalesTargets’, 1) would return SalesTargets but QUOTENAME(‘Sales Targets’, 1) would return [Sales Targets].

That would then make it easy for the team to change SSMS (and other tools) to have a single setting for how you’d like scripts generated. It would also be great for any of us that need to write code that generates scripts.

NB: I really wish there was consistency in the built-in function names and that this was QUOTE_NAME() but that ship has sailed.

The DAX team has already beaten us to this

Note that the DAX team has already beaten us to this. The DAX function NAMEOF now has that option. They’ve realized the need for it and you can pass ESCAPED, UNESCAPED, or MINIMALLYESCAPED to it. You can see it here:

NAMEOF .

2026-05-20