如何在VBA Excel中执行SQL查询

时间:2016-09-20 12:55:24

标签: sql excel-vba vba excel

Sub Run()

  Call ConnectDB

    Dim Cmd As ADODB.Command
    Dim rcs As ADODB.Recordset
    Dim SQL As String
    Dim res() As String

    Set Cmd = New ADODB.Command
    Set Cmd.ActiveConnection = con

    SQL = "select tl.id, al.price_crossing, al.price_exchange_fees, tl.charges_execution, tl.charges_mariana, tl.charges_exchange, tl.trade_date, un.value, tl.nb_crossing  from mfb.trade_leg tl" & _
    "inner join mfb.trade t on t.id = tl.id_trade" & _
    "inner join mfb.instrument i on t.id_instrument = i.id" & _
    "inner join mfb.instrument_type it on it.id = i.id_instrument_type" & _
    "inner join mfb.options o on o.id_instrument = i.id" & _
    "inner join mfbref.mfb.underlying un on un.id = o.id_underlying" & _
    "inner join mfb.allocation_leg al on al.id_trade_leg = tl.id" & _
    "where tl.trade_date > '20160101' and t.state = 3"

    Cmd.CommandText = SQL
    Set rcs = Cmd.Execute()

每次执行此代码时,都会出现一个调试错误,指出“#tt”附近的语法不正确。我尝试以不同的方式执行SQL,但错误不会改变

3 个答案:

答案 0 :(得分:2)

SQL = "select tl.id, al.price_crossing, al.price_exchange_fees, tl.charges_execution, tl.charges_mariana, tl.charges_exchange, tl.trade_date, un.value, tl.nb_crossing  from mfb.trade_leg AS tl " & _
"inner join mfb.trade t on t.id = tl.id_trade " & _
"inner join mfb.instrument i on t.id_instrument = i.id " & _
"inner join mfb.instrument_type it on it.id = i.id_instrument_type " & _
"inner join mfb.options o on o.id_instrument = i.id " & _
"inner join mfbref.mfb.underlying un on un.id = o.id_underlying " & _
"inner join mfb.allocation_leg al on al.id_trade_leg = tl.id " & _
"where tl.trade_date > '20160101' and t.state = 3 "

答案 1 :(得分:1)

SQL = "select tl.id, al.price_crossing, al.price_exchange_fees, tl.charges_execution, tl.charges_mariana, tl.charges_exchange, tl.trade_date, un.value, tl.nb_crossing  from mfb.trade_leg tl " & _
"inner join mfb.trade t on t.id = tl.id_trade " & _
"inner join mfb.instrument i on t.id_instrument = i.id " & _
"inner join mfb.instrument_type it on it.id = i.id_instrument_type " & _
"inner join mfb.options o on o.id_instrument = i.id " & _
"inner join mfbref.mfb.underlying un on un.id = o.id_underlying " & _
"inner join mfb.allocation_leg al on al.id_trade_leg = tl.id " & _
"where tl.trade_date > '20160101' and t.state = 3;"

你遗漏了大量的空间

答案 2 :(得分:0)

在为SQL对象分配别名时,应使用“as”。

尝试更改

     ...from mfb.trade_leg tl...
     ...join mfb.trade t...
     ...join mfb.options o ...

     ...from mfb.trade_leg as tl...
     ...join mfb.trade as t...
     ...join mfb.options as o ...