英文:
How to Rename Column SQL Server with []
问题
我输入了错误的列名,并包含了 [],如上所示 [avail_memory_mb],我想使用语法将其移除,应该如何操作?
我尝试使用以下语法
EXEC sp_RENAME '[db_isdv_itsm].[dbo].[tbl_m_comp_sysboot_time].[avail_memory_mb]', 'avail_memory', 'COLUMN'
但出现了错误
Msg 15248, Level 11, State 1, Procedure sp_RENAME, Line 247 要么参数 @objname 不明确,要么所声明的 @objtype (COLUMN) 错误。
英文:
I entered the wrong column name and included [] as shown above [avail_memory_mb], I want to remove [] using the syntax, how do I do that?
I have tried using syntax
EXEC sp_RENAME '[db_isdv_itsm].[dbo].[tbl_m_comp_sysboot_time].[avail_memory_mb]', 'avail_memory', 'COLUMN'
but an error appears
Msg 15248, Level 11, State 1, Procedure sp_RENAME, Line 247
Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong.
答案1
得分: 2
最简单的方法,在这种情况下,是使用不同的分隔符([]
)来表示列名:
EXEC sys.sp_rename N'dbo.tbl_m_comp_sysboot_time."[avail_memory_mb]"', N'avail_memory', N'COLUMN';
如果你必须使用方括号,那么你需要转义右方括号(]
):
EXEC sys.sp_rename N'dbo.tbl_m_comp_sysboot_time.[[avail_memory_mb]]]', N'avail_memory', N'COLUMN';
注意,在这两个示例中,我还删除了数据库名称。这是因为 sys.sp_rename
不支持四部分命名。首先连接到数据库,然后使用系统存储过程。
如果你需要知道一个对象的文字应该是什么,你可以使用 QUOTENAME
来查找。例如:
SELECT QUOTENAME(N'[avail_memory_mb]');
这将返回 nvarchar(258)
类型的值 [[avail_memory_mb]]]
。所以,如果你真的想要的话,你可以像这样做:
DECLARE @ObjectPath nvarchar(1000) = CONCAT(QUOTENAME(N'dbo'), N'.', QUOTENAME(N'tbl_m_comp_sysboot_time'), '.', QUOTENAME(N'[avail_memory_mb]'));
EXEC sys.sp_rename @ObjectPath, N'avail_memory', N'COLUMN';
英文:
The simplest method, in this case, would be to use a different delimit identifier to brackets ([]
) for your column's name:
EXEC sys.sp_rename N'dbo.tbl_m_comp_sysboot_time."[avail_memory_mb]"', N'avail_memory', N'COLUMN';
If you "must" use brackets, then you need to escape the right bracket (]
):
EXEC sys.sp_rename N'dbo.tbl_m_comp_sysboot_time.[[avail_memory_mb]]]', N'avail_memory', N'COLUMN';
Note that I also removed the database name in both examples. This is because sys.sp_rename
doesn't support 4 part naming. Connect to the database first, and then use the system procedure.
If you ever need to know what an object's literal should be, you can use QUOTENAME
to find it out as well. For example:
SELECT QUOTENAME(N'[avail_memory_mb]');
Which brings back the nvarchar(258)
value [[avail_memory_mb]]]
. So, if you really wanted, you could do something like:
DECLARE @ObjectPath nvarchar(1000) = CONCAT(QUOTENAME(N'dbo'),N'.',QUOTENAME(N'tbl_m_comp_sysboot_time'),'.',QUOTENAME(N'[avail_memory_mb]'));
EXEC sys.sp_rename @ObjectPath, N'avail_memory', N'COLUMN';
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论