Invalid SQL statement expected; ‘DELETE’,’INSERT’,

≡放荡痞女 提交于 2019-12-02 14:54:54

问题


I have a code

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

Is that something worng when i ran this code VBA show Error "Invalid SQL statement expected; ‘DELETE’,’INSERT’," Thanks for see my question !


回答1:


The syntax for your parametered query doesn't look right.

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

I'm not sure the provider supports DECLARE statements. If it doesn't, that's why you're getting this message. Let's try to remove it:

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

Notice the WHERE clause, WHERE Ngay_HD <> NULL AND TS_HD = ? - the parameter placeholder is just a question mark.

I'm pretty sure that statement would work.

I'm less sure about how the parameter is passed in though:

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

I think you can drop the name parameter, it's optional - and some providers don't support named parameters. That sucks though, because now you need to name the arguments since the Name parameter is first in the signature of CreateParameter:

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

An alternative could be to New it up and initialize it "manually":

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


来源:https://stackoverflow.com/questions/33886288/invalid-sql-statement-expected-delete-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!