SSIS:如何将 SQL 语句从文件中提取到字符串变量中? [英] SSIS: How do I pull a SQL statement from a file into a string variable?

查看:26
本文介绍了SSIS:如何将 SQL 语句从文件中提取到字符串变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本文件中存储了一些 SQL 语句.如何将这些文件拉入 SSIS 中的字符串变量中,以便我可以在多个地方使用相同的查询?

I have a few SQL statements stored in text files. How do I pull these files into a string variable in SSIS so that I can use the same query in multiple places?

回答问题:

查询又长又复杂,我更喜欢在真正的文本编辑器中进行编辑,而不是在 SSIS 文本框中进行编辑.我还希望无法访问 SSIS 或不知道如何使用它的人可以编辑查询.最后,每个查询都用于许多不同的数据流.如果我错了,请纠正我,但如果我在多个位置使用相同的查询,我相信我必须使用变量或为每个数据流重新编写代码.

The queries are long and complex, something I'd prefer to edit in a real text editor, not inside the SSIS text boxes. I'd also like the queries to be editable by people who don't have access to SSIS or don't know how to use it. Finally, each of the queries is used in a number of different data flows. Correct me if I'm wrong, but if I use the same query in multiple spots I believe I have to either use a variable or re-write the code for each data flow.

推荐答案

这就是我做这件事的方法(在到处寻找答案但没有找到.)

Here's how I did this very thing (after searching everywhere for an answer and finding none.)

我从导出数据向导创建的包开始,所以我的说明与此相关.这样做会设置列映射.如果您没有使用导出向导来创建包,您可能需要手动添加列.

I started with a package that the Export Data Wizard created, so my instructions relate to that. Doing it that way sets up the column mappings. If you didn't use the Export Wizard to create the package you may have to add columns by hand.

  1. 将名为 SQLFileName 的字符串变量添加到包中.
  2. 将名为 SQLCommand 的字符串变量添加到包中.
  3. 在控制流开始时添加脚本任务.
  4. 编辑脚本任务并转到脚本部分.
  5. 将 SQLFileName 添加到 ReadOnlyVariables 部分.将其设置为.sql 文件的路径.
  6. 将 SQLCommand 添加到 ReadWriteVariables 部分.
  7. 点击设计脚本.
  8. 粘贴下面的脚本.它只是读入内容SqlFileName 指定的文件写入SQL 命令.
  9. 确定退出,将脚本任务连接到控制流的其余部分.
  10. 转到您的数据流并选择源查询.你需要使用编辑属性属性窗口.如果您使用花哨的编辑窗口,你会得到一个关于命令文本的错误不是正在设置.这是因为 SQLCommand在设计时为空白.
  11. 将 AccessMode 从变量更改为 SQL 命令.
  12. 在 SQLVariableName 下,选择 SQLCommand.
  13. 您会看到一个红色的 X 被添加到源查询中.那是因为 SQLCommand 是空白的.到防止红X,改变验证ExternalMetaData 为假.

就是这样.我希望我记得所有的点点滴滴.脚本是关键部分,您可以将 SQL 放入变量中,然后在数据流中使用该变量.

That's about it. I hope I remembered all the bits. The script is the key part so that you can get the SQL into a variable and then use the variable in the Data Flow.

   Imports System
    Imports System.IO
    Imports Microsoft.SqlServer.Dts.Runtime

    Public Class ScriptMain

        Public Sub Main()

            Try

                Dts.Variables("SQLCommand").Value = System.IO.File.ReadAllText(Dts.Variables("SQLFileName").Value.ToString)

                Dts.TaskResult = Dts.Results.Success

            Catch oException As System.Exception

                Dts.TaskResult = Dts.Results.Failure

            End Try

        End Sub

    End Class

这篇关于SSIS:如何将 SQL 语句从文件中提取到字符串变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆