Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ALTER current database without using its name

Tags:

I need to run update script on current database (ALTER DATABASE...), but can't use implicit its name. Is possible to use some function to get current db name and use inside ALTER DATABASE (Sql Server 2005 and above) ? I tried use db_name(), but doesn't work.

select db_name(); works

ALTER DATABASE db_name() ... doesn't work

like image 424
marioosh Avatar asked Jan 11 '13 10:01

marioosh


People also ask

Can we alter database?

Overview: SQL Server Adds or removes files and filegroups from a database, changes the attributes of a database or its files and filegroups, changes the database collation, and sets database options. Database snapshots cannot be modified.

How do you rename a database?

In Object Explorer, expand Databases, right-click the database to rename, and then select Rename. If the database was your default database, see Reset your default database after rename. Refresh the database list in Object Explorer.


2 Answers

Actually something more like this is probably a little better if you're altering the current database:

ALTER DATABASE CURRENT SET COMPATIBILITY_LEVEL = 90

like image 134
Russ B Avatar answered Sep 18 '22 13:09

Russ B


You need to use something like

declare @dbname varchar(100) set @dbname=quotename(db_name()) exec('alter database '+@dbname+' ...'); 

or.. even simpler

set @sql='alter database '+quotename(db_name())+' ...'; exec(@sql) 
like image 26
Rich S Avatar answered Sep 21 '22 13:09

Rich S