0

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!

4

1 回答 1

0

如下更新您的代码,应该可以解决问题:

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

简单的测试......运行这个,它会告诉你所有的数据库都像'%a%':

exec sp_msForEachDB 'use [?];
                    if ''?'' like ''%a%''
                    begin
                        select ''? is like a''
                    end
                    else
                    begin
                        select ''? is not like a''
                    end'
于 2014-06-18T20:45:56.197 回答