查询在子查询中设置参数

时间:2015-08-27 13:50:55

标签: sql excel-2007 external

如何在Excel查询中添加参数?这种情况并不像现场?那么简单。查询是:

SELECT * FROM crm.dbo.Meetings mt
left outer join crm.dbo.Cases cs on mt.meet_CaseId = cs.Case_CaseId
left outer join CRM.dbo.Customer cust on mt.meet_companyid =cust.cust_CustomerID
left outer join crm.dbo.users on mt.meet_launcher = user_userid
WHERE mt.meet_companyid in  (select * from crm.dbo.customer_tree(7587,0))

在最后一个子句中,工作基本上设置为四位数字作为参数,从当前工作簿中的另一个工作表中读取单元格内容。

in  (select * from crm.dbo.customer_tree( ? ,0)) 

(仅供参考,customer_tree不是数据库中的简单表/视图名称,而客户是表名。)

但是,Excel 2007不喜欢这种格式,错误消息显示为:

  

[Microsoft] [ODBC SQL Server驱动程序]语法错误或访问冲突
  [Microsoft] [ODBC SQL Server驱动程序]无效的描述符索引

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

通过将单元格内容分配到变量然后重置整个查询命令框,可以解决此问题。

第1步

由开发人员创建 ActiveX控件命令按钮 - >插入 - > ActiveX命令按钮(第一个)

在工作表中绘制一个按钮,并设置名称,标题和其他任何属性(可选)。

第2步

双击按钮,或右键单击选择视图代码,或单击开发人员栏上的Visual Basic以打开VBA编辑器。

修改工作表的代码,如下所示(我的按钮名为Refresh):

Private Sub Refresh_Click() 

    'Declare a variable to content the cell, here is a number in my case
    Dim CustomerId As Integer

    'Declare variables for my ODBC connection, "sql01" is the table name   
    Dim awc As WorkbookConnection
    Set awc = ActiveWorkbook.Connections("sql01")

    'Get the cell content which has the target number
    CustomerId = Sheets("Sheet1").Range("B2").Value


    'Pass the Parameters values 
    With awc.ODBCConnection

        .CommandText = "mt.meet_companyid IN " & _ 
               "( select * from crm.dbo.customer_tree('" & **CustomerId** & "', 0)) " 

        'Refresh the sheet
        awc.Refresh

    End With
End Sub

用户单击该按钮后,将使用当前单元格内容编号更改查询命令。

相关问题