Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change database within a stored procedure

Status
Not open for further replies.

Mirrorball

IS-IT--Management
Sep 24, 2002
2
GB
I have an update stored procedure which needs to be run over 40 identical databases on the same server. Is it possible to include a command in the update stored procedure to change from one database to another?

Thanks for your help
 
USE
Changes the database context to the specified database.

Syntax
USE { database }

Arguments
database

Is the name of the database to which the user context is switched. Database names must conform to the rules for identifiers.
 
Hi Mirrorball,
You can do updates without changing the database. The trick is to prefix the table you want to update with the database name.
e.g.
Update databasename..TableName set ColumnName = ColumnValue where condition

-Mukund.

 
The Use Database statement DOES NOT work within a stored procedure.

Mukund is correct. You can use the database name in the SQL statement, but this could require 40 statements and I assume you want to execute the same statment 40 times. You can overcome this with dynamic SQL.

Another alternative is to utilize the undocumented stored procedure named sp_MSforeachdb that will execute statements within the context of each database. Here is an example.

Declare @sql varchar(1000)
Set @sql = 'If Exists (Select * From ?.dbo.sysobjects Where type=''U'' and name=''MyTable'' and uid=1) ; Update ?.dbo.MyTable Set col1 = 0 Where col2<100'

exec sp_msforeachdb @command1 = @sql

Hopefully, I've got the correct syntax. Check out this SP and others at ...

Terry L. Broadbent - DBA
Computing Links:
faq183-874 contains &quot;Suggestions for Getting Quick and Appropriate Answers&quot; to your questions.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top