How to rename something in SQL Server that has square brackets in the name?

Solution 1:

You do it the same way you do to create it:

exec sp_rename 'BookPublisher."[Book_Category]"', 'Book_Category', 'COLUMN';

Here's a little sample I made to test if this was even possible. At first I just assumed it was a misunderstanding of how [] can be used in SQL Server, turns out I was wrong, it is possible - you have to use double quotes to outside of the brackets.

begin tran

create table [Foo] ("[i]" int);

exec sp_help 'Foo';

exec sp_rename 'Foo."[i]"', 'i', 'column ';

exec sp_help 'Foo';

rollback tran

Solution 2:

Double quotes are not required. You simply double up closing square brackets, like so:

EXEC sp_rename 'BookPublisher.[[Book_Category]]]', 'Book_Category', 'COLUMN';

You can find this out yourself using the quotename function:

SELECT QuoteName('[Book_Category]');
-- Result: [[Book_Category]]]

This incidentally works for creating columns, too:

CREATE TABLE dbo.Book (
   [[Book_Category]]] int -- "[Book_Category]"
);

Solution 3:

this works for me:

exec sp_rename ‘[dbo].[TableName].[OldColumnName]’, ‘NewColumnName’