2

I need to pass Column name as [ID-ColumnName] as column name in order by for a table.

Ex:

Select [ID-ColumnName],[ID2-ColumnName2] FROM TABLE1 ORDER BY [ID-ColumnName]

Problem is if the ColumnName which is dynamic name comes with one opening/closing square brackets e.g Column[Name or Column]Name

In this scenario the SQL statement is breaking; Problem is I dont know how many such open/close square brackets can come.

Wrapping the column name with square brackets is mandatory in my scenario.

Please help me handling this scenario.

Abhinaw Kaushik
  • 607
  • 6
  • 18

1 Answers1

2

All,

I was able to solve the problem like given below:

Create a table having square brackets in name (You can choose to have any combination of open/close brackets or single open/close).

CREATE TABLE [dbo].[TestTable](
    [OF-[Test [Name]]]]] [nvarchar](100) NULL,
    [Name] [nvarchar](100) NULL
) ON [PRIMARY]

GO

And the Prepare the Dynamic Query and use QUOTENAME() function as suggested by @Damien_The_Unbeliever; but make sure the QUOTENAME() function should not be given as string; post that execute the Query.

DECLARE @orderBy NVARCHAR(MAX),@sql NVARCHAR(MAX)

SET @orderBy = N' ORDER BY '+QUOTENAME('OF-[Test [Name]]')+' ASC'
SET @sql=N'select '+QUOTENAME('OF-[Test [Name]]')+' from TestTable'
--PRINT(@sql +@orderBy)
EXEC(@sql +@orderBy)

Thanks for all your help & suggestions.

Abhinaw Kaushik
  • 607
  • 6
  • 18