从参数/变量动态创建视图SQL SSIS

时间:2017-07-07 01:16:17

标签: sql-server ssis

我有一个包含不到一百万行的表。我使用SSIS构建表单,询问用户输入并使用值作为参数从源数据构建视图。我无法通过SSIS从变量创建视图。

这个'工具的目的'是提供一个对话,以编程方式构建一个视图,然后根据通过将执行SSIS包的表单定义的参数更新语句。我团队中的一些人都知道0 SQL。因此,这规避了任何SQL知识。创建一个完全独立的应用程序并不理想,因为它需要额外的额外开销,并且会偏离目前使用SSIS / SQL以获得类似结果的许多现有流程。

这就是我尝试过的尝试。

我有一个包含'执行SQL任务'

的SSIS包

此任务会显示一个包含5个输入(变量)的表单 VAR1,VAR2,VAR3,VAR4,VAR5。 一些变量是字符串,其他是双打,整数等...(它们都有所不同)

您填充字段并点击确定。 这些变量将传递给执行包任务'。 在这个包内(包B) vars用于执行SQL任务'。

此任务尝试获取用户输入并使用包含4个其他变量的where子句创建视图。

示例:

Create View ? AS Select col1,col2,col3,col4 WHERE
col1 = ?
AND col2 =?
AND col3 =?.........

首先看来用的是?在创建视图中无效。 错误是:

Error: 0x0 at Build_Query: Incorrect syntax near '@P1'.
Error: 0xC002F210 at Build_Query, Execute SQL Task: Executing the query "CREATE VIEW ? as Select * from S_t_equip_template
..." failed with the following error: "The batch could not be analyzed because of compile errors.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established

 correctly.
Task failed: Build_Query

如果我使用create view变量作为表达式并删除where语句的变量/参数,我可以创建视图没问题。 然而,一旦我将其添加回来,where语句就会抛出错误。我已经尝试将这些错误作为“执行SQL任务”中的表达式进行评估。但由于这些是各种类型我得到错误:

[Execute SQL Task] Error: Executing the query "
CREATE VIEW testing AS SELECT
P.label,P.uniq..." failed with the following error: "The metadata could not 
be determined because statement 'CREATE VIEW testingagain AS SELECT
P.label,P.uniqueid,C.label as Child_Label,C.uniqueid as Child_uni' does not 
support metadata discovery.". Possible failure reasons: Problems with the 
query, "ResultSet" property not set correctly, parameters not set correctly, 
or connection not established correctly.

不知道发生了什么。任何帮助将不胜感激

我已经搜索了错误并找到了一些信息,但其他用例非常不同,以至于难以理解其实际原因或其他解决方法。

AS要求(简化示例): 我创建了一个名为:View_Name

的包变量(数据类型字符串)

执行SQL任务:

CREATE VIEW @[User::View_Name] AS SELECT
* from table1 
where col1 = 100;

具体而言,我不喜欢在这里使用变量。 如果我设置了视图名称,则一切正常,直到:我转到包含变量的Where子句。

创建一个名为type(datatype int)的变量

我在我的sql任务中映射变量/参数

示例:

CREATE VIEW tempTable AS SELECT
    * from table1 
    where col1 = ?;

这不会起作用,同样的错误。

如果我尝试通过表达式或表达式执行上述操作,则会出现以下错误

[Execute SQL Task] Error: Executing the query "CREATE VIEW test_45678 AS SELECT P.label,P.uniquei..." failed with the following error: "Must declare the scalar variable "@".". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

通常不得不以这种方式评估变量。我猜我需要单独评估每一件作品并逐件构建表达。这很好,但非常低效且无法维护。

1 个答案:

答案 0 :(得分:0)

在尝试评估我的表情时,我有一些基本的误解。特别是语法问题,必须将每个变量转换为字符串。 我的SQL语句变量

ON C.pid = P.ID 
where
C.width >="+(DT_WSTR, 8)@[User::Width] +"-"+ (DT_WSTR, 8)@[User::Range]+........

最终表达式如下:

"Create View "+@[User::View_Name] + " AS SELECT " + @[User::SQLStatement]