Removing [] around column in SQL Server 2005
-
31-05-2021 - |
سؤال
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.
المحلول
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.
نصائح أخرى
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
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.