Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

User Defined Functions

Mathias Rangel Wulff edited this pageOct 2, 2017 ·18 revisions

User defined functions

To define new functions for SQL simply add it toalasql.fn variable, like below:

alasql.fn.cube=function(x){returnx*x*x;}alasql(‘SELECTcube(x)FROM ?,[data]);
alasql.fn.double=function(x){returnx*2};alasql.fn.sum10=function(x,y){returnx+y*10;}alasql('SELECT a, double(a) AS b, sum10(a,b) FROM test1');

You can use alasql inside alasql functions, like below:

alasql.fn.myfilter=function(phase){returnalasql('SELECT VALUE COUNT(*) FROM ? WHERE Phase = ?',[data,phase])==2;};varres=alasql('SELECT * FROM ? WHERE myfilter(Phase)',[data]);

See the working examplein jsFiddle

From 3.8 functions can be set via a SQL statement with the following syntax:

CREATEFUNCTIONcubicAS``function(x) { return x*x*x; }``;

Aggregators

To make your own user defined aggregators please follow this example:

// How to implement the SUM() aggregatoralasql.aggr.MYAGGR=function(value,accumulator,stage){if(stage==1){// first call of aggregator - for first linevarnewAccumulator=value;returnnewAccumulator;}elseif(stage==2){// for every line in the groupaccumulator=accumulator+value;returnaccumulator;}elseif(stage==3){// Post production - please nota that value Will be undefinedreturnaccumulator;}}

See more examples here:

Create aggretating functions

From 3.8 aggretating functions can be set via a async SQL statement with the following syntaxes:

CREATE (AGGREATE|AGGREGATOR) MyAggrAS``function(value, accumulator, stage) { ... }``;

CustomFROM function

You can create custom FROM function like here:

alasql.from.DB = function(dbtype, opts, cb, idx, query) {var res = [];        async_read_data_from_mysql_function(dbtype, opts.dbname, opts.tablename, function(data) {res = data;if(cb){res = cb(res, idx, query);}};return null;};function async_read_data_from_mysql_function(dbtype, dbname, tablename, cb) {    // put your code here   cb(read_data);}

Then you can use it like:

SELECT*FROM DB("mysql",{dbname:"one", tablename:"two"})

Also, you can save data to MYSQL withalasql.into.DB() custom function.

alasql('SELECT * INTO DB("mysql",{dbname:"one", tablename:"two"}) FROM ?',[data]);

You can see the examples of FROM and INTO functions atsrc/84from.js andsrc/830into.js files.

© 2014-2026,Andrey Gershun &Mathias Rangel Wulff

Please help improve the documentation by opening a PR on thewiki repo

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp