18

I am writing a sql script for sql server 2008 where I place a use statement at the beginning that specifies the database the script should be run against:

use [my_database]

As I have different environments where the same database exists, eg dev, qa, prod, is there any way I can specify in the script the environment the script is for, either by server name or ip address or by any other mechanism.

1
  • Did you ever find an answer for this question? Did @Filip De Vos's answer work for you? Commented Jun 19, 2013 at 21:29

3 Answers 3

32

You can put the SQL Management Studio in SQLCMD mode and specify the server with the :CONNECT myserver statement.

You can switch on command mode by clicking on the option in the pic below enter image description here

Your script would then look something like this

    :CONNECT devserver
    use [my_database]
    SELECT * FROM my_table

You can even make the query window switch servers during execution

    :CONNECT devserver
    use [my_database]
    SELECT * FROM my_table
    GO
    :CONNECT uatserver
    use [my_database]
    SELECT * FROM my_table

To connect with a specific user and password you can specify this as follows

    :CONNECT devserver -U myUser -P myPassword
    use [my_database]
    SELECT * FROM my_table

There are actually a number of options you can specify which are well documented on msdn.

Sign up to request clarification or add additional context in comments.

4 Comments

Is there any way to do this and specify a user name and password? I am getting a login failed error.
you can do :CONNECT devserver -U user -P password. I will add it to the answer once my updates stop erroring.
Thanks . Is there a way to do this within nested / multiple cte? (for me this was better as I was locked out from linked servers)
no, this is a client hack, you can not embed it in queries.
1

That's a CONNECTION setting, not a parameter within the script.

You can run the same script in different environments via batch file or powershell script if desired, or you could set up linked servers, but you can't just say

USE SomeOtherServer

There are security and networking implications as well.

Comments

0

Assuming you will run all of these scripts on a particular server - e.g. the Dev server - then you merely need to create a Linked Server to each of the other servers.

Then, for example, you could run an identically named stored procedure on each of these servers thusly:

EXEC MyDatabase.dbo.mysp_DoSomething --Dev Server; no server prefix needed since that's where we are
EXEC QA.MyDatabase.dbo.mysp_DoSomething --QA Server
EXEC Prod.MyDatabase.dbo.mysp_DoSomething --Prod server

etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.