1

Let's say I have some update script:

update sometable set somecolumn = 'somevalue' where xyz = 0

Now let's say I have multiple databases, like DB1, DB2, DB3 and so on. How could I run this script on all of them without doing it manually?

Thanks :)

0

2 Answers 2

2

You can do this using cursor

  • get list of all server in your lan or in network

  • create cursor for that

  • Than make use of sp_executesql to run you update script with forpart query

    set ANSI_NULLS ON
    set QUOTED_IDENTIFIER ON
    GO
    
    CREATE PROCEDURE [sp_cross_db_query]
    @SQLQuery varchar(400)
    AS
    
    DECLARE @DB_Name varchar(100)
    DECLARE database_cursor CURSOR FOR 
    
    SELECT DatabaseName 
    FROM Management.dbo.Customers
    
    OPEN database_cursor
    
    FETCH NEXT FROM database_cursor INTO @DB_Name
    
    WHILE @@FETCH_STATUS = 0 
    BEGIN 
        exec(
            'USE [' + @DB_Name + '];' +
            @SQLQuery
            )
           FETCH NEXT FROM database_cursor INTO @DB_Name 
    END
    CLOSE database_cursor 
    DEALLOCATE database_cursor
    

    to run the query

      exec sp_cross_db_query 'SELECT count(*) FROM Products'
    
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, can u give me some SQL please?
Thanks, FROM Management.dbo.Customers is causing some trouble...whats wrong?
The answer assumes you have a table that contains a list of databases, I think
SELECT [name] FROM master.dbo.sysdatabases did the trick, thanks!
1

If you wanted all databases, you can use sp_MSforeachdb:

http://www.databasejournal.com/features/mssql/article.php/3441031/SQL-Server-Undocumented-Stored-Procedures-spMSforeachtable-and-spMSforeachdb.htm

EXEC sp_MSforeachdb @command1="UPDATE ?..sometable SET somecolumn='somevalue' WHERE xyz=0"

Or for specific databases, you could try some of the logic as seen here:

http://www.sqlservercurry.com/2009/04/6-common-uses-of-undocumented-stored.html

Hope that helps.

1 Comment

Undocumented stored procedures are not recommended for use in anything but ad hoc scenarios because they are subject to change or even deletion at any time. You can always roll your own pretty easily though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.