如何创建将 运行 位于特定文件夹中的 T-SQL 查询列表的 SSIS 包?

How to create an SSIS Package that will run a list of T-SQL queries located in a specific folder?

我正在使用 SQL Server 2012,我需要创建一个 SSIS 包,它将 运行 来自特定文件夹的 T-SQL 查询列表。

我的 T-SQL 查询列表已命名为“01(查询名称)”。sql' 并且该文件夹包含 25 个查询的列表。我需要 运行 这些查询的任务 从查询“01...”开始到“25...”

这可以在 SSIS 包中创建吗?如果是,我应该使用哪个任务?

更新 1

我尝试了@Hadi建议的第一种方法,脚本任务抛出以下异常

Error: Exception has been thrown by the target of an invocation

我在 SSDT 中的任务截图

脚本任务VB代码

 <Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
 Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase

 Public Sub Main()

    Using sr As New IO.StreamReader(Dts.Variables("strFilename").Value.ToString)

        Dts.Variables("strQuery").Value = sr.ReadToEnd()
        sr.Close()

    End Using

    Dts.TaskResult = ScriptResults.Success
End Sub

End Class

变量

(1) 使用脚本任务 + 执行 SQL 任务

  1. 添加 Foreach 循环容器
  2. 选择类型 = 文件枚举器
  3. Select 包含 .sql 个文件的文件夹作为源目录
  4. Select Fully qualified 文件名选项
  5. 转到变量映射选项卡,将结果映射到变量 (新建一个例如:@[User::strFilename]
  6. 创建字符串类型的变量@[User::strQuery]
  7. 在 foreach 循环容器中添加脚本任务和 Select @[User::strFilename] 作为 ReadOnly 变量@[User::strQuery] 作为 读写变量
  8. 在脚本任务中编写以下代码(选择 Visual Basic 作为语言):

    Try
    
        Using sr as new IO.StreamReader(Dts.Variables("strFilename").Value.ToString)
    
            Dts.Variables("strQuery").Value = sr.ReadToEnd()
            sr.Close()
    
        End Using
    
        Dts.TaskResult = ScriptResults.Success
    
    Catch ex as exception
    
        Messagebox.Show(ex.Message)
        Dts.TaskResult = ScriptResults.Failure
    
    End Try
    
  9. 添加一个 Execute SQL Task 链接到 Script Task 和 Select ConnectionString 属性,然后选择 SQLSource Type 属性 = Variable

  10. Select @[User::strQuery] 作为 SourceVariable

(2) 使用执行进程任务

使用 foreach 循环容器循环遍历这些文件,然后使用 Execute process task 到 运行 这些使用 SQLCMD.

的查询

附加信息:


(3) 使用批处理文件

您也可以在没有 SSIS 的情况下实现这一点,只需使用您用记事本创建的批处理文件 .BAT

  • Run all SQL files in a directory

我给哈迪投了赞成票,因为我学到了一些新东西。

但这就是我处理脚本任务的方式。经销商选择。

//Read SQL to string
System.IO.StreamReader sr = new System.IO.StreamReader(Dts.Variables["ForEachFilePathName"].Value);
string sql = sr.ReadToEnd();
sr.Close();

string cstr = Dts.Variables["connString"].Value;
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(cstr))
{
   System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, conn);

     conn.Open();
     cmd.ExecuteNonQuery();
}