SQL Server · Execute

A procedure that returns tables

A procedure that returns tables, in two scenarios. A SQL Server procedure returns a table by selecting it: each SELECT it runs is a result set. ARX runs the call in one round trip and returns the result sets by position (ResultSets[0], ResultSets[1] …), in the order the procedure sends them.

Set up for this page

The scenarios build on the sample application: SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleContext.Application.cs (dbContext.Service, the application's ARX service); SampleCatalog.cs (the tables' ids, keys, lookups and display names).

Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:

Set up
var account = new ArxEntity("account");
account["name"] = "Tables Inc";
account["account_number"] = "ACC-E401";
var accountId = await service.CreateAsync(account);
foreach (var (sku, price) in new[] { ("SKU-E401", 10m), ("SKU-E402", 4.5m) })
{
    var product = new ArxEntity("product");
    product["sku"] = sku;
    product["name"] = $"Product {sku}";
    product["unit_price"] = price;
    await service.CreateAsync(product);
}
var place = new ArxProcedureExpression("sp_place_order");
place.AddParameter("p_account_id", accountId.AsInt64());
place.AddParameter("p_order_number", "SO-E401");
place.AddParameter("p_skus", "SKU-E401,SKU-E402");
place.AddParameter("p_quantity", 2);
place.AddOutParameter<long>("p_order_id");
place.AddOutParameter<decimal>("p_total");
var orderId = (long)(await service.ExecuteAsync(place)).Outputs["p_order_id"]!;

1 One table

sp_order_with_lines's second table, the lines: ResultSets[1].

Already in scope: service (ArxMsSqlDbService), orderId (long)

C#
var procedure = new ArxProcedureExpression("sp_order_with_lines");
procedure.AddParameter("p_order_id", orderId);

var lines = (await service.ExecuteAsync(procedure)).ResultSets[1];
Console.WriteLine(string.Join(", ", lines.Entities.Select(x => $"{x["sku"]} x{x["quantity"]} at {x["unit_price"]:N2}")));

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT p.sku, l.quantity, l.unit_price
FROM order_line l
JOIN sales_order o ON o.id = l.order_id
JOIN product p ON p.id = l.product_id
WHERE o.order_number = 'SO-E401'
ORDER BY p.sku;

Expect: 2 rows: SKU-E401 2 10.00, SKU-E402 2 4.50.

2 Two tables, by position

Both tables: the order (ResultSets[0]) and its lines (ResultSets[1]).

Already in scope: service (ArxMsSqlDbService), orderId (long)

C#
var procedure = new ArxProcedureExpression("sp_order_with_lines");
procedure.AddParameter("p_order_id", orderId);

var result = await service.ExecuteAsync(procedure);
var order = result.ResultSets[0].Entities.Single();
Console.WriteLine($"{order["order_number"]} for {order["account"]}, total {order["total"]:N2}; {result.ResultSets[1].Entities.Count} lines (ResultSets[1] is \"{result.ResultSets[1].EntityName}\")");

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT o.order_number, a.name, o.total, (SELECT count(*) FROM order_line l WHERE l.order_id = o.id) AS lines
FROM sales_order o
JOIN account a ON a.id = o.account_id
WHERE o.order_number = 'SO-E401';

Expect: SO-E401, Tables Inc, 29.00, 2.

Run the complete sample

The code above comes from one program, built in a fresh project and run against the database. To run it yourself, here is every file and step.

The program, its files and how to run it

Run it locally

  1. .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target net10.0).
  2. Create the project:
    Terminal
    dotnet new console -n ArxSample -f net10.0
    cd ArxSample
  3. Install the packages:
    Terminal
    dotnet add package ARX.SDK.SQL --version 1.0.0-rc.1
  4. Database: a SQL Server 2022 (tested with 16.0.4225.2) database with the sample schema.
  5. Configuration: set ARX_SAMPLES_SQLSERVER to its connection string. Nothing is hard-coded.
  6. Source code: add the files of the sample application this sample uses (SampleContext.cs, SampleOutput.cs, SampleContext.Application.cs, SampleCatalog.cs), then replace Program.cs and add the other file below, with the file names shown.
  7. Run it:
    Terminal
    dotnet run
  8. Expected output: below.

The files

Program.cs

Runs the sample. Generated for this page; it reads the connection string from the environment.

using ArxSamples.MSSQL;
using ArxSamples.MSSQL.Operations.Execute.Basics;

// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_SQLSERVER")
    ?? throw new InvalidOperationException("Set the ARX_SAMPLES_SQLSERVER environment variable to your SQL Server connection string.");

await new Basic4_AProcedureThatReturnsTables().RunAsync(new SampleContext(connectionString));
Basic4_AProcedureThatReturnsTables.cs

The sample, as it is in the repository.

using ARX.SDK.Query;
using ARX.SDK.Services;
using static ArxSamples.MSSQL.SampleOutput;

namespace ArxSamples.MSSQL.Operations.Execute.Basics;

/// <summary>
/// A procedure that returns tables, in two scenarios. A SQL Server procedure returns a table by selecting it: each
/// SELECT it runs is a result set. ARX runs the call in one round trip and returns the result sets by position
/// (<c>ResultSets[0]</c>, <c>ResultSets[1]</c> …), in the order the procedure sends them.
/// </summary>
public sealed class Basic4_AProcedureThatReturnsTables : ISample
{
    public string Name => "execute-basics-4-a-procedure-that-returns-tables";

    public string Title => "A procedure that returns tables";

    public async Task RunAsync(SampleContext dbContext)
    {
        var account = new ArxEntity("account");
        account["name"] = "Tables Inc";
        account["account_number"] = "ACC-E401";
        var accountId = await dbContext.Service.CreateAsync(account);

        foreach (var (sku, price) in new[] { ("SKU-E401", 10m), ("SKU-E402", 4.5m) })
        {
            var product = new ArxEntity("product");
            product["sku"] = sku;
            product["name"] = $"Product {sku}";
            product["unit_price"] = price;
            await dbContext.Service.CreateAsync(product);
        }

        var place = new ArxProcedureExpression("sp_place_order");
        place.AddParameter("p_account_id", accountId.AsInt64());
        place.AddParameter("p_order_number", "SO-E401");
        place.AddParameter("p_skus", "SKU-E401,SKU-E402");
        place.AddParameter("p_quantity", 2);
        place.AddOutParameter<long>("p_order_id");
        place.AddOutParameter<decimal>("p_total");
        var orderId = (long)(await dbContext.Service.ExecuteAsync(place)).Outputs["p_order_id"]!;

        await Scenario1_OneTableAsync(dbContext, orderId);

        await Scenario2_TwoTablesByPositionAsync(dbContext, orderId);
    }

    /// <summary>1. <c>sp_order_with_lines</c>'s second table, the lines: <c>ResultSets[1]</c>.</summary>
    private static async Task Scenario1_OneTableAsync(SampleContext dbContext, long orderId)
    {
        Step("1. One table");

        var procedure = new ArxProcedureExpression("sp_order_with_lines");
        procedure.AddParameter("p_order_id", orderId);

        var lines = (await dbContext.Service.ExecuteAsync(procedure)).ResultSets[1];
        Show(string.Join(", ", lines.Entities.Select(x => $"{x["sku"]} x{x["quantity"]} at {x["unit_price"]:N2}")));

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT p.sku, l.quantity, l.unit_price
         * FROM order_line l
         * JOIN sales_order o ON o.id = l.order_id
         * JOIN product p ON p.id = l.product_id
         * WHERE o.order_number = 'SO-E401'
         * ORDER BY p.sku;
         * -- Expect: 2 rows: SKU-E401 2 10.00, SKU-E402 2 4.50.
         * ===========================================================
         */
    }

    /// <summary>2. Both tables: the order (<c>ResultSets[0]</c>) and its lines (<c>ResultSets[1]</c>).</summary>
    private static async Task Scenario2_TwoTablesByPositionAsync(SampleContext dbContext, long orderId)
    {
        Step("2. Two tables, by position");

        var procedure = new ArxProcedureExpression("sp_order_with_lines");
        procedure.AddParameter("p_order_id", orderId);

        var result = await dbContext.Service.ExecuteAsync(procedure);
        var order = result.ResultSets[0].Entities.Single();
        Show($"{order["order_number"]} for {order["account"]}, total {order["total"]:N2}; {result.ResultSets[1].Entities.Count} lines (ResultSets[1] is \"{result.ResultSets[1].EntityName}\")");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT o.order_number, a.name, o.total, (SELECT count(*) FROM order_line l WHERE l.order_id = o.id) AS lines
         * FROM sales_order o
         * JOIN account a ON a.id = o.account_id
         * WHERE o.order_number = 'SO-E401';
         * -- Expect: SO-E401, Tables Inc, 29.00, 2.
         * ===========================================================
         */
    }
}

Expected output

What dotnet run printed when the sample was verified, on a freshly created sample schema. Ids differ when the tables already hold rows.

Output
  > 1. One table
      SKU-E401 x2 at 10.00, SKU-E402 x2 at 4.50
  > 2. Two tables, by position
      SO-E401 for Tables Inc, total 29.00; 2 lines (ResultSets[1] is "sp_order_with_lines")