gpt4 book ai didi

excel - 使用 Excel 2010 通过存储过程读取/写入 SQL Server 2008 数据库

转载 作者:行者123 更新时间:2023-12-02 11:19:08 31 4
gpt4 key购买 nike

我们有一个 SQL Server 2008 数据库,它有存储过程来处理读/写等。这些过程由各种应用程序在内部使用。

需要一个人直接更新数据库中名为 Employee 的表。更新非常简单;更新 VARCHAR 和 INT(外键)字段。问题在于 SharePoint 2010 无法轻松支持通过 BCS 进行此类更新;浏览和更新并不是最好的用户体验。

有人建议使用 Excel 和 VBA 可以轻松解决这个问题。打开时,Excel 连接到 SQL Server 数据库并从 Employee read 存储过程中读取数据。它还对外键引用的表执行读取存储过程。用户对字段进行更新,该字段又调用 Employee 更新存储过程。

这样做的优点是不需要构建/托管/等网站界面;如果使用 Active Directory 进行身份验证,DBA 可以采用这种方法。

问题是我找不到 VBA 程序员或任何有用的资源或逐步演练来编写 VBA。

有人知道这样的在线资源和/或对如何快速为单个用户启动和运行管理界面有替代建议吗?

最佳答案

我最终选择了使用 AD 身份验证的这种方法。我使用这篇文章中的示例来获取灵感: http://www.eggheadcafe.com/community/sql-server/13/10141669/using-excel-to-update-data-on-ms-sql-tables.aspx

请注意,这些函数位于 Excel 工作簿的不同区域(对象、模块、本工作簿),但这里有一个快速引用。

我还拥有根据它们引用的表进行 FK 验证的每一列。

以下是一些代码示例:

Public aCon As New ADODB.Connection
Public aCmd As New ADODB.Command

Private Sub Workbook_Open()
Application.EnableEvents = False
PopulateSheet
Application.EnableEvents = True
End Sub

Sub Connect()
Dim sConn As String
sConn = "Provider=SQLOLEDB;Trusted_Connection=Yes;Server=[SVR];Database=[DB]"
With aCon
.ConnectionString = sConn
.CursorLocation = adUseClient
.Open
End With
BuildProcs
End Sub

Sub BuildProcs()
With aCmd
.ActiveConnection = aCon
.CommandType = adCmdStoredProc
.CommandText = "[SPROC]"
.Parameters.Append .CreateParameter("@in_EmployeeID", adInteger, adParamInput)
End With

End Sub

Sub PopulateSheet()
Dim n As Integer, r As Long

Dim aCmdFetchEmployees As New ADODB.Command
Dim aRstEmployees As New ADODB.Recordset

If aCon.State = adStateClosed Then Connect

With aCmdFetchEmployees
.ActiveConnection = aCon
.CommandType = adCmdStoredProc
.CommandText = "[SPROC]"
Set aRstEmployees = .Execute
End With
r = aRstEmployees.RecordCount

Worksheets(1).Activate
Application.ScreenUpdating = False
Cells(2, 1).CopyFromRecordset aRstEmployees

For n = 1 To aRstEmployees.Fields.Count
Cells(1, n) = aRstEmployees(n - 1).Name
Cells(1, n).EntireColumn.AutoFit
Next
Cells(1).EntireColumn.Hidden = True
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
If aCon.State = adStateClosed Then Connect
With aCmd
.Parameters(0) = Cells(Target.Row, 1)
.Parameters(1) = Cells(Target.Row, 4)
.Parameters(2) = Cells(Target.Row, 5)
.Parameters(3) = Cells(Target.Row, 6)
.Parameters(4) = Cells(Target.Row, 7)
.Parameters(5) = Cells(Target.Row, 8)
.Parameters(6) = Cells(Target.Row, 10)
.Parameters(7) = Cells(Target.Row, 11)
.Parameters(8) = Cells(Target.Row, 12)
.Parameters(9) = Cells(Target.Row, 13)
.Parameters(10) = Cells(Target.Row, 14)
.Parameters(11) = Cells(Target.Row, 15)
.Parameters(12) = Cells(Target.Row, 16)
.Execute , , adExecuteNoRecords
End With

End Sub

关于excel - 使用 Excel 2010 通过存储过程读取/写入 SQL Server 2008 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9508454/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com