如何获取多列以便在游标循环中使用?

当我尝试在游标循环中运行以下 SQL 代码片段时,

set @cmd = N'exec sp_rename ' + @test + N',' +
RIGHT(@test,LEN(@test)-3) + '_Pct' + N',''COLUMN'''

我收到了如下信息,

Msg 15248,第11层,状态1,过程 sp _ rename,第213行
要么参数 @objname不明确,要么声明的 @objtype(COLUMN)错误。

出了什么问题,我该怎么解决?我尝试用括号 []包装列名,并按照一些搜索结果的建议使用双引号 ""

编辑1 -

这是整个剧本。如何将表名传递给重命名 sp?我不确定如何进行此操作,因为列名位于许多表中的一个。

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”作为前缀。

230289 次浏览

Here is slightly modified version. Changes are noted as code commentary.

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