从Access插入/更新链接的SQL Server表

时间:2014-06-17 22:56:47

标签: sql-server-2008 access-vba ms-access-2010

是否可以从Access前端将数据插入/更新到SQL Server表中?如果是这样的话?

我在访问数据库中有一个链接的sql server表,我想使用未绑定的访问表单进行更新,这样做的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

不确定为什么它会在退出数据库时删除,除非它不提交事务,但不确定你将如何实际执行此操作,可能是表的连接字符串中的某些内容。

非常简单的存储过程路径如下所示:

创建存储过程:

CREATE PROCEDURE usp_SimpleUpdateExample 
    -- Add the parameters for the stored procedure here
    @NewValue int,
    @WhereCriteria1 int,
    @WhereCriteria2 varchar(10),
    @Ret int OUTPUT
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
BEGIN TRY
    BEGIN TRANSACTION
        UPDATE tbl_YourTable
        SET UpdatedField = @NewValue
        WHERE FirstCriteriaField = @WhereCriteria1 
                And SecondCriteriaField = @WhereCriteria2

        SET @Ret = @@ROWCOUNT

        COMMIT TRANSACTION

END TRY
BEGIN CATCH
    IF @@trancount > 0 ROLLBACK TRANSACTION
    SET @Ret = -1
END CATCH

END

创建一个函数来调用该过程:

Function UpdateData(iNewValue As Integer, iCrtieria1 As Integer, _
    strCriteria2 As String) As Long
On Error GoTo Err_Handle


Set cnn = CreateObject("ADODB.Connection")
cnn.ConnectionString = "DRIVER={SQL Server};SERVER=ServerName;" _
    & "DATABASE=DatabaseName;Trusted_Connection=Yes"

cnn.Open cnn.ConnectionString

Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "dbo.usp_SimpleUpdateExample"
cmd.CommandTimeout = 0

Set param = cmd.CreateParameter("@NewValue", adInteger, _
    adParamInput, , iNewValue)
cmd.Parameters.Append param
Set param = cmd.CreateParameter("@WhereCriteria1", 20, _
    adParamInput, , iCrtieria1)
cmd.Parameters.Append param
Set param = cmd.CreateParameter("@WhereCriteria2", adVarChar, _
    adParamInput, , strCriteria2)
cmd.Parameters.Append param
Set param = cmd.CreateParameter("@Ret", adInteger, adParamOutput)
cmd.Parameters.Append param


cmd.Execute

UpdateData = cmd.Parameters("@Ret")


Exit_Proc:
Set cnn = Nothing
Set cmd = Nothing
Set param = Nothing

Exit Function

Err_Handle:
    ' msgbox with details or whatever error handle you use
    AllocatePymt = -1
    GoTo Exit_Proc
End Function

存储过程(以及函数)返回更新的行数(或者INSERT新行数)或者如果发生错误则返回-1;称之为:

l = UpdateData(52,1234,"FooBar")
SelectCase l
Case Is > 0
    msgbox "Updated " & l & " rows"
Case 0
    Msgbox "No rows updated, but no error"
Case Else
    Msgbox "An error occurred, the transaction was rolled back"
End Select

这一切都适用于Access 2007SQL Server 2005,这就是我所能提供的。