posted 7/3/2011 by Raghav Khunger
Yesterday a person asked me on the forums on how to rename a table in SQL Server. I told him the script sp_rename oldname,newname to do the same. I decided to write a short blog on the same to show with some scripts:Let's create a dummy table and insert some data in it:
GO CREATE TABLE [MyTable] ([ID] INT IDENTITY,[Name] NVARCHAR(20)) GO INSERT INTO dbo.MyTable ( Name ) SELECT 'ABC' UNION SELECT 'DEF' UNION SELECT 'GHI' UNION SELECT 'JKL' GO
Now let's Rename the table:
--RENAME THE TABLE sys.sp_rename 'MyTable','MyTable2' --OUTPUT --Caution: Changing any part of an object name could break scripts and stored procedures.
Above we changed the name of our table from "MyTable" to MyTable2". You will see a Caution in Results Pane of SSMS that "Changing any part of an object name could break scripts and stored procedures.", i.e you need to consider the fact that the old name which was reffered in SPs and other scripts has not been changed. Below is the output after running the select query on table with new name:
GO SELECT * FROM dbo.MyTable2 --OUTPUT --ID Name ------------- -------------------- --1 ABC --2 DEF --3 GHI --4 JKL
I hope the above script will help you.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18