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。

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...