SELECT Query在管理工作室中工作但不在VBA中工作

时间:2017-06-29 10:11:08

标签: sql-server excel vba excel-vba

我在Excel / VBA中遇到问题:从Microsoft SQL Server获取记录集中的数据我收到“多步OLE DB操作生成错误...”当我打开记录集时发生错误。

查询是一个没有错误的SELECT查询(在Management Studio中启动),但它在VBA中使用记录集时出错。

奇怪的是:查询是SELECT SUM ...如果我删除SUM,我就不会收到错误。

你能帮我吗?

代码:

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String

Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset

Set W1 = ActiveWorkbook

sConnString = "Provider=SQLOLEDB;Data Source=SERVERNAME;" & _
    "Initial Catalog=DBNAME;" & _
    "Integrated Security=SSPI;"
conn.Open sConnString

conn.CommandTimeout = 30  

t_sql = ""
t_sql = t_sql & "SELECT" & vbCrLf
t_sql = t_sql & "SUM(rroc.PrezzoUnit / (Cambi.VALORE * (1 + ISNULL(nis.Aliquota, ni.Aliquota)))) AS ordinato" & vbCrLf
t_sql = t_sql & "FROM RepOrdiniClienti roc WITH (NOLOCK)" & vbCrLf
t_sql = t_sql & "inner join RepRigheOrdiniClienti rroc WITH (NOLOCK) ON rroc.RepOrdiniClienti_ID = ID_RepOrdiniClienti" & vbCrLf
t_sql = t_sql & "inner join repclientidestinatari rcd WITH (NOLOCK) ON repclientidestinatari_id = id_repclientidestinatari" & vbCrLf
t_sql = t_sql & "inner join NAZIONI WITH (NOLOCK) ON nazioni_id = id_nazioni" & vbCrLf
t_sql = t_sql & "INNER JOIN CountryBP WITH (NOLOCK) ON CountryBP_ID = ID_CountryBP" & vbCrLf
t_sql = t_sql & "INNER JOIN Valuta WITH (NOLOCK) ON Valuta_ID = ID_VALUTA" & vbCrLf
t_sql = t_sql & "left join Articolo Articolo WITH (NOLOCK) ON rroc.codice10 = Articolo.Codice10" & vbCrLf
t_sql = t_sql & "left join Stagioni Stagioni WITH (NOLOCK) ON Articolo.Stagione_di_Vendita_ID = ID_Stagioni" & vbCrLf
t_sql = t_sql & "INNER JOIN Cambi WITH (NOLOCK) ON Cambi.Valuta_ID=roc.Valuta_ID AND CONVERT(DATE,roc.Data,103) = CONVERT(DATE,Cambi.DATA,103)" & vbCrLf
t_sql = t_sql & "left join Nazioni_intrastat ni WITH (NOLOCK) ON ni.Nazioni_ID = rcd.Nazioni_ID and roc.Data between ni.DataInizio and ni.DataFine" & vbCrLf
t_sql = t_sql & "inner join commitenti c WITH (NOLOCK) ON rcd.Commitenti_ID=c.ID_Commitenti" & vbCrLf
t_sql = t_sql & "left join nazioni_intrastat_societa nis WITH (NOLOCK) ON nis.societa_id=c.Societa_id and nis.nazioni_id=rcd.nazioni_id and (roc.Data between nis.DataInizio and nis.DataFine)" & vbCrLf

ordinato = 0         
rs.Open stringa_sql, conn, adOpenDynamic, adLockOptimistic
If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst
    If Not (IsNull(rs("ordinato"))) Then ordinato = ordinato + CDbl(rs("ordinato"))
End If
rs.Close

Set rs = Nothing
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing

1 个答案:

答案 0 :(得分:1)

尝试将adOpenDynamic更改为adOpenStatic。