gpt4 book ai didi

function - 如何从 C# 调用 ms-access 函数?

转载 作者:行者123 更新时间:2023-12-04 04:39:59 25 4
gpt4 key购买 nike

我在一个名为“StripLead”的模块中编写了一个 ms-access 函数。我制作了一个名为“CallFunction”的单行程序。现在,当我从 ms-access 调用此过程时,它工作正常。但是当我从 C# 调用这个过程时,我得到了错误:

Undefined function 'Striplead' in expression.



ms-access模块​​代码:
Public Function StripLead(pstrPhrase As String) As String
Dim strFirstWord As String
Dim strReturn As String
Dim intPos As Integer

strReturn = pstrPhrase
intPos = InStr(pstrPhrase, " ")
If intPos > 0 Then
strFirstWord = Left$(pstrPhrase, intPos - 1)
Select Case strFirstWord
Case "A", "An", "The"
strReturn = Right$(pstrPhrase, Len(pstrPhrase) - intPos)
End Select
End If

StripLead = strReturn
End Function

ms-access 过程“CallFunction”(sql View ):
SELECT Customers.ID, Striplead([ContactName]) AS a FROM Customers;

C#代码:
   public void CallStoredProcedure(string NewQry)
{
try
{
DataTable tbl = new DataTable();
using (OleDbConnection connection = new OleDbConnection(ConnectionString))
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "CallFunction";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;

using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
{
adp.Fill(tbl);
}
}

}
catch(Exception ex)
{
throw;
}
}

请提出方法是否不正确。或者,如果有办法从 C# 调用 ms-access 函数来获取数据。
我的目标是从 ms-access 获取修改后的数据并用 C​​# 填充数据网格。

最佳答案

Access 提供了从 SQL 查询调用用户定义的 VBA 函数的能力,但该能力仅限于从 Microsoft Access 应用程序本身进行的查询。这是因为 VBA 功能需要 Access 应用程序的基础结构(特别是 VBA“表达服务”)来执行。

在您的情况下,您可以使用 Microsoft.Office.Interop.Access 在 C# 代码中运行“真实”访问查询。但这会给你一个DAO Recordset对象,并摆弄它以使用 OleDbDataAdapter很可能比它的值(value)更麻烦(如果可能的话)。

在 C# 中重新创建 VBA 函数逻辑可能会更好。

关于function - 如何从 C# 调用 ms-access 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19043939/

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