如何构造包含Excel单元格值的SELECT语句?

时间:2016-04-25 15:38:30

标签: excel postgresql parameter-passing excel-2013 powerquery

我通过Excel查询带有电源查询的外部数据库。我想要做的是根据单元格值填充我的where子句,例如我的sql语句将读取类似

的内容
Select *
From employees
where hiredate between Sheet1!A1 and Sheet2!A2

我尝试了上面的语法并且它不起作用,但我认为它说明了我想要实现的目标。

如何将Excel表格中的参数传递给我的电源查询语法?

修改
我试过关注blog.oraylis.de(不是实际的链接,链接在评论中),但是当我尝试执行我的陈述时出现以下错误

  

DataSource.Error ODBC:错误[4203]错误:列" start_p"不存在;

我创建了一个名为it的参数表添加了标题&值和我尝试运行的完整SQL是:

let
startp_Param = Excel.CurrentWorkbook(){[Name="Parameter"]}[Content],
startp_Value = startp_Param {0}[Value],
endp_Param = Excel.CurrentWorkbook(){[Name="Parameter"]}[Content],
endp_Value = endp_Param {1}[Value],
Source = Odbc.Query("dsn=postgresql", "Select * FROM employees where hiredate BETWEEN startp_Value AND endp_Value")
in
Source

编辑#2
我将查询改为像这样读取

"Select * 
FROM employees 
where hiredate BETWEEN " & startp_Value & " AND " & endp_Value

但是现在出现了错误:

"We cannot apply operator & to types Text and Number" 

1 个答案:

答案 0 :(得分:0)

startp_Value和endp_Value是Power Query中的步骤,因此您必须使用&将它添加到字符串中,如下所示:

sessionInfo() R version 3.2.3 (2015-12-10) Platform: x86_64-redhat-linux-gnu (64-bit) Running under: CentOS release 6.7 (Final) gbm_2.1.1 caret_6.0-68 mlbench_2.1-1

这不会处理您的SQL查询的清理,因此您可能希望对startp_Value和endp_Value执行此操作(例如,通过转换为Date然后再转换为Text)。