DarioDP
DarioDP

Reputation: 627

How do I count the number of elements in a table using a script on Azure?

I need to make an online leaderboard for a videogame. I'm using a Mobile Service on Azure. I have a table which should contain only the first 100 scores (highest, of course) so before this number of records is reached, every score should be admitted. To do this, I need to count the number of the rows of my Leaderboard table in my insert script on Azure.

The default script is:

function insert(item, user, request) {
   request.execute();
}

And my query would be something like:

SELECT COUNT (*)  
FROM Leaderboard

I tried to use mssql.query but it's like that part of code is ignored.

var sql = "SELECT COUNT (*) FROM Leaderboard";

    mssql.query(sql, {
        success: function(results){
            //do things
        },
        error: function(err) {
            console.log("error: " + err);
        }
    });

I also tried:

var LeaderboardOnlineTable = tables.getTable('LeaderboardOnline');

LeaderboardOnlineTable.take(0).includeTotalCount().read().then(function (results) {
        var count = results.totalCount;
    });

Am I doing something wrong?

Thanks in advance!

Upvotes: 1

Views: 191

Answers (1)

gbellmann
gbellmann

Reputation: 1951

This should work:

function insert(item, user, request) {
    var LeaderboardOnlineTable = tables.getTable('LeaderboardOnline');
    LeaderboardOnlineTable.includeTotalCount().read({success: insertRecord});

    function insertRecord(results) {
        var count = results.totalCount;
        if (count < 100) {
            request.execute();
        } else {
            // do whatever you need if the table is "full"
        }
    }
}

Upvotes: 1

Related Questions