2010-08-19 33 views
5

如何自動運行來自給定文件夾的所有SQL腳本的過程?執行SQL Server腳本

+0

操作系統?腳本的數量?任何潛在的衝突或運行訂單要求?你想多久運行一次?一些細節將有助於回答你的問題。 – 2010-08-19 15:28:27

回答

10

編寫一個Windows腳本,使用FOR構造來遍歷文件並使用SQLCMD實用程序來執行每個文件。

for %f in (c:\MySQLScripts\*.sql) do sqlcmd -i %f 
1

您可以使用SQL Server附帶的sqlcmd命令行工具運行SQL腳本文件。語法是這樣的:

sqlcmd -i c:\MyScript.sql 

因此,基本上,你只需要找到您的文件夾中的所有文件,依次通過他們,並執行SQLCMD爲每一個,如上所示。

1

我創建了下面的腳本爲我的項目之一:

SET NOCOUNT ON 

EXEC master.dbo.sp_configure 'show advanced options', 1 
RECONFIGURE 
EXEC master.dbo.sp_configure 'xp_cmdshell', 1 
RECONFIGURE 

--Create the Folder- en filetables. 
DECLARE @SQLFolders TABLE (SQLFolderName VARCHAR(MAX)) 
DECLARE @SQLFiles TABLE (SQLFileName VARCHAR(MAX)) 
DECLARE @MainFolder VARCHAR(MAX) 
DECLARE @FileName VARCHAR(MAX) 
DECLARE @FolderName VARCHAR(MAX) 
DECLARE @SQLStatement VARCHAR(2000) 

SET @MainFolder = 'C:\ProjectName\' 

--Fill the foldertable and loop through them. 
INSERT INTO @SQLFolders VALUES ('CreateScripts\') 
INSERT INTO @SQLFolders VALUES ('ChangeScripts\') 

DECLARE cFolders CURSOR LOCAL FOR 
    SELECT [SQLFolderName] 
    FROM @SQLFolders 
OPEN cFolders 
FETCH NEXT FROM cFolders INTO @FolderName 
WHILE @@FETCH_STATUS = 0 
BEGIN 
    --Fill the file-table and loop through. 
    SET @SQLStatement = 'dir /b "' + @MainFolder + @FolderName + '*.sql"' 
    INSERT INTO @SQLFiles 
    EXECUTE master.dbo.xp_cmdshell @SQLStatement 

    DECLARE cFiles CURSOR LOCAL FOR 
     SELECT DISTINCT [SQLFileName] 
     FROM @SQLFiles 
     WHERE [SQLFileName] IS NOT NULL AND 
       [SQLFileName] != 'NULL' AND 
       [SQLFileName] != 'File Not Found' 
     ORDER BY [SQLFileName] 
    OPEN cFiles 
    FETCH NEXT FROM cFiles INTO @FileName 
    WHILE @@FETCH_STATUS = 0 
    BEGIN 
     SET @SQLStatement = 'SQLCMD -d hantisdb -i' + @MainFolder + @FolderName + @FileName 
     EXECUTE master.dbo.xp_cmdshell @SQLStatement 

     FETCH NEXT FROM cFiles INTO @FileName 
    END 

    DELETE FROM @SQLFiles 

    CLOSE cFiles 
    DEALLOCATE cFiles 
    FETCH NEXT FROM cFolders INTO @FolderName 
END 

CLOSE cFolders 
DEALLOCATE cFolders 
GO 

EXEC master.dbo.sp_configure 'xp_cmdshell', 0 
RECONFIGURE 
EXEC master.dbo.sp_configure 'show advanced options', 0 
RECONFIGURE 

SET NOCOUNT OFF 

我使用它來重新創建我的數據庫和一個全新的數據庫每天啓動。 請注意,它將以alfabetical順序執行文件!