Quotename() function is used to return a unicode string with delimiters. A delimiter can be a single quote, double quote or braces ( or [.
select
quotename('test','''') as single_quote,
quotename('test','"') as double_quote,
quotename('test','(') as brace,
quotename('test','[') as sqaure_beace
The result is
single_quote double_quote brace sqaure_beace
------------ ------------ -------- ------------
'test' "test" (test) [test]
Consider the following example. A variable @display is used for a display purpose ie to show them as part of the resultset.
create table #t(data varchar(100))
insert into #t(data)
select 'test' union all
select 'testing' union all
select 'nothing'
declare @sql varchar(1000), @display varchar(100), @data varchar(100)
select @display ='Reporting', @data='test'
select @display as display,data from #t where data=@data
The result is
display data
------------ ------------
Reporting test
What if a single should be appended to the value Reporting?. We can use this method
select ''''+@display+'''' as display,data from #t where data=@data
The quotename can be used in this case
select quotename(@display,'''') as display,data from #t where data=@data
But beware that the Quotename() function will not work if the input's length is more than 128 characters