HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

SQL Server renaming table from another database

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
sqldatabaserenaminganotherserverfromtable

Problem

Is there a way in SQL Server to rename a table in another database? When you are in current database and migrating data over to another database in the TEMP table and then renaming TEMP table in that another database. I do not want to use "USE [database]" since the database name could change on different servers.

Thanks for the help in advance!

Solution

You should use dynamic sql to do this. Build a string and execute it. As long as you know the name of the destination database, everything should be fine.

use CurrentDB
declare @x varchar(1000), @otherDb sysname = 'NewDB';

set @x = 'use ' + @otherDB + '

EXEC sp_rename ''dbo.temp'', ''temp2''
'
exec (@x);
print @x;
GO

Code Snippets

use CurrentDB
declare @x varchar(1000), @otherDb sysname = 'NewDB';

set @x = 'use ' + @otherDB + '

EXEC sp_rename ''dbo.temp'', ''temp2''
'
exec (@x);
print @x;
GO

Context

StackExchange Database Administrators Q#739, answer score: 7

Revisions (0)

No revisions yet.