Execute SQL Server scripts

2020-03-03 08:24发布

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

4条回答
够拽才男人
2楼-- · 2020-03-03 08:35

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.

查看更多
Summer. ? 凉城
3楼-- · 2020-03-03 08:41

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!

查看更多
乱世女痞
5楼-- · 2020-03-03 08:48

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
查看更多
登录 后发表回答