In SQL server is there any way to get the 'use database' command to accept a variable

前端 未结 4 762
醉酒成梦
醉酒成梦 2020-12-17 22:37

I would like to write a \'generic\' script to operate on a number of databases. The \'use databasename\' commands will be distributed in the body of the script. I would rath

4条回答
  •  [愿得一人]
    2020-12-17 23:11

    Ed already mentioned SQLCMD, a very good choice for scripting.

    If that doesn't do it for you, and you have sa rights on the server, and you don't mind the risk of using undocumented features and modifying the master database, you might look into user-defined system stored procedures.

    A user-defined system stored procedure (UDSSP) is created in the master database, prefixed with "sp_", and marked as a system object with the undocumented system proc sp_MS_marksystemobject (SQL2005).

    It takes its database context from the current connection, or a three-part name if so called.

    Sample invocation:

    declare @db sysname
    declare @sql nvarchar(max)
    set @db = 'yourdatabase'
    set @sql = 'exec '+quotename(@db)+'..sp_@yourproc'
    exec (@sql)
    

    Notes:

    1. If you go this route, I strongly suggest using a unique prefix that sorts toward the top, like sp_@yourproc, rather than sp_yourproc, so you can find them again later, and other people know that they are something special.

    2. Once the procedure is marked as system, it can't be updated. To make changes, you must drop, recreate and remark as system.

    3. Don't do this unless you know what you are doing and have done a little more research. Don't do this if you are risk-averse. Don't do this if you don't have a development instance to test on first.

    4. Backup the UDSSPs to file or CSV. A server upgrade can wipe them out.

提交回复
热议问题