azureu-sql

USQL - SQL.ARRAY get length?


For the context, I get data from a sensor and it store in string like this

"axes" : "...,1,23,21,0,12,10,212,12,..."

the size may change depending on the machine sending the data... So my goal is to store it like a SQL.ARRAY and I want to get the size of this array later to perform some bussiness report.

Is there a way to find the length of SQL.ARRAY ?

@outputfile =
    SELECT m.MachineID,
           COUNT( * ) AS nbAxesArray
    FROM MachineInfos AS m
         JOIN
             LoadDataAxes AS lda
         ON m.EventIoTID == lda.EventIoTID
         //WHERE getLength(lda.L) == 0 // something like this
    GROUP BY m.MachineID;

Solution

  • The SQL.ARRAY complex type has a number of methods, like Count and implements IEnumerable under the hood*.

    A simple example:

    DECLARE @outputFile string = @"output/output.csv";
    
    @input =
        SELECT *
        FROM ( VALUES 
            ( 100, "1,23,21,0,12,10,212,12" ),
            ( 101, "7,8,9" )
             ) AS x(rowId, y);
    
    
    // Convert the string to array
    @working =
        SELECT rowId, new SQL.ARRAY<string>(y.Split(',')) AS z
        FROM @input;
    
    
    /*
    // Explode the array to individual rows
    @output =
        SELECT b
        FROM @working
             CROSS APPLY
                 EXPLODE(z) AS a(b);
    */
    
    @output =
        SELECT rowId, z.Count AS c
        FROM @working;
    
    
    OUTPUT @output
    TO @outputFile
    USING Outputters.Csv(quoting:false);
    

    *(I think)

    My results:

    Results

    Some other examples here. Does that help?