[英]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. 我希望通过此代码完成的工作是在服务器中的所有数据库上运行IC_PURCHASEORDER存储过程,并将其结果记录到创建的结果表中。 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
我知道IF语句中存在语法错误,这导致以下错误
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!
谢谢!
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%': 简单测试...运行此命令,它将告诉您所有数据库,例如'%a%':
exec sp_msForEachDB 'use [?];
if ''?'' like ''%a%''
begin
select ''? is like a''
end
else
begin
select ''? is not like a''
end'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.