The function that you're looking for is QUOTENAME!
Through the practical use of square bracket technology, you can safely encapsulate strings to aid in the prevention of hot SQL injection attacks.
Note that just sticking square brackets around something does not safely quote it out, though you can avoid your code erroring with invalid characters in object names.
Good code
DECLARE @sql NVARCHAR(MAX) = N''
SELECT @sql = 'SELECT ' + QUOTENAME(d.name) + ' FROM your_mom'
FROM sys.databases AS d
Bad code
DECLARE @sql NVARCHAR(MAX) = N''
SELECT @sql = 'SELECT [' + d.name + '] FROM your_mom'
FROM sys.databases AS d
To give a specific example...
The following works fine for the initial input
DECLARE @ObjectName SYSNAME = 'sysobjects';
DECLARE @dynSql NVARCHAR(MAX) = 'SELECT COUNT(*) FROM [' + @ObjectName + ']';
EXEC (@dynSql);
But with malicious input it is vulnerable to SQL injection
DECLARE @ObjectName SYSNAME = 'sysobjects];SELECT ''This is some arbitrary code executed. It might have dropped a table or granted permissions''--'
DECLARE @dynSql NVARCHAR(MAX) = 'SELECT COUNT(*) FROM [' + @ObjectName + ']';
EXEC (@dynSql);
Using QUOTENAME correctly escapes the embedded ] and prevents the attempted SQL injection from happening.
DECLARE @ObjectName SYSNAME = 'sysobjects];SELECT ''This is some arbitrary code executed. It might have dropped a table or granted permissions''--'
DECLARE @dynSql NVARCHAR(MAX) = 'SELECT COUNT(*) FROM ' + QUOTENAME(@ObjectName);
EXEC (@dynSql);
Invalid object name 'sysobjects];SELECT 'This is some arbitrary code
executed. It might have dropped a table or granted permissions'--'.