当我尝试运行游标循环中下面的SQL代码段,
set @cmd = N'exec sp_rename ' + @test + N',' +
RIGHT(@test,LEN(@test)-3) + '_Pct' + N',''COLUMN'''
我收到以下消息,
消息15248,级别11,状态1,过程sp_rename可以,213线
无论是参数@objname
不明确或所要求的@objtype
(列)是错误的。
什么是错的,我怎么解决? 我试着在括号包裹列名[]
和双引号""
像一些搜索结果的建议。
编辑1 -
这里是整个脚本。 我如何通过表名称重命名藻? 我不知道该怎么做,因为列名在许多表之一。
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
declare @cmd nvarchar(500)
declare Tests cursor for
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE 'pct%' AND TABLE_NAME LIKE 'TestData%'
open Tests
fetch next from Tests into @test
while @@fetch_status = 0
BEGIN
set @cmd = N'exec sp_rename ' + @test + N',' + RIGHT(@test,LEN(@test)-3) + '_Pct' + N', column'
print @cmd
EXEC sp_executeSQL @cmd
fetch next from Tests into @test
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
编辑2 - 脚本设计有“PCT”前缀命名,其名称匹配的模式,在这种情况下,列。 列发生在各种数据库中的表。 所有的表名的前缀为“TESTDATA”。
下面是稍作修改的版本。 注意变化的代码注释。
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION