[英]Expression.Error when dynamically passing in Teradata SQL query (with column aliases) to ODBC query
I have a macro that prompts me for a SQL query (unless it was called by another Sub, in which case it uses the argument that was passed into its optional string parameter as the query) and then executes the query against my Teradata SQL database. 我有一个宏提示我进行SQL查询(除非它被另一个Sub调用,在这种情况下它使用传递给其可选字符串参数作为查询的参数),然后对我的Teradata SQL数据库执行查询。
It works fine, unless there's a column alias containing a space in the query. 它工作正常, 除非在查询中有一个包含空格的列别名。
Example query: SELECT 2 + 2 AS "Query Result";
查询示例:
SELECT 2 + 2 AS "Query Result";
Error: 错误:
Run-time error '1004':
[Expression.Error] The name 'Source' wasn't recognized. Make sure it's spelled correctly.
The line of code which I believe is the culprit is as follows (my apologies for the readability-- I recorded the macro, modified it just enough to get it to work somewhat dynamically and then haven't touched it since). 我认为是罪魁祸首的代码行如下(我为可读性道歉 - 我记录了宏,修改它只是为了让它在某种程度上动态地工作,然后就没有触及它)。
ActiveWorkbook.Queries.Add Name:=queryName, formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Odbc.Query(""dsn=my-server-name"", " & Chr(34) & code & Chr(34) & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
I assume it has to do with the fact that the example query above has double quotes for the alias, which are confusing the syntax when trying to be interpolated. 我假设它与以下事实有关:上面的示例查询具有别名的双引号,这在尝试插值时会混淆语法。 Any help would be greatly appreciated!
任何帮助将不胜感激!
Here's what the string for the formula
is set to in this line: 以下是此行中
formula
的字符串设置:
ActiveWorkbook.Queries.Add Name:=queryName, formula:=<string here>
after all the chr()
and concatenation are done: 在完成所有
chr()
和连接之后:
let
Source = Odbc.Query("dsn=my-server-name", "<code>")
in
Source
That token <code>
is replaced by whatever is in your variable code
. 该令牌
<code>
将替换为您的变量code
任何内容。 So I suspect you are correct in that this formula would need to have it's double quotes escaped fully. 所以我怀疑你是正确的,因为这个公式需要让它的双引号完全转义。
In other words this string you are building form Formula
is going to be evaluated as code itself, and even in that evaluation it will be passing more code (your SQL) onto the Teradata server to be evaluated there. 换句话说,这串你正在建设形式
Formula
将被评估为代码本身,甚至在评估将通过更多的代码(你的SQL)到Teradata的服务器那里进行评估。
You are in code inception. 你在代码开始。 VBA code writing powerquery code writing Teradata code.
VBA代码编写powerquery代码编写Teradata代码。
Understanding that and guessing a bit here, I'm thinking your current code
variable looks something like: 在这里理解并猜测一下,我认为你当前的
code
变量看起来像:
code="SELECT 2 + 2 AS ""Query Result"";"
Your double quotes are already escaped for VBA. 您的双引号已经为VBA转义。 BUT because you have to survive another round of eval in powerquery you need to escape once again.
但是因为你必须在powerquery的另一轮评估中存活下来,你需要再次逃脱。 Instead:
代替:
code="SELECT 2 + 2 AS """"Query Result"""";"
*I think... *我认为...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.