[英]Running a Stored Procedure on All Databases, and Saving All Results Into A Table
我試圖創建一個查詢,在其中循環瀏覽服務器中的所有數據庫,在服務器上運行存儲過程,然后將其保存到結果表中。
到目前為止,這是我所擁有的:
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
我希望通過此代碼完成的工作是在服務器中的所有數據庫上運行IC_PURCHASEORDER存儲過程,並將其結果記錄到創建的結果表中。 之后,我可以將這些結果通過電子郵件發送給主管,然后放下桌子,但這又是一天的工作。 我知道IF語句中存在語法錯誤,這導致以下錯誤
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '{insert database name here}'.
是否可以對我要完成的工作有所了解? 謝謝!
如下更新您的代碼,應該做到這一點:
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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.