views:

59

answers:

4

How can I automate process of running all SQL scripts from given folder ?

+1  A: 

You can run an SQL script file with the sqlcmd command line tool that comes with SQL Server. The syntax is like this:

sqlcmd -i c:\MyScript.sql

So basically, you just need to find all files in your folder, loop through them and execute sqlcmd for each one, like shown above.

haarrrgh
+2  A: 

Write a Windows script, use the FOR construct to loop through your files and use the SQLCMD utility to execute each file.

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

You can also use powershell to execute scripts in a given folder. http://sqlblogcasts.com/blogs/martinbell/archive/2009/07/30/Executing-all-.SQL-files-in-a-directory-with-Powershell.aspx Jay

A: 

I have created the following script for one of my projects:

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

I use this to recreate my database and start with a fresh database everyday. Mind you that it will execute the files in alfabetical order!

Geert Immerzeel