当我试图在游标循环中运行以下SQL代码段时,
set @cmd = N'exec sp_rename ' + @test + N',' +
RIGHT(@test,LEN(@test)-3) + '_Pct' + N',''COLUMN'''
我得到了以下消息,
消息15248,级别11,状态1,Procedure sp_rename,第213行
参数列不明确,或者声明的列( @objtype
)错误。
哪里出了问题,我该如何修复它?我试着按照一些搜索结果的建议,用括号[]
和双引号""
将列名括起来。
编辑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“为前缀。
发布于 2012-06-15 03:35:16
这是一个稍微修改过的版本。更改被标注为代码注释。
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
https://stackoverflow.com/questions/11035187
复制相似问题