预期的SQL语句无效; “删除”,”插入”,

时间:2015-11-24 05:46:45

标签: excel excel-vba adodb vba

我有一个代码

Dim Cn As New ADODB.Connection

Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
Dim i As Long

Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=" & ThisWorkbook.FullName & ";" & _
    "Extended Properties=""Excel 8.0;"""
Cn.Open
cmd.ActiveConnection = Cn
cmd.CommandText = "DECLARE @TS_HD DOUBLE;" & _
"SET @TS_HD = ?TS_HD;" & _
"SELECT So_HD, Ngay_HD, Ten_Khach_Hang, Ma_So_Thue, Sum(Doanh_So_KT) as DoanhSo, Sum(Thue_VAT) as VAT from [BR$] " & _
"Where Ngay_HD <> null And TS_HD = @TS_HD Group by So_HD, Ma_So_Thue,Ngay_HD, Ten_Khach_Hang Order by Ngay_HD"

Set TS_HD = cmd.CreateParameter("?TS_HD", adDouble, adParamInput)
cmd.Parameters.Append TS_HD
TS_HD.Value = 0.1          'in excel this value is 10%'

Dim rst As ADODB.Recordset
Set rst = cmd.Execute()

BRToTalKhongChiuThue() = rst.GetRows

rst.Close
Cn.Close

当我运行此代码时出现问题VBA显示错误“预期无效的SQL语句;'删除','插入',” 谢谢你看到我的问题!

1 个答案:

答案 0 :(得分:1)

参数化查询的语法看起来不正确。

DECLARE @TS_HD DOUBLE;
SET @TS_HD = ?TS_HD;
SELECT 
     So_HD
    ,Ngay_HD
    ,Ten_Khach_Hang
    ,Ma_So_Thue
    ,SUM(Doanh_So_KT) AS DoanhSo
    ,SUM(Thue_VAT) AS VAT 
FROM [BR$]
WHERE Ngay_HD <> NULL AND TS_HD = @TS_HD 
GROUP BY 
     So_HD
    ,Ma_So_Thue
    ,Ngay_HD
    ,Ten_Khach_Hang
ORDER BY 
     Ngay_HD

我不确定提供商是否支持DECLARE语句。如果没有,那就是你收到这条消息的原因。我们试着删除它:

SELECT 
     So_HD
    ,Ngay_HD
    ,Ten_Khach_Hang
    ,Ma_So_Thue
    ,SUM(Doanh_So_KT) AS DoanhSo
    ,SUM(Thue_VAT) AS VAT 
FROM [BR$]
WHERE Ngay_HD <> NULL AND TS_HD = ?
GROUP BY 
     So_HD
    ,Ma_So_Thue
    ,Ngay_HD
    ,Ten_Khach_Hang
ORDER BY 
     Ngay_HD

注意WHERE子句WHERE Ngay_HD <> NULL AND TS_HD = ? - 参数占位符只是一个问号。

我很确定该声明可行。

我不太确定如何传递参数:

Set TS_HD = cmd.CreateParameter("?TS_HD", adDouble, adParamInput)

我认为您可以删除name参数,它是可选的 - 某些提供程序不支持命名参数。这很糟糕,因为现在你需要命名参数,因为Name参数是CreateParameter签名中的第一个:

Set TS_HD = cmd.CreateParameter(Type:=adDouble, Direction:=adParamInput)

替代方案可以是New,并“手动”初始化它:

Dim param As New ADODB.Parameter
With param
    .Type = adDouble
    .Direction = adParamInput
    .Value = 0.01    'in excel this value is 10% '?? really? it's 1% here!
End With

cmd.Parameters.Append param