1
我需要遍歷所有以特定前綴開頭的表來重命名它們。我試過的代碼在下面,但是它以兩個結果中的一個結束,或者崩潰了SSMS(有時),或者我得到了每個表下面的錯誤消息。我用dbo
試過。遍歷並重命名所有帶有對象限定符的表MSSQL
任何人都可以告訴我我做錯了什麼或者建議更好的方法來做到這一點?
No item by the name of 'dbo.prefix_TableName' could be found in the current database 'DatabaseName', given that @itemtype was input as '(null)'.
以下是我正在運行的代碼......
SET NOCOUNT ON;
USE [DatabaseName];
DECLARE @oq NVARCHAR(5), @tableName NVARCHAR(128), @newTableName NVARCHAR(128);
SET @oq = N'prefix_';
/*
find and rename all tables
*/
DECLARE [tableCursor] CURSOR FOR
SELECT [TABLE_NAME] FROM INFORMATION_SCHEMA.TABLES
WHERE [TABLE_TYPE] = 'BASE TABLE' AND [TABLE_NAME] LIKE @oq + '%'
ORDER BY [TABLE_NAME];
OPEN [tableCursor]
FETCH NEXT FROM [tableCursor] INTO @tableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @newTableName = REPLACE(@tableName, @oq, N'');
EXEC('EXEC sp_rename ''dbo.' + @tableName + ''', ''' + @newTableName + '''');
END
CLOSE [tableCursor];
DEALLOCATE [tableCursor];
你錯過了while循環中的一個FETCH語句 – Squirrel
謝謝@Squirrel ...這是問題。你應該把它作爲答案。 –