How to rename a table in SQL Server? - sql-server

The SQL query that I have used is :
ALTER TABLE oldtable RENAME TO newtable;
But, it gives me an error.
Server: Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'TO'.

To rename a table in SQL Server, use the sp_rename command:
exec sp_rename 'schema.old_table_name', 'new_table_name'

To rename a column:
sp_rename 'table_name.old_column_name', 'new_column_name' , 'COLUMN';
To rename a table:
sp_rename 'old_table_name','new_table_name';

Table Name
sp_rename 'db_name.old_table_name', 'new_table_name'
Column
sp_rename 'db_name.old_table_name.name', 'userName', 'COLUMN'
Index
sp_rename 'db_name.old_table_name.id', 'product_ID', 'INDEX'
also available for statics and datatypes

When using sp_rename which works like in above answers, check also which objects are affected after renaming, that reference that table, because you need to change those too
I took a code example for table dependencies at Pinal Dave's blog here
USE AdventureWorks
GO
SELECT
referencing_schema_name = SCHEMA_NAME(o.SCHEMA_ID),
referencing_object_name = o.name,
referencing_object_type_desc = o.type_desc,
referenced_schema_name,
referenced_object_name = referenced_entity_name,
referenced_object_type_desc = o1.type_desc,
referenced_server_name, referenced_database_name
--,sed.* -- Uncomment for all the columns
FROM
sys.sql_expression_dependencies sed
INNER JOIN
sys.objects o ON sed.referencing_id = o.[object_id]
LEFT OUTER JOIN
sys.objects o1 ON sed.referenced_id = o1.[object_id]
WHERE
referenced_entity_name = 'Customer'
So, all these dependent objects needs to be updated also
Or use some add-in if you can, some of them have feature to rename object, and all depend,ent objects too

If you try exec sp_rename and receieve a LockMatchID error then it might help to add a use [database] statement first:
I tried
exec sp_rename '[database_name].[dbo].[table_name]', 'new_table_name';
-- Invalid EXECUTE statement using object "Object", method "LockMatchID".
What I had to do to fix it was to rewrite it to:
use database_name
exec sp_rename '[dbo].[table_name]', 'new_table_name';

To change a table name with a different schema:
Example: Change dbo.MyTable1 to wrk.MyTable2
EXEC SP_RENAME 'dbo.MyTable1', 'MyTable2'
ALTER SCHEMA wrk TRANSFER dbo.MyTable2

Nothing worked from proposed here ..
So just pored the data into new table
SELECT *
INTO [acecodetable].['PSCLineReason']
FROM [acecodetable].['15_PSCLineReason'];
maybe will be useful for someone..
In my case it didn't recognize the new schema also the dbo was the owner..
UPDATE
EXECUTE sp_rename N'[acecodetable].[''TradeAgreementClaim'']', N'TradeAgreementClaim';
Worked for me.
I found it from the script generated automatically when updating the PK for one of the tables.
This way it recognized the new schema as well..

Related

Retrieve old sp name when i wrongly update the sp name

While selecting the sp name by using Rename, i wrongly press 's' and press tab. Then it is renamed wrongly. I don't know the Sp Name. How do i get the old sp name. Kindly suggest me.
From MSDN I found in sp_rename (Transact-SQL)
Renaming a stored procedure, function, view, or trigger will not
change the name of the corresponding object name in the definition
column of the sys.sql_modules catalog view. Therefore, we recommend
that sp_rename not be used to rename these object types. Instead, drop
and re-create the object with its new name.
I have tested the same and I got old object name.
GO
CREATE PROCEDURE PROC_MY_SP
AS
BEGIN
SELECT 1 AS COL
END
GO
SELECT OBJECT_ID('PROC_MY_SP') --789786071
GO
SELECT * FROM sys.sql_modules WHERE OBJECT_ID('PROC_MY_SP')= OBJECT_ID
GO
sp_rename 'PROC_MY_SP', 'PROC_YOUR_SP'
GO
SELECT OBJECT_ID('PROC_YOUR_SP') --789786071
--Changing the SP Name wont change the objectID
GO
SELECT definition,* FROM sys.sql_modules WHERE OBJECT_ID=789786071
--Or Simply pass your new sp name
SELECT definition, * FROM sys.sql_modules WHERE OBJECT_ID('PROC_YOUR_SP')= OBJECT_ID
Here the definition column showing the old sp name only.

change column name in table

How can I change my column in table?
I try these codes to change it but it doesnt work.
If I will run that it will result as an
'Either the parameter #objname is ambiguous or the claimed #objtype
(COLUMN) is wrong.'
Here is my code:
exec sp_rename 'EMPLOYEE.COMMISSION_PCT', 'COMMISSION', 'COLUMN'
SELECT * FROM EMPLOYEES
I've just tried here and work properly.
open another tab and try to do this way.
USE [YOUR DATABASE]
GO
exec sp_RENAME 'TABLE.Column', 'NewColumnName',
'COLUMN'
GO

Changing a table owner

I'm trying to change the owner of a table:
sp_changeobjectowner 'OWNER.TABLENAME', 'dbo'
But when executing I get the error message:
Msg 15001, Level 16, State 1, Procedure sp_changeobjectowner, Line 62
Object 'OWNER.TABLENAME' does not exist or is not a valid object for
this operation.
The correct way to do this in SQL Server 2005 and up is to stop thinking about the prefix as an "owner." The sp_changeobjectowner procedure has been deprecated since SQL Server 2005, and you should instead be using schema DDL, e.g.:
ALTER SCHEMA dbo TRANSFER [current_owner].tablename;
To check the current "owner" (this may return multiple rows if you have more than one tablename in multiple schemas):
SELECT s.name
FROM sys.schemas AS s
INNER JOIN sys.tables AS t
ON s.[schema_id] = t.[schema_id]
WHERE t.name = N'tablename';
Also be sure that you spell the object correctly. In a case-sensitive collation, for example, TABLENAME and tablename are not the same object, and spelling it with InCorrEcT CaSe could also lead to this error.
Your statement is correct:
EXEC sp_changeobjectowner '<owner>.<tableName>', '<newOwner>'
If the error happend, try to check who is the current owner of the table:
EXEC sp_table_privileges '<tableName>'
To cover the case where a table exists within a constructed schema name like 'Common' (that is not related to a username), then it is the schema owner that needs to be changed.
alter authorization on schema::Common TO dbo;
That will change the objects within the schema to the specified owner 'dbo' and keep the table within 'Common'.
To list schema owners:
select db_name() as Db,
sch.name as SchemaName,
u.Name as Owner
from sys.schemas sch
join sys.sysusers u
on u.uid = sch.principal_id;
SELECT 'Exec sp_changeobjectowner ''<CURRENTOWNER>.' + name + ''', ''dbo'' ' FROM sys.objects WHERE type IN ('U','P','V','FN')
Apply Following Steps
(1) Run Following Query on Sql Prompt
(2) Copy The Result and Paste Again to New Sql Query and Again Execute
This is Change owner of your Tables, Views, Stored Procedures and Functions
If dropping the table is an option, you can drop and recreate under the desired user. Just specify dbo in the create script. For example:
USE [X]
GO
/****** Object: Table [dbo].[TableName] Script Date: 4/21/2014 1:26:37 PM ******/
CREATE TABLE [dbo].[TableName](
[Field1] [bigint] NOT NULL,
[Field2] [nvarchar](50) NOT NULL,
[Field3] [datetime] NOT NULL
) ON [PRIMARY]
GO
run the following query
EXEC sp_changeobjectowner 'set here object name', 'set here new owner'
go

Rename column in SQL Server

I tried the following code. Although I don't get any errors, it did not do it.
SELECT * FROM Categories EXEC sp_rename 'Active', CategoriesActive
EXEC sp_rename 'Categories.Active', 'CategoriesActive', 'COLUMN'
FOR MSSQL :
EXEC sp_rename 'TABLENAME.OLD_COLUMNNAME', 'NEW_COLUMNAME', 'COLUMN';
FOR MYSQL : Use ALTER TABLE to do this
ALTER TABLE tbl_name CHANGE [COLUMN] old_col_name new_col_name
You can rename a column using a CHANGE old_col_name new_col_name column_definition clause. To do so, specify the old and new column names and the definition that the column currently has. For example, to rename an INTEGER column from a to b, you can do this:
ALTER TABLE t1 CHANGE a b INTEGER;
You don't need to use that select in front, and the syntax should be like:
EXEC sp_rename
#objname = 'Categories.Active',
#newname = 'CategoriesActive',
#objtype = 'Type_of_your_column'

Find a table across multiple databases SQL SERVER 2005

I exported a table to a server but I can't find the table. Maybe I didn't put the right destination database. How can I find this table if my server has multiple databases, without opening each one of them?
I use MS Sql Server Management Studio 2008.
Rough and dirty, but it would do the job.
-- Instructions. Replace "table_name_here" with actual table name
sp_MSforeachdb 'USE ?
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N''[table_name_here]'') AND OBJECTPROPERTY(id, N''IsUserTable'') = 1)
BEGIN
PRINT ''Found in db ?''
END'
One way
SELECT DISTINCT DB_NAME(database_id)
FROM [sys].[dm_db_index_operational_stats](NULL,NULL,NULL,NULL)
WHERE OBJECT_NAME(object_id,database_id) = 'table_name'
Or if you are reasonably confident it would be in the dbo schema in whichever database
SELECT name
FROM sys.databases
WHERE CASE
WHEN state_desc = 'ONLINE'
THEN OBJECT_ID(QUOTENAME(name) + '.[dbo].[table_name]', 'U')
END IS NOT NULL
Based off Martin Smith's answer above but generalised into a view to give a sort of cross-DB version of sys.tables -
CREATE VIEW ListTablesAllDBs
AS
SELECT
DB_NAME(database_id) as DBName,
OBJECT_SCHEMA_NAME(object_id,database_id) as SchemaName,
OBJECT_NAME(object_id,database_id) as TableName
FROM
[sys].[dm_db_index_operational_stats](NULL,NULL,NULL,NULL)
Now, if only I can work out a way to do the same for columns.......
EDIT - Ignore this, finding it sometimes misses tables altogether.
Minor clarification just to avoid headaches for those with 'SuperUsers' who don't know how to name DBs:
EXEC sp_MSForEachDB '
USE [?]
IF OBJECT_ID(''mytable'') IS NOT NULL AND
OBJECTPROPERTY(OBJECT_ID(''mytable''), ''IsTable'') = 1
PRINT ''Found here: ?'''
select 'select * from '+name+'.sys.tables where name=
''[yourtable]'';' from sys.databases
Instead of [yourtable], type the name of the missing table, and run the result again.
EXEC sp_MSForEachDB '
USE ?
IF OBJECT_ID(''mytable'') IS NOT NULL AND
OBJECTPROPERTY(OBJECT_ID(''mytable''), ''IsTable'') = 1
PRINT ''?''
'

Resources