sqlsql-serverstored-proceduressp-msforeachdb

Running a Stored Procedure on All Databases, and Saving All Results Into A Table


I'm trying to create a query in which I cycle through all the databases in a server, run a stored procedure on it, and save it to a results table.

This is what I have thus far:

CREATE table results (Severity INT, PurchaseOrderNumber INT,
                      PurchaseOrderLineNumber SMALLINT, ShipmentNumber SMALLINT,
                      ErrorCode int, ErrorText VARCHAR(256), DateCreated datetime)

EXECUTE sp_msForEachDB '
    IF "?" LIKE "VIS%"
        BEGIN
            USE "?"
            INSERT INTO results EXECUTE IC_PURCHASEORDER
        END
    '
SELECT * FROM results

DROP TABLE results

What I'm hoping to accomplish from this code is to run the IC_PURCHASEORDER stored procedure over all of the databases in the server, and record the result of that into the created results table. After that, I would be able to e-mail those results off to a supervisor, and then drop the table, but that's a job for another day. I know there exists a syntax error in the IF statement, that results in the following error

Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '{insert database name here}'.

Would it be possible to get some insight to what I'm trying to accomplish? Thanks!


Solution

  • Update your code as follows, should do the trick:

    CREATE table results (Severity INT, PurchaseOrderNumber INT,
                              PurchaseOrderLineNumber SMALLINT, ShipmentNumber SMALLINT,
                              ErrorCode int, ErrorText VARCHAR(256), DateCreated datetime)
    
        exec sp_msForEachDB 'use [?];
                        if ''?'' like ''vis%''
                        begin
                            if object_id(''IC_PURCHASEORDER'') is not null
                            begin
                                 INSERT INTO results EXECUTE IC_PURCHASEORDER
                            end
                            else
                            begin
                                 print ''missing proc in ?''
                            end
                        end'
    
        SELECT * FROM results
    
        DROP TABLE results
    

    Simple test... run this, it will tell you all db's like '%a%':

    exec sp_msForEachDB 'use [?];
                        if ''?'' like ''%a%''
                        begin
                            select ''? is like a''
                        end
                        else
                        begin
                            select ''? is not like a''
                        end'