MSSQL: Rename Table
tsql | by: ITManxLtd
last edit: Oct, 17th 2011 | jump to bottom
/* Safely renames a table and associated objects in MSSQL 2008 */ ALTER PROCEDURE [dbo].[RenameTable] ( @id int, @newname nvarchar(128) --128 is the max length for a table name ) AS BEGIN SET NOCOUNT ON; SET QUOTED_IDENTIFIER ON; IF ((SELECT LEFT(@newname, 1)) = '#') BEGIN RAISERROR ('Illegal first character', 16, 1); RETURN; END --128 is the maximum table name length. double the size in case of ] replacement with ]] DECLARE @table_oldname nvarchar(256), @table_newname nvarchar(256), @object_oldname nvarchar(256), @object_newname nvarchar(256); SELECT @table_oldname=name FROM sys.tables WHERE object_id = @id; IF (@table_oldname IS NULL) BEGIN RAISERROR ('No table was found with that object_id', 16, 1); RETURN; END SET @table_newname=@newname; DECLARE c CURSOR FOR SELECT [name] FROM sys.objects WHERE parent_object_id = @id; OPEN c FETCH c INTO @object_oldname WHILE @@Fetch_Status=0 BEGIN SET @object_newname = REPLACE(SUBSTRING(@object_oldname,0,4) + SUBSTRING(@table_newname,0,126),'''',''''''); SET @object_oldname = REPLACE(REPLACE(@object_oldname,']',']]'), '''', ''''''); EXEC ('sp_rename N''[dbo].['+@object_oldname+']'', N'''+@object_newname+''', ''OBJECT'' '); FETCH c INTO @object_oldname END CLOSE c DEALLOCATE c SET @table_oldname = REPLACE(REPLACE(@table_oldname,']',']]'), '''', ''''''); SET @table_newname = REPLACE(@table_newname,'''',''''''); EXEC ('sp_rename N''[dbo].['+@table_oldname+']'', N'''+@table_newname+''', ''OBJECT'' '); END
118 views




