在Access中通过查询

时间:2015-11-04 06:15:57

标签: sql access-vba

我是使用SQL Server express来扩大Access(2007-2010)前端的新手。

我编写了一个管理SQL连接的类模块。为了自动调用函数,称为过程和动态SQL字符串,最后两个使用SELECT语句成功返回一个表,我附加到DAO.recordset以进一步提取结果。

然而,当尝试对插入语句执行相同操作时遇到问题 SQL直通查询是:

DECLARE @ret int;
BEGIN TRANSACTION T1;
BEGIN TRY
INSERT INTO dbo.[Munten](Munt, Decimalen, Volgorde) VALUES ('XYZ', 4, 99)
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION T1;
END CATCH;
IF @@TRANCOUNT = 0
SET @ret = 0
ELSE
BEGIN
        COMMIT TRANSACTION T1;
    SET @ret = 1
END;
SELECT @ret as Retval;

在SQL管理工作室上运行正常,返回一列记录,但在执行poassthrough查询时,我得到:

  

“将returnrecords属性设置为true的Passtrhough没有返回任何记录”

获取访问代码:

Public Function AddRecord(TblName As String, Connectstring As String,      ParamArray Pars()) As Boolean
Dim s As String, I As Integer, str As String, sc As String, sv As String, rs As DAO.Recordset
ProcList.Start procmodule, "AddRecord", TblName, Connectstring, Pars()
On Local Error GoTo ErrHandler
With appdb.CreateQueryDef("")
    If Len(Connectstring) = 0 Then
       .Connect = StConnectstr
    Else
       .Connect = Connectstring
   End If
   For I = 0 To UBound(Pars)     ' ubound=-1 if no pars are passed
       If I Mod 2 = 0 Then     ' list of columns
          If I > 0 Then sc = sc & ", "
          sc = sc & Pars(I)
       Else                    '  list of values
          If I > 1 Then sv = sv & ", "
          If IsDate(Pars(I)) Then
              sv = sv & DateForSQL(Pars(I))
          ElseIf IsNumeric(Pars(I)) Then
              sv = sv & ConvDecimal(Pars(I), True)
          Else
              sv = sv & cSquote & Pars(I) & cSquote
         End If
       End If
   Next
   s = "INSERT INTO " & Me.WithSchema(TblName, IsTable) & "(" & sc & ") VALUES (" & sv & ")"
   str = EmbedTryCatch(s, .Connect)
   .ReturnsRecords = True
   .SQL = str
   AddRecord = (.OpenRecordset(, dbSQLPassThrough).Fields(0) <> 0)
   .Close
End With
Exit_Here:
     ProcList.Leave
     Exit Function
ErrHandler:
     If Error_message() Then Resume 0
     Resume Exit_Here
End Function

Private Function EmbedTryCatch(SQLstring As String, Connectstr As String) As String
EmbedTryCatch = "DECLARE @ret BIT;" & vbCrLf _
    & "BEGIN TRANSACTION T1;" & vbCrLf _
    & "BEGIN TRY" & vbCrLf _
        & SQLstring & vbCrLf _
    & "END TRY" & vbCrLf _
    & "BEGIN CATCH" & vbCrLf _
        & "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION T1;" & vbCrLf _
    & "END CATCH;" & vbCrLf _
    & "IF @@TRANCOUNT = 0" & vbCrLf _
        & "SET @ret = 0" & vbCrLf _
    & "ELSE" & vbCrLf _
        & "BEGIN" & vbCrLf _
            & "COMMIT TRANSACTION T1;" & vbCrLf _
            & "SET @ret = 1" & vbCrLf _
        & "END;" & vbCrLf _
    & "SELECT @ret as Retval;"
End Function

渔获物在哪里?

1 个答案:

答案 0 :(得分:0)

您需要将查询的ReturnsRecords属性设置为False,因为插入查询不返回任何内容。

也是一个好主意,包括:

set nocount on

作为直通查询的第一行 - 例如,Access似乎无法理解您在SSMS中看到的返回消息。