微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Access 2010 执行SQLServer 2008 R2存储过程获取返回值

该示例描述了如何利用Access ADO 执行sqlServer 中的存储过程

1、运行sql Server Management Studio, 创建数据库TestDb和如下图的表Customers:

2. 创建存储过程sp_AddCustomer

USE [TestDb]
GO
/****** Object:  StoredProcedure [dbo].[sp_AddCustomer]    Script Date: 11/10/2011 15:55:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_AddCustomer]
(
        @ID int output,@CustomerLevelID numeric,@ContactFirstName   nvarchar(255),@ContactLastName   nvarchar(255)
)
AS
IF @ContactFirstName IS NOT NULL  
BEGIN
        IF NOT EXISTS  ( SELECT * FROM Customers  WHERE ContactLastName=@ContactLastName )      
            BEGIN    
             INSERT INTO Customers
             (  
                [ContactFirstName],[ContactLastName],[CustomerLevelID]     
            )
        VALUES
            (  

                @ContactFirstName,@ContactLastName,@CustomerLevelID
			)
            select @ID = @@IDENTITY
            return    
        END  
            ELSE  
             select -1  
             return
  END  
        ELSE  
         select 0  
         return

3. 创建Access Form并设计成如下:

 

 4. 给ExcutesqlProc添加事件:

Option Compare Database

Private Sub Command0_Click()
AddCustomer
End Sub

Private Sub AddCustomer()

DoCmd.Hourglass True

    Dim cn As ADODB.Connection
    Dim sp As ADODB.Command
    Set cn = New ADODB.Connection
    'cn.ConnectionString = "Data Source=localhost;Initial Catalog=TestDb;Integrated Security=sspI;"
    
    cn.ConnectionString = "Provider=sqlNCLI10;" _
         & "Server=(local);" _
         & "Database=TestDb;" _
         & "Integrated Security=sspI;" _
         & "DataTypeCompatibility=80;"

    
    cn.Open
    Set sp = New ADODB.Command
    sp.ActiveConnection = cn
    sp.CommandType = adCmdstoredProc
    sp.CommandText = "sp_AddCustomer"
    sp.Parameters.Refresh
    sp.Parameters("@CustomerLevelID") = IIf(Me.txtCustomerLevelID = "",Me.txtCustomerLevelID)
    sp.Parameters("@ContactFirstName") = Me.txtContactFirstName
    sp.Parameters("@ContactLastName") = Me.txtCustomerLastName
    
    sp.Execute
    
    Me.txtCustomerID = sp.Parameters("@ID").Value
    'MsgBox sp.Parameters("@ID").Value
    cn.Close
    
    DoCmd.Hourglass False

End Sub


 

 5. 执行该存储过程会判断表中LastName是否存在,不存在就会插入一条记录并返回该记录的IdentityId。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐