创建执行SQL脚本的bat文件

时间:2012-05-24 12:29:10

标签: sql batch-file automation

我有一个文件夹,每个每周冲刺后会有许多MSQL脚本被放入其中。例如,今天在文件夹中放置了10个脚本。然后我必须单独打开每个脚本并针对适用的数据库运行它。需要运行的数据库位于文件名中。 例如[2] [CRMdata] UpdateProc.sql

[2]表示运行它的顺序,因此脚本[1]需要在它之前运行。 [CRMdata]是我必须运行它的数据库。

这个过程非常烦人,特别是如果要按顺序运行50个脚本。 我想知道是否有更简单的方法来做到这一点? Perhpas一个.bat文件,它读取文件名,并根据脚本编号顺序执行脚本,并根据文件名中指定的数据库执行脚本。

非常感谢任何帮助。 感谢。

2 个答案:

答案 0 :(得分:0)

首先,当您需要运行时,请考虑使用SQL Server作业代理。这是安排简单事情的好方法。

对于像这样的任务,我建议将PowerShell与“sqlcmd”结合使用。此命令实际上是您的问题的答案,因为它将从命令行运行脚本。

然而,更进一步。安排一个每周运行一次的工作(或者每当你想要它运行时)。它包含一个步骤,一个PowerShell脚本。然后,它可以循环遍历目录中的所有脚本,从名称中提取文件名,并使用sqlcmd运行脚本。在此过程中,还要记录您在表格中所做的事情,以便发现错误。

答案 1 :(得分:0)

我对使用MSQL执行SQL一无所知。您将不得不使用为MSQL提供的任何命令行实用程序来确定如何针对正确的数据库运行每个脚本。

我可以帮助您使用批处理文件,该文件将按照正确的顺序对SQL文件进行排序,并解析出数据库的名称。

如果序列号为零,则前缀为恒定宽度,则批处理更容易。我假设可以重命名文件,这就是这个解决方案的作用。

我还假设您永远不会有超过999个文件需要处理。可以轻松修改代码以处理更多内容。

如果任何文件名包含!字符,则必须进行一些更改,因为延迟扩展会破坏FOR变量的扩展。但这是一个不太可能的问题。

@echo off
setlocal enableDelayedExpansion

:: Change the definition to point to the folder that contains the scripts
set "folder=sqlCodeFolder"

:: The mask will only match the pattern that you indicated in your question
set "mask=[*] [*]*.sql"

:: Rename the .sql files so that the sequence numbers are zero prefixed
:: to width of 3. This enables the default alpha sort of the directory to be
:: in the proper sequence
for /f "tokens=1* delims=[]" %%A in ('dir /b "%folder%\%mask%"') do (
  set seq=00%%A
  ren "%folder%\[%%A]%%B" "[!seq:~-3!]%%B"
)

::Process the renamed files in order
for %%F in ("%folder%\%mask%") do (
  for /f "tokens=2 delims=[] " %%D in ("%%~nF") do (
    rem %%F contains the full path to the sql file
    rem %%D contains the name of the database, without enclosing []
    rem Replace the echo line below with the proper command to run your script
    echo run %%F against database [%%D]
  )
)
相关问题