IF condition in While loop in Snowflake procedure - snowflake-cloud-data-platform

my procedure looks like below, but here, the values are not coming into if condition which is written in while loop. please let me know if someone fixes this. i am using v_CODE in insert command which is coming from if condition , since no values are coming into this V_CODE, procedure is getting failed and showing following error Undefined 'FCT.V_CODE'
`CREATE OR REPLACE PROCEDURE CDW_PROC.SAMPLE_PROCEDURE(col1 FLOAT, COL2 VARCHAR, COL3 VARCHAR, COL4 VARCHAR, COL5 VARCHAR, COL6 VARCHAR)
RETURNS VARCHAR(10000)
LANGUAGE JAVASCRIPT
STRICT
EXECUTE AS OWNER
AS
$$
try
{
var v_FILTER_ID=0;
var v_A_TYPE=COL2
var v_TYPE=COL3
var v_FILTER_ATTRIBUTE
var v_ORG=COL4;
var v_FILTER_CONDITION,v_FILTER_VALUE,v_FILTER_DESC;
var v_BRAND ='v_BRAND';
var v_F_TIME_CUR = 'v_F_TIME_CUR';
var v_F_TIME_PREV='v_F_TIME_PREV';
var v_F_RANK='v_F_RANK';
var v_F_TIME_BUCKET='v_F_TIME_BUCKET';
var v_CODE='v_CODE';
var v_ID=col1;
var v_TIME_FRAME=COL5;
var v_WK_MTH_FLG=COL6;
var SEL_SQL=snowflake.execute({sqlText: "SELECT ID,TYPE,ORG,SUB_TYPE,FILTER_ID,FILTER_DESC,FILTER_ATTRIBUTE,FILTER_CONDITION,FILTER_VALUE,TIME_FRAME,WK_MTH_FLG FROM CDW_DB.FCT_TABLE WHERE ID=? AND TYPE =? AND SUB_TYPE =? AND ORG=? AND TIME_FRAME=? AND WK_MTH_FLG =?",binds:[v_ID,v_A_TYPE, v_TYPE, v_ORG, v_TIME_FRAME, v_WK_MTH_FLG]});
while(SEL_SQL.next())
{
var v_ID=SEL_SQL.getColumnValue(1);
var v_A_TYPE=SEL_SQL.getColumnValue(2);
var v_ORG=SEL_SQL.getColumnValue(3);
var v_TYPE=SEL_SQL.getColumnValue(4);
var v_FILTER_ID=SEL_SQL.getColumnValue(5);
var v_FILTER_DESC=SEL_SQL.getColumnValue(6);
var v_FILTER_ATTRIBUTE=SEL_SQL.getColumnValue(7);
var v_FILTER_CONDITION=SEL_SQL.getColumnValue(8);
var v_FILTER_VALUE=SEL_SQL.getColumnValue(9);
var v_TIME_FRAME=SEL_SQL.getColumnValue(10);
var v_WK_MTH_FLG=SEL_SQL.getColumnValue(11);
if (v_BRAND == 'v_'+v_FILTER_DESC.trim())
{
v_BRAND=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
}
else if ( v_F_TIME_CUR =='v_'+v_FILTER_DESC.trim())
{
v_F_TIME_CUR=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
}
else if (v_F_TIME_PREV=='v_'+v_FILTER_DESC.trim())
{
v_F_TIME_PREV=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
}
else if (v_F_RANK=='v_'+v_FILTER_DESC.trim())
{
v_F_RANK=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
}
else if (v_F_TIME_BUCKET=='v_'+v_FILTER_DESC.trim())
{
v_F_TIME_BUCKET=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
}
else if (v_CODE=='v_'+v_FILTER_DESC.trim())
{
v_CODE=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
}
v_WORK_SQL_ALRT_VOL1 = "create or replace table CDW_DB.TEMP_TABLE1(CUST_ID INTEGER,CALL_DATE VARCHAR(255),RNK INTEGER)";
var v_WORK_SQL_ALRT_VOL1_SQL=snowflake.createStatement({sqlText: v_WORK_SQL_ALRT_VOL1});
v_WORK_SQL_ALRT_VOL2 = `insert into CDW_DB.TEMP_TABLE1
select DISTINCT FCT.CUST_ID,
CAST(TO_CHAR(FCT.CALL_DATE_VOD ,'MM/DD/YYYY') AS VARCHAR(10)) AS CALL_DATE,
RANK() OVER (PARTITION BY FCT.CUST_ID ORDER BY FCT.DT_SK ASC,FCT.CREATEDDATE ASC) AS RNK
from CDW_VW.FCT_TABLE FCT WHERE CUST_ID <> -1
and FCT.${v_CODE}
and CALL_DATE_VOD > CURRENT_TIMESTAMP(0) QUALIFY RNK=1;`;
var v_WORK_SQL_ALRT_VOL2_SQL=snowflake.createStatement({sqlText: v_WORK_SQL_ALRT_VOL2});
var VOL1_RESULT=v_WORK_SQL_ALRT_VOL1_SQL.execute();
var VOL2_RESULT=v_WORK_SQL_ALRT_VOL2_SQL.execute();
var v_DROP_VOL_TBL1 =snowflake.execute({sqlText:"DROP TABLE CDW_DB.TEMP_TABLE1"});
var RESULT='Success';
return RESULT;
}
catch(err)
{
RESULT="Failed: Code: "+err.code+"\\n State: "+ err.state;
RESULT+="\\n Message: "+err.message;
RESULT+="\\n Stack Trace:\\n"+err.StackTraceTxt;
return RESULT;
}
$$
;
`
Thanks

You have if/else structure based on the values coming for the SELECT query. So it is normal that the if/else part about v_CODE is not executed everything. For example if v_F_TIME_CUR equals to v_FILTER_DESC, then the following code will not be executed:
...
else if (v_CODE=='v_'+v_FILTER_DESC.trim())
{
v_CODE=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
}
I think you need to use separate "if" conditions?
if (v_BRAND == 'v_'+v_FILTER_DESC.trim())
{
v_BRAND=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
};
if ( v_F_TIME_CUR =='v_'+v_FILTER_DESC.trim())
{
v_F_TIME_CUR=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
};
if (v_F_TIME_PREV=='v_'+v_FILTER_DESC.trim())
{
v_F_TIME_PREV=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
};
...
if (v_CODE=='v_'+v_FILTER_DESC.trim())
{
v_CODE=v_FILTER_ATTRIBUTE+" "+v_FILTER_CONDITION+" "+v_FILTER_VALUE;
}

Related

How to extract information from nested arrays with multiple objects?? (AdminReport.Activities.list)

Could anyone point me in the correct direction?
I searched plenty... I had no luck with mapping... or "find" nor extracting the data I need.
My code:
function checkMeetCode(meetCode, index, searchDate) {
var ss=SpreadsheetApp.getActive().getSheetByName('AsistenciaMeet');
var colB = ss.getRange("D3:D").getValues();
var filasLlenasLengthB = colB.filter(String).length; //
var userKey = 'all';
var applicationName = 'meet';
var emailAddress = colB[index];
Logger.log("Index / Alumno: "+index+" / " + emailAddress);
var optionalArgs = {
event_name: "call_ended",
endTime: searchDate,
startTime: fechaRestada(searchDate),
filters: "identifier==" + emailAddress + ",meeting_code==" + meetCode
};
var response = AdminReports.Activities.list(userKey, applicationName, optionalArgs)
Logger.log("RESPONSE: "+response);
var actividad = response.items;
if (actividad == null) {
// do nothing
}
else {
**// HERE IS WHERE I AM TRYING TO FIND / EXTRACT INFORMATION FROM "response"
// READ BELOW PLEASE.**
}
}
NEED HELP WITH:
I want to FIND/EXTRACT the intValue of "duration_seconds":
The results from:
Logger.log("RESPONSE: "+response);
RESPONSE: {"kind":"admin#reports#activities","etag":"\"JDMC8884sebSctZ17CIssbQ/IhilrSKVziEhoZ7URUpQ-NrztHY\"","items":[{"events":[{"parameters":[{"name":"video_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_mean","intValue":"0"},{"name":"identifier_type","value":"email_address"},{"name":"video_send_packet_loss_max","intValue":"0"},{"name":"endpoint_id","value":"meet_android_4154513448557872"},{"name":"video_recv_long_side_median_pixels","intValue":"320"},{"name":"calendar_event_id","value":"44jr4vu3qo75q6bvkknq_20200421T213000Z"},{"name":"video_send_fps_mean","intValue":"29"},{"name":"video_recv_short_side_median_pixels","intValue":"180"},{"name":"network_estimated_download_kbps_mean","intValue":"351"},{"name":"duration_seconds","intValue":"1830"},{"name":"video_send_bitrate_kbps_mean","intValue":"762"},{"name":"network_recv_jitter_msec_max","intValue":"130"},{"name":"ip_address","value":"186.59.21.55"},{"name":"audio_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_max","intValue":"0"},{"name":"video_recv_seconds","intValue":"1818"},{"name":"network_rtt_msec_mean","intValue":"36"},{"name":"video_send_long_side_median_pixels","intValue":"640"},{"name":"screencast_recv_seconds","intValue":"1829"},{"name":"product_type","value":"meet"},{"name":"video_recv_packet_loss_max","intValue":"0"},{"name":"is_external","boolValue":false}],"name":"call_ended","type":"call"}] ...
OK, after roughly 8 hours... I was able to make it work.
var insideParameters = response["items"][0]["events"][0]["parameters"];
Logger.log(insideParameters.length);
for (var i = 30; i<insideParameters.length;i++){ // its always located above i = 30...
if(insideParameters[i].name === "duration_seconds"){
var duration = insideParameters[i].intValue;
Logger.log(duration);
}
}

Google Scripts: Combining multiple functions and output on same row (cell+ [1] [2], etc)

I'm having some difficulty with the following formula in Google Scripts. What I would like to achieve, is:
1- get Number from A1
2- from Number, have multiple returns
3- set those returns in the same row (A) as original Number, in neighboring cells (A2, A3)
What it looks like now:
function GETALLTWO(bid) {
if (input.map) {
return input.map(GETALLTWO)
} else {
return input;
}
var api_str = "client_id=randomstringofnumbers&client_secret=anotherrandomstringofnumbers";
var url= "https://api.untappd.com/v4/beer/info/" + bid + "?" + api_str;
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() == 200) {
var respObj = JSON.parse(response.getContentText());
var beer = respObj.response.beer;
if (beer.bid == bid) {
return beer.beer_name;
return beer.rating_score;
return beer.stats.total_user_count;
return beer.rating_count;
return beer.stats.monthly_count;
return beer.created_at;
}
}
}
From Code.gs, I can get the first Return to work, but am I combining the different functions correctly? And how would I set the location to return?
Hope someone can help, would love to learn more about scripting.
// Edit for future reference:
function getAll(bid) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Overview')
var row=sh.getActiveCell().getRow();
var bid=sh.getRange(row,3).getValue();
var api_str = "client_id=randomstring&client_secret=randomstring";
var url= "https://api.untappd.com/v4/beer/info/" + bid + "?" + api_str;
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() == 200) {
var respObj = JSON.parse(response.getContentText());
var beer = respObj.response.beer;
if (beer.bid == bid) {
var rObj= {name:beer.beer_name,rating:beer.rating_score,totalcount:beer.stats.total_user_count,ratingcount:beer.rating_count,monthlycount:beer.stats.monthly_count,createddate:beer.created_at};
values=[[rObj.name,rObj.ratingcount,rObj.rating,rObj.totalcount,rObj.monthlycount,rObj.createddate]];
return values;
}
}
}
With this function you just need to put your cursor on the row that you want to get the bid from. It will put the data back in that row starting at column D
function getAllTwo() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Your Sheet Name')
var row=sh.getActiveCell().getRow();
var bid=sh.getRange(row,3).getValue();
var api_str = "client_id=randomstringofnumbers&client_secret=anotherrandomstringofnumbers";
var url= "https://api.untappd.com/v4/beer/info/" + bid + "?" + api_str;
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() == 200) {
var respObj = JSON.parse(response.getContentText());
var beer = respObj.response.beer;
if (beer.bid == bid) {
var rObj= {name:beer.beer_name,rating:beer.rating_score,totalcount:beer.stats.total_user_count,ratingcount:beer.rating_count,monthlycount:beer.stats.monthly_count,createdate:beer.created_at};
values=[[rObj.name,rObj.ratingcount,rObj.rating,rObj.totalcount,rObj.monthlycount,rObj.createddate]];
sh.getRange(row,4,values.length,values[0].length).setValues(values);
}
}
}

combine two array as key value pair

I have two array as follows
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
I want to combine these two array and covert it to the following format
var data={
"booktitle":"testtitle",
"bookid":"testid",
"bookauthor":"testauthor"
}
I want to insert this data to database using nodejs
var lastquery= connection.query('INSERT INTO book_tbl SET ?',data, function (error, results, fields) {
if (error) {
res.redirect('/list');
}else{
res.redirect('/list');
}
});
Please help me to solve this.
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
var finalObj = {};
field_array.forEach(function (eachItem, i) {
finalObj[eachItem] = data_array[i];
});
console.log(finalObj); //finalObj contains ur data
You also can use reduce() in a similar way:
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
var result = field_array.reduce((acc, item, i) => {
acc[item] = data_array[i];
return acc;
}, {});
console.log(result);
Here I explaned my code line by line..Hope it will help
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
//Convert above two array into JSON Obj
var jsondata = {};
field_array.forEach(function (eachItem, i) {
jsondata[eachItem] = data_array[i];
});
//End
//Store Jsondata into an array according to Database column structure
var values = [];
for (var i = 0; i < jsondata.length; i++)
values.push([jsondata[i].booktitle, jsondata[i].bookid, jsondata[i].bookauthor]);
//END
//Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
connection.query('INSERT INTO book_tbl (booktitle, bookid, bookauthor) VALUES ?', [values], function(err, result) {
if (err) {
res.send('Error');
}
else {
res.send('Success');
}
//END

Syntax Error: Token 'undefined' not a primary expression at column null of the expression [xx] starting at [xx%]

I have a sorting function. This function does not work if column name contains %.
For example columnName == "calldrop" my function works but columnName == "calldrop%" my function does not work and I get this error :
Syntax Error: Token 'undefined' not a primary expression at column null of the expression [RABPSHSDPAdrop%] starting at [RABPSHSDPAdrop%].
I dont know why.
$scope.applySorting = function (query, data) {
var orderArray = query.sorting;
// sortingArray == RABPSHSDPAdrop%
var sortingArray = $.Enumerable.From(orderArray).Select(function (item) { return item.replace('data.', ''); }).ToArray();
var sortedData = $.Enumerable.From($filter('orderBy')(data, sortingArray)).ToArray(); //broken here
return sortedData;
};
How can fix this case ?
Please.
I edited this part and its work :
var sortingArray = $.Enumerable.From(orderArray).Select(function (item) { return item.replace('data.', '\'') + "'"; }).ToArray();
You have to use this : ''

angular js variable not work

index.html
<div class="test" ng-controller="Ctrl">
<button ng-click="removeTask(10);">remove</button>
<div>
app.js
app.controller('Ctrl', function($scope) {
$scope.removeTask = function(taskId) {
alert("Task Id is " + taskId);
};
var statement = "";
db.transaction(function (tx) {
//tx.executeSql('DROP TABLE IF EXISTS test_table');
statement = "select * from objects where o.TYPES=' + taskId' GROUP BY objectid";
The alert message work perfectly, but when I try to use the variable taskId on select statement it does not work.
app.controller('Ctrl', function($scope) {
$scope.removeTask = function(taskId){
alert("Task Id is "+taskId);
$scope.taskId = taskId;
};
var statement = "";
db.transaction(function (tx) {
//tx.executeSql('DROP TABLE IF EXISTS test_table');
statement = "select * from objects where o.TYPES='+$scope.taskId+' GROUP BY objectid";
Note that you must assign the task id to a scope variable to use it later.
You need to make the db transaction inside the function.
app.controller('Ctrl', function($scope) {
var statement = "";
$scope.removeTask = function(taskId) {
alert("Task Id is " + taskId);
db.transaction(function (tx) {
//tx.executeSql('DROP TABLE IF EXISTS test_table');
statement = "select * from objects where o.TYPES='+taskId' GROUP BY objectid";
};
};
Function arguments such as taskId are available only inside the function.

Resources