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?
To remove the square brackets that surround the JSON output of the FOR JSON clause by default, specify the WITHOUT_ARRAY_WRAPPER option.
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.
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'.
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.
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
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]"
);
this works for me:
exec sp_rename ‘[dbo].[TableName].[OldColumnName]’, ‘NewColumnName’
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With