30

when I was renaming the column in SQL Server, I accidentally inserted the square brackets around the column. The actual statement that I used was:

SP_RENAME 'customer.[EMPLOYEENAMES]', '[EMPLOYEENAME]', 'COLUMN'

But when I try to retrieve the data it just says and I even tried with out square brackets, it gives the same error

Invalid column name '[EMPLOYEENAME]'.

How should I remove the square brackets.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Sreedhar Danturthi
  • 7,119
  • 19
  • 68
  • 111
  • Maybe you can use the `quotename` function, see http://stackoverflow.com/questions/6074826/how-to-escape-square-brackets-inside-square-brackets-for-field-name – The Nail Apr 13 '12 at 07:24

3 Answers3

46

This will restore order in your database:

EXEC SP_RENAME 'customer."[EmployeeName]"', 'EmployeeName','COLUMN'

You cannot use double brackets because it returns syntax error. Quotes circumvent this limitation.

Nikola Markovinović
  • 18,963
  • 5
  • 46
  • 51
8

As you've now got a column with square brackets in the name itself, you can access that column by:

SELECT [[EmployeeName]]] 
FROM Customer

Yes, all those extra square brackets are a bit unwieldy :)

So, I'd rename your column again to remove the brackets:

EXEC SP_RENAME 'customer.[[EmployeeName]]]', 'EmployeeName','COLUMN'

So you can then reference "normally":

SELECT EmployeeName
FROM Customer
AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
1

None of the given alternatives worked for me, so I had to create a new column with the right name, do an update setting newName = [[badName]]], and then drop the wrongly named column.

Sebastián Vansteenkiste
  • 2,234
  • 1
  • 19
  • 29