Business Central AL Language OnPrem链接外部数据库

1. REST/ODATA API

如果外部数据库通过 Web API 暴露数据(如 ASP.NET Core Web API),你可以使用 AL 的 HttpClient 来访问

Bash
procedure CallExternalAPI()
var
    HttpClient: HttpClient;
    HttpResponse: HttpResponseMessage;
    JsonText: Text;
begin
    if HttpClient.Get('http://yourserver/api/customers', HttpResponse) then begin
        HttpResponse.Content().ReadAs(JsonText);
        // 处理返回的 JSON
    end;
end;

2. 使用 SqlConnection 访问外部 SQL Server

Business Central OnPrem 支持通过 .NET Interop 使用 System.Data.SqlClient 来连接外部 SQL Server 数据库

Bash
codeunit 50100 SqlIntegration
{
    var
        SqlConnection: DotNet "System.Data.SqlClient.SqlConnection";
        SqlCommand: DotNet "System.Data.SqlClient.SqlCommand";
        SqlDataReader: DotNet "System.Data.SqlClient.SqlDataReader";

    procedure GetDataFromExternalDB()
    begin
        SqlConnection := SqlConnection.SqlConnection('Server=YOUR_SERVER;Database=YOUR_DB;User Id=USER;Password=PASS;');
        SqlConnection.Open();

        SqlCommand := SqlCommand.SqlCommand('SELECT TOP 10 * FROM Customer', SqlConnection);
        SqlDataReader := SqlCommand.ExecuteReader();

        while SqlDataReader.Read() do begin
            // 处理读取的数据
        end;

        SqlConnection.Close();
    end;
}

3. LinkedObject

Business Central OnPrem 支持通过LinkedObject鏈接到同服務器下的不同數據庫

讓 Business Central 不必真正「複製」資料,而是即時讀寫已存在於同一SQL Server執行個體(但不同資料庫或相同資料庫)的任意使用者資料表或檢視表

Bash
table 50101 LedgerEntryView
{

    DataClassification = CustomerContent;
    LinkedObject = true; //鏈接SQL對象
    DataPerCompany = false; //不按公司分隔數據

不可使用其他服務器,即使是鏈接服務器,只能在同服務器下跨數據庫操作

4. TableType = External

TableType = External 是 Business Central 2022 Wave 2 (v21) 之後引入的新屬性。

用來 取代舊的 LinkedObject = true,讓 AL 語法更直觀、意圖更清楚,核心行為與 LinkedObject 幾乎相同。

但與LinkedObject不同的是TableType = External 支持使用字符串鏈接外部服務器并進行讀寫等操作

數據庫鏈接:

Bash
begin

        
        DatabaseName := '';
        ConnectionString := '';

        // 检查是否已存在连接,如果存在则注销
        IF HasTableConnection(TableConnectionType::ExternalSQL, DatabaseName) THEN
            UnregisterTableConnection(TableConnectionType::ExternalSQL, DatabaseName);

        // 注册新的数据库连接
        RegisterTableConnection(TableConnectionType::ExternalSQL, DatabaseName, ConnectionString);

        // 设置默认连接
        SetDefaultTableConnection(TableConnectionType::ExternalSQL, DatabaseName);

    end;

在Table中的使用:

Bash
table 50026 ""
{
    Caption = '';
    DataClassification = CustomerContent;
    TableType = ExternalSQL;
    ExternalSchema = 'dbo';
    ExternalName = '';
订阅评论
提醒
0 评论
最旧
最新 最多投票
内联反馈
查看所有评论
滚动至顶部