Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a column in one of my tables which has square brackets around it, [Book_Category], which I want to rename to Book_Category.

I tried the following query:

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

but I got this error:

Msg 15253, Level 11, State 1, Procedure sp_rename, Line 105 Syntax error parsing SQL identifier 'BookPublisher.[[Book_Category]]'.

Can anyone help me?

like image 821
rajesh Avatar asked Jan 16 '14 17:01

rajesh


People also ask

How do I get rid of square brackets in SQL?

To remove the square brackets that surround the JSON output of the FOR JSON clause by default, specify the WITHOUT_ARRAY_WRAPPER option.

What is [] in SQL query?

The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space) – but then you'd need to use brackets every time you referred to that column. The newer tools add them everywhere just in case or for consistency.

Why do you put [] in SQL?

On SQL Server and MS Access, square brackets have a special meaning when used in a query filter. The square brackets are used to specify a set or range of characters, as in "[A-Z]" which would match any single character from 'A' to 'Z'.

Can SQL column names have brackets?

It's only necessary if the column name contains spaces or punctuation or conflicts with a reserved word, but many wizards will just add the brackets for all field names to avoid the logic for deciding whether they are necessary.


Video Answer


3 Answers

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
like image 143
DaveShaw Avatar answered Oct 19 '22 20:10

DaveShaw


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]"
);
like image 30
ErikE Avatar answered Oct 19 '22 21:10

ErikE


this works for me:

exec sp_rename ‘[dbo].[TableName].[OldColumnName]’, ‘NewColumnName’
like image 1
danmbuen Avatar answered Oct 19 '22 20:10

danmbuen