Sql server 将动态参数传递给SQL

Sql server 将动态参数传递给SQL,sql-server,powerbi,Sql Server,Powerbi,我正在尝试在Excel中创建一个动态参数 我尝试过使用这个和这个,但我得到以下错误: “”查询中出现错误。表达式。错误:我们找不到 名为“Parameters”的Excel表 我的参数表如下所示,该表也称为参数: 我的参数代码如下: (ParameterName as text) => let ParamSource = Excel.CurrentWorkbook(){[Name="Parameters"]}[Content], ParamRow = Table.SelectRows(P

我正在尝试在Excel中创建一个动态参数

我尝试过使用这个和这个,但我得到以下错误:

“”查询中出现错误。表达式。错误:我们找不到 名为“Parameters”的Excel表

我的参数表如下所示,该表也称为参数:

我的参数代码如下:

(ParameterName as text) =>
let
ParamSource = Excel.CurrentWorkbook(){[Name="Parameters"]}[Content],
ParamRow = Table.SelectRows(ParamSource, each ([Parameter] = ParameterName)),
Value=
if Table.IsEmpty(ParamRow)=true
then null
else Record.Field(ParamRow{0},"Value")
in
Value
let
//Pull in a values from the parameter table
SQL_Instance = fnGetParameter("SQL Instance"),
dbName = fnGetParameter("Database Name"),
dbTable = fnGetParameter("Database Table"),
sFilterField = fnGetParameter("Filter Field"),
sFieldValue = Text.From(fnGetParameter("Field Value")),

//Create the query
dbQuery = "Select * FROM " & dbTable & " WHERE " & sFilterField & "='" & sFieldValue & "'",

//Get the data
Source = Sql.Database(SQL_Instance,dbName,[Query=dbQuery])
in
Source
我的SQL查询如下:

(ParameterName as text) =>
let
ParamSource = Excel.CurrentWorkbook(){[Name="Parameters"]}[Content],
ParamRow = Table.SelectRows(ParamSource, each ([Parameter] = ParameterName)),
Value=
if Table.IsEmpty(ParamRow)=true
then null
else Record.Field(ParamRow{0},"Value")
in
Value
let
//Pull in a values from the parameter table
SQL_Instance = fnGetParameter("SQL Instance"),
dbName = fnGetParameter("Database Name"),
dbTable = fnGetParameter("Database Table"),
sFilterField = fnGetParameter("Filter Field"),
sFieldValue = Text.From(fnGetParameter("Field Value")),

//Create the query
dbQuery = "Select * FROM " & dbTable & " WHERE " & sFilterField & "='" & sFieldValue & "'",

//Get the data
Source = Sql.Database(SQL_Instance,dbName,[Query=dbQuery])
in
Source

如何在不接收错误的情况下使其工作?

您不能在SQL中参数化对象;您必须安全地注入其值。您很可能希望创建一个SP来执行此操作,但所需的SQL将遵循以下原则:

DECLARE @DBTable sysname,
        @FilterField sysname,
        @FilterValue varchar(50); --choose an appropriate data type here

DECLARE @SQL nvarchar(MAX);

SET @SQL = N'SELECT * FROM dbo.' + QUOTENAME(@DBTAble) + N' WHERE ' + QUOTENAME(@FilterField) + N' = @FilterValue;';

EXEC sp_executesql @SQL, N'@FilterValue varchar(50)', @FilterValue; --again, choose an appropriate data type for @FilterValue

请注意使用
QUOTENAME
安全地注入动态对象的值,同时将
@FilterValue
作为参数传递,而不是将其注入到动态语句中。

您看到的特定错误表明Excel中的参数表未命名为“参数”。Excel中的表表示为特殊命名范围。您可以通过以下方式编辑表的名称:

  • 选择表中的任意单元格
  • 导航到“表格设计”功能区菜单
  • 编辑功能区最左侧的表名
  • 请注意关于通过字符串连接构建SQL语句的一般坏主意的其他答案——这是一个真正的问题


    谢谢!找不到那个!