Is this a problem in the sp_rename function or sql server?

When renaming a column name, a square bracket is included in the column name, which I think is an error. Here is an example code snippet,

 create table [TestTable]

(TestColumnName nvarchar(30))

select TestColumnName from TestTable

sp_rename '[TestTable].[TestColumnName]', '[RenamedColumnName]', 'Column'

select [RenamedColumnName] from TestTable -- does not work "Invalid column name 'RenamedColumnName'."

select RenamedColumnName from TestTable -- does not work "Invalid column name 'RenamedColumnName'."

select * from [TestTable]  -- works fine!!!

the error is that the rename column contains square brackets , I found this , which says that "the first character must be one of the following", but " [ " does not seem to be included in the list, there is a problem with sp_rename or sql server , because it allows you to change the name of a column using a square bracket.

+3
source share
5 answers

, [] -

SELECT [[RenamedColumnName]]] FROM TestTable

] - , . ], ] , .

+5

, :

IF EXISTS(SELECT * FROM sys.columns where name ='[MyColumn]' AND [object_id]=OBJECT_ID('[MyTable]'))
BEGIN
EXEC sp_rename 'MyTable.[[MyColumn]]]', 'MyColumn', 'COLUMN';
END

, , .

+4

!!!

sp_rename '[TestTable].[TestColumnName]', '[RenamedColumnName]', 'Column'

sp_rename '[TestTable].[TestColumnName]', 'RenamedColumnName', 'Column'

select [RenamedColumnName] from TestTable -- works fine!!!

select RenamedColumnName from TestTable -- works fine!!!

select * from [TestTable]  -- works fine!!!

, "Renamed ColumnName",

+1

, "[" "]" . sp_rename , , , - , , "[MyColumnWithBrackets]" "MyColumnWithBrackets". , , , ()

+1

. , , , .. , script .

sp_rename: http://msdn.microsoft.com/en-us/library/aa238878(SQL.80).aspx

from BOL: this example renames the contact column header in the client table to header: EXEC sp_rename "clients. [contact name]", "name", 'COLUMN'

try the following:

sp_rename 'TestTable.TestColumnName', 'RenamedColumnName', 'Column'

since you are passing strings to a procedure in which you do not need the square brackets "[", "]"

you can use "[", "]" in the first parameter, but if you use them in the second parameter, they become part of the actual column name:

create table [TestTable2]([Test ColumnName] nvarchar(30))
exec sp_help testtable2
exec sp_rename 'dbo.TestTable2.[Test ColumnName]', 'Renamed ColumnName', 'Column'
exec sp_help testtable2
0
source

Source: https://habr.com/ru/post/1738949/


All Articles