Skip to content

Instantly share code, notes, and snippets.

@dhmacher
Created July 20, 2024 19:54
Show Gist options
  • Save dhmacher/d4c7b20c76870efbbc8a8b66a106029b to your computer and use it in GitHub Desktop.
Save dhmacher/d4c7b20c76870efbbc8a8b66a106029b to your computer and use it in GitHub Desktop.
A QUOTENAME() function that works with longer strings
/*
Blog post: https://sqlsunday.com/2023/10/18/i-love-quotename/
*/
CREATE OR ALTER FUNCTION dbo.QUOTENAME_BIG(
@character_string nvarchar(max),
@quote_character nchar(1)=N'['
)
RETURNS nvarchar(max)
WITH SCHEMABINDING
AS
BEGIN;
DECLARE @quoted_string nvarchar(max)=NULL,
@quoted_block nvarchar(max),
@block_size tinyint=100;
WHILE (@character_string IS NOT NULL) BEGIN;
--- Use QUOTENAME() on a block
SET @quoted_block=QUOTENAME(LEFT(@character_string, @block_size), @quote_character);
--- Add that quoted block to @quoted_string
SET @quoted_string=ISNULL(@quoted_string, @quote_character)+
SUBSTRING(@quoted_block, 2, LEN(@quoted_block)-2);
--- Truncate the beginning of the @character_string
SET @character_string=NULLIF(SUBSTRING(@character_string, @block_size+1, LEN(@character_string)), N'');
END;
--- When done, close the quotation on the @quoted_string...
SET @quoted_string=@quoted_string+RIGHT(QUOTENAME(N'', @quote_character), 1);
--- ... and return.
RETURN @quoted_string;
END;
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment