如何使用Power Query M将Excel表的列值提取到SQL WHERE子句中?

我有一个Excel表,最终用户在其中向“ RefNum”列输入参考号。我还创建了一个带有公式的“ RefNum_SQL”列,该公式会自动为WHERE子句用逗号和括号格式化列表,以防使SQL / M部分变得更容易。我们将此表称为“输入”表:

RefNum  RefNum_Formatted
2123    (2123,2456    2456,2789    2789)

然后我有一个SQL查询,该查询将附加到这些参考编号的其他详细信息拉入Excel工作簿的另一张纸上的表中。

SELECT RefNum,LocationID,ShipDate
FROM database.dbo.Products (NOLOCK)
WHERE RefNum IN (2123,2456,2789)

然后将查询结果加载到工作簿中另一张表上的表中,我们将其称为“输出”表:

RefNum  LocationID  ShipDate
2123    13321       12/3/2019
2456    16654       5/17/2019
2789    19987       8/24/2019

Power Query M代码是否可以将RefNum列中的值直接拉到SQL查询的WHERE子句中,以便最终用户不必在列表更改时在高级编辑器中手动调整查询? / strong>


这是根据到目前为止我发现的资源尝试的代码:

let
  Source = Sql.Database("server","database")
  RefNum_Formatted = table.Column(Input,RefNum_Formatted)
  Output = Value.NativeQuery( Source,"SELECT RefNum,ShipDate
     FROM database.dbo.Products (NOLOCK)
     WHERE RefNum = @RefNum_Formatted")
in
  Output

尝试运行上述M代码时,出现以下错误:

DataSource.Error:microsoft SQL:必须声明标量变量“ @RefNum_Formatted”。

我确实了解到,正如目前所写的那样,Power Query希望@RefNum_Formatted是SQL中声明的变量,而不是Excel表中的变量。但是,我无法弄清楚如何创建与“输入”表值的连接,可以使用M将其拉入查询中。


在下面的链接中提出了类似的问题,但我无法成功应用任何答案:

Power Query to Filter a SQL view based on an Excel column list

Using Excel Columns in SQL Query for Where Clause

https://techcommunity.microsoft.com/t5/excel/create-dynamic-power-query-sql-by-using-excel-table-column/m-p/211504

cafeblue 回答:如何使用Power Query M将Excel表的列值提取到SQL WHERE子句中?

这里有些错误的地方

  1. “ @ RefNum_Formatted”只是一个字符串,而不是对 上一步
  2. RefNum_Formatted步骤很可能是一个列表,而不是 比字符串

尝试此代码(您可能需要调整表格/列引用)

let
  Source = Sql.Database("server","database"),RefNum_Formatted = List.Accumulate(Input[RefNum_Formatted],"",(state,current) => state & current),//List.Accumulate converts list to string
  SQL_Code = "SELECT RefNum,LocationID,ShipDate
     FROM database.dbo.Products (NOLOCK)
     WHERE RefNum IN " & RefNum_Formatted,//that's how you pass a reference to a step,it cannot be done inside a string
  Output = Value.NativeQuery( Source,SQL_Code)
in
  Output

编辑:添加了源代码步骤

本文链接:https://www.f2er.com/2776043.html

大家都在问