【问题标题】:How to run an SQL query via VBA如何通过 VBA 运行 SQL 查询
【发布时间】:2021-11-12 06:33:26
【问题描述】:

我正在尝试运行以下 SQL 查询:

select a.isin
from Risk.BenchmarkFipFwdMainPort a
(where a.ValueDate =  (and a.Isin NOT IN (Select b.isin from Risk.BenchmarkFipCurrMainPort b where b.ValueDate = )))

通过 VBA 将上述查询存储在 Excel 单元格中。 VBA 代码为:

Worksheets("Oversikt over papirer inn-ut").Range("A3:C10000").ClearContents

Set cn = New ADODB.Connection
 cn.Open "Provider=sqloledb;" & _
     "Data Source=NBDBAG-DM1P,60000;" & _
     "Initial Catalog=PRADA;Integrated Security=SSPI"


Src = Worksheets("Oversikt over papirer inn-ut").Range("B1").Value & "'" & myDate & "'"

Set rs = New ADODB.Recordset
With rs
     .Open Source:=Src, ActiveConnection:=cn
     
  '   Write the field names
    For Col = 0 To rs.Fields.Count - 1
        Worksheets("Oversikt over papirer inn-ut").Range("A3").Cells(1, 1).Offset(0, Col).Value = rs.Fields(Col).Name
    Next
     
  '   Write the recordset
    Worksheets("Oversikt over papirer inn-ut").Range("A3").Cells(1, 1).Offset(1, 0).CopyFromRecordset rs
End With

rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

我在 VBA 中收到一条错误消息:“关键字 'and' 附近的语法不正确。有人对如何解决此问题有建议吗?

【问题讨论】:

  • 您没有将想要作为参数的日期放在正确的位置,您只需将其添加到末尾即可。

标签: sql vba


【解决方案1】:

您的 SQL 查询是否正确?

"其中 a.ValueDate = (和 a.Isin"

看起来很奇怪。

你是这个意思吗?

select 
   a.isin
from 
  Risk.BenchmarkFipFwdMainPort a
where 
  a.ValueDate = 'some date' and 
 a.Isin NOT IN 
(Select b.isin from Risk.BenchmarkFipCurrMainPort b where b.ValueDate = 'some date' );

别忘了注明日期。

【讨论】:

  • “不要忘记引用日期”:更好的是:使用 ADODB.Parameter 传递参数。使其类型安全并防止 SQL 注入(好吧,如果 SQL 本身在工作表中,后者并不那么重要)。
  • 确实如此。但在这种情况下,最好尝试一下 SQL 语法是否正确;)
  • 感谢您的反馈! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
相关资源
最近更新 更多