ALTER current database without using its name

时间秒杀一切 提交于 2019-12-21 06:59:49

问题


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


回答1:


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)



回答2:


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

ALTER DATABASE CURRENT SET COMPATIBILITY_LEVEL = 90




回答3:


Try this

DECLARE @DBName sysname;
SET @DBName = (SELECT db_name());
DECLARE @SQL varchar(1000);
SET @SQL = 'ALTER DATABASE '+@DBName+' .......'

Raj



来源:https://stackoverflow.com/questions/14275935/alter-current-database-without-using-its-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!