如何自动运行从给定文件夹运行所有SQL脚本的过程?
答案 0 :(得分:10)
答案 1 :(得分:1)
您可以使用SQL Server附带的 sqlcmd 命令行工具运行SQL脚本文件。语法如下:
sqlcmd -i c:\MyScript.sql
所以基本上,您只需找到文件夹中的所有文件,循环浏览它们并为每个文件执行 sqlcmd ,如上所示。
答案 2 :(得分: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顺序执行文件!
答案 3 :(得分:0)
您还可以使用powershell执行给定文件夹中的脚本。 http://sqlblogcasts.com/blogs/martinbell/archive/2009/07/30/Executing-all-.SQL-files-in-a-directory-with-Powershell.aspx 杰