开发者

Database name in .sql script

开发者 https://www.devze.com 2023-03-17 02:08 出处:网络
I need to execute the following statement ALTER DATABASE DatabaseName ... in my .sql script. But I want to keep my 开发者_Go百科script neutral to the specific database. So I want to make ALTER DATA

I need to execute the following statement

ALTER DATABASE DatabaseName ...

in my .sql script. But I want to keep my 开发者_Go百科script neutral to the specific database. So I want to make ALTER DATABASE work on the current database. I hoped DatabaseName is optional parameter, but according to documentation, it is not.


Database name is required and you cannot even put it in a parameter.

But you can use 'exec' instead

    declare @stmt varchar(max)
    set @stmt = 'alter database....'
    exec (@stmt)

It is not very elegant, but i believe it is the only way to do it


db_name() returns the current database, which you can then stuff into an EXEC statement

DECLARE @dbname sysname = db_name()

EXEC('ALTER DATABASE ' + @dbname + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE') 


Well,

This is one of the reasons why so many ORMs appeared for almost all the languages possible. To be sure you offer as much DB independence as possible, I recommend you to use one of them.


Can't you just use a scripting language to wrap this sql call? It would be much easier and cleaner.

You can accomplish this through a series of convoluted SQL commands. If you're using MySQL, an example of creating your own SQL statement using variables and CONCAT is shown here:

http://blog.mclaughlinsoftware.com/2011/01/19/prepared-statement-failure/

As it says in the article, for ALTER statements, you have to CONCAT the database name into the statement variable. You can then use other SQL commands to get the database name you want, like DATABASE().


EDIT: I retract my answer, the answers using EXEC are the right idea in this case.

Haven't need this in a while, but I believe you can use SELECT db_name() as a subquery, like so:

ALTER DATABASE (SELECT db_name()) ...

To run the relevant command on the current database, if that works for your use case.

0

精彩评论

暂无评论...
验证码 换一张
取 消