Dynamic SQL, using QUOTENAME

Dynamic SQL, using QUOTENAME

Use QUOTENAME for single quoting, it makes code readable and help to prevent SQL injection problems.

The function QUOTENAME have a parameter for what charachter to use for enclosing the string. The default value is [ and thats perfect for object names. One thing to note is that the parameter takes only 1 charachter but it automatically uses the equivalent other.

Samples:

QOUTENAME('A Frog', '[') --> [A Frog], QOUTENAME('A Frog', ']') --> [A Frog]

QOUTENAME('A Frog', '{') --> {A Frog}, QOUTENAME('A Frog', '}') --> {A Frog}

With the parameter you can use QOUTENAME for dynamic SQL when enclosing strings with single quotes to make it more readable and secure.

Disclaimer:You should always try to avoid what I do in the code below and not concatenate a parameter value to the execution statement string, this is for educational purposes only. Use parameters with sp_executesql instead.

CREATE OR ALTER PROC _Danger
	@CustomerName NVARCHAR(MAX)
AS
BEGIN
	SET NOCOUNT ON;
	SET ARITHABORT ON;

	DECLARE
		@SqlStatement NVARCHAR(MAX);

	/*This is no good*/
	SET
		@SqlStatement = 'SELECT ''' +  @CustomerName + ''' AS _txt;';

	EXEC sp_executesql @SqlStatement = @SqlStatement;
	Print @SqlStatement;

	/*Do this*/
	SET
		@SqlStatement = 'SELECT ' + QUOTENAME(@CustomerName, CHAR(39)) + ' AS _txt;';
	
	EXEC sp_executesql @SqlStatement = @SqlStatement;
	Print @SqlStatement;
END;

GO

EXEC _Danger
	@CustomerName = ''';DECLARE @s NVARCHAR(1024) = N''SELECT * FROM sys.sysusers ''; EXEC sp_executesql @s ; SELECT ''';

/*The result*/
/*
--Without QUOTENAME, this will execute and do bad stuff!!
SELECT '';DECLARE @s NVARCHAR(1024) = N'DROP_ DATABASE ' + QUOTENAME(DB_NAME()); EXEC _sp_executesql @s ; SELECT '' AS _txt;

--With QUOTENAME, this will only return a string
SELECT ''';DECLARE @s NVARCHAR(1024) = N''DROP_ DATABASE '' + QUOTENAME(DB_NAME()); EXEC _sp_executesql @s ; SELECT ''' AS _txt;
*/

        

To view or add a comment, sign in

More articles by Micael Uthas

  • string_split is as bad as table variables.

    Database: StackOverflow2013 COMPATIBILITY_LEVEL: 160 The bad way. Executionplan: Estimation from string_split = 50 but…

    1 Comment
  • ROLLBACK Once, COMMIT Each!

    In SQL Server ROLLBACK TRANSACTION affects all open transactions for the session. COMMIT TRANSACTION affects the latest…

  • Datatype length!

    Make sure to match parameters length with the column´s length. Don´t do this! Complicated execution plan and i Filter…

    2 Comments
  • Indexes and memory.

    In this article, I will demonstrate how indexing can significantly reduce memory consumption, allowing resources to be…

  • Self join to eliminate Key LookUp.

    A Key Lookup retrieves values from the clustered index using the primary key. It occurs when a non-clustered index is…

    2 Comments
  • Batchloading data to Azure fabric from Jeeves using Heap and RID.

    The problem One of my clients wanted to upload data to Microsoft fabric from their ERP (Jeeves). They didn´t want to…

    3 Comments
  • Deleted rows are Ghost in SQL Server

    SQL SERVER does not remove rows from a page when you delete them, instead it´s marked for delete or "ghosted". A…

  • The issue with TRY CATCH in T-SQL.

    Try catch blocks in T-SQL are very useful for handeling errors in your code but there are some stuff you need to…

  • ORM and filtered indexes.

    I´m no big fan of ORM, they have their upsides but for me as a SQL Server nerd it creates more issues then god stuff…

  • INLINE FILTERED INDEX CREATION BUG!

    One feauture in most DBRM´s is the computed column feauture and it is very useful but you cant use it in indexes. The…

    1 Comment

Insights from the community

Others also viewed

Explore topics