该示例描述了如何利用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并设计成如下:
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。