您的位置:首页 > 数据库

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

2011-11-10 16:02 591 查看
该示例描述了如何利用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 = "", 0, 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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: