加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 14:52:06 所属栏目:MsSql教程 来源:网络整理
导读:该示例描述了如何利用Access ADO 执行SQLServer 中的存储过程 1、运行SQL Server Management Studio, 创建数据库TestDb和如下图的表Customers: 2. 创建存储过程sp_AddCustomer USE [TestDb]GO/****** Object: StoredProcedure [dbo].[sp_AddCustomer] Scrip

该示例描述了如何利用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。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读