How to update all columns at once in Mysql - mysql

There is a database with 200 columns, how to update data from 21 to 200, not in this way -
Set Column21 = NEW.Column21,
Column22 = NEW.Column22,
Column23 = NEW.Column23,
Column24 = NEW.Column24,
Column25 = NEW.Column25...

//You can loop through 22 to 200 and make the string or access property
let sql = "Set",i=22;
[...Array(179)].forEach((_, l) => {
let column = 'Column'+i;
let val = "some val"; //access value
sql += ` ${column} = ${val} `;
i++;
});
console.log(sql);

Related

Using custom date format

I have this working script to sent mails with data from a Google sheet:
function SendEmail() {
let timestamp = 0
let poid = 1
let sku = 2
let qty = 3
let description = 4
let licenseid = 5
let itcost = 6
let total = 7
let company = 8
let contact = 9
let contactmail = 10
let endusermail = 11
let address = 12
let country = 13
let status = 14
let suppliermail = 15
let currency = 16
let otherinfo = 17
let brand = 18
let comment = 19
let cc = 20
let emailTemp = HtmlService.createTemplateFromFile("MAIL")
let ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA")
let sd = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA2")
let data = ws.getRange("A2:V" + ws.getLastRow()).getValues()
let sData = sd.getRange("B2:J" + sd.getLastRow()).getValues()
let sInfo = sData.map(function (r) { return r[0] })
data = data.filter(function (r) { return r[14] == 'SENTNOW' })
if (data.length) {
let found = false
data.forEach(function (row) {
emailTemp.ts = row[timestamp].toLocaleString("da-DK")
emailTemp.po = row[poid]
emailTemp.co = row[contact]
emailTemp.cm = row[company]
emailTemp.ad = row[address]
emailTemp.cu = row[country]
emailTemp.cn = row[contactmail]
emailTemp.sk = row[sku]
emailTemp.de = row[description]
emailTemp.qt = row[qty]
emailTemp.it = (row[itcost]).toLocaleString("da-DK")
emailTemp.to = (row[total]).toLocaleString("da-DK")
emailTemp.ce = row[comment]
emailTemp.cy = row[currency]
emailTemp.eu = row[endusermail]
emailTemp.li = row[licenseid]
emailTemp.ot = row[otherinfo]
let indexSupp = sInfo.indexOf(row[15])
if (indexSupp > -1) {
//only change status if supplierdata email is found
found = true
emailTemp.spname = sData[indexSupp][1]
emailTemp.saddress1 = sData[indexSupp][2]
emailTemp.saddress2 = sData[indexSupp][3]
emailTemp.scountry = sData[indexSupp][4]
emailTemp.sterms = sData[indexSupp][5]
emailTemp.scurrency = sData[indexSupp][6]
emailTemp.sothers = sData[indexSupp][7]
emailTemp.vat = sData[indexSupp][8] * 100
emailTemp.totvat = (row[total] * sData[indexSupp][8]).toLocaleString("da-DK")
emailTemp.totandvat = (row[total] + (row[total] * sData[indexSupp][8])).toLocaleString("da-DK")
let subjectLine = "Subject line # " + row[poid]
let htmlMessage = emailTemp.evaluate().getContent()
//only send email if supplierdata email is found
try {
GmailApp.sendEmail(
row[suppliermail],
subjectLine,
"",
{ name: 'Name', htmlBody: htmlMessage, bcc: 'myemail#domain.com' })
}
catch (err) {
SpreadsheetApp.getUi().alert(err)
}
}
})
if (found) {
let sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA")
.getRange('O2:O')
.createTextFinder('SENTNOW')
.replaceAllWith('SENT')
}
}
}
Only problem is the date format emailTemp.ts = row[timestamp].toLocaleString("da-DK")
This give output date-format "11.2.2022 06.00.00" within the e-mail sent to the reciever.
What I wish is the date to be just "02/11/2022"
I tried emailTemp.ts = row[timestamp].toLocaleString("da-DK").getDisplayValue() but that was not working.
Any suggestions ?
You're going to have to figure out your time zone but try this.
emailTemp.ts = Utilities.formatDate(row[timestamp],"GMT","dd/MM/yyyy");
Reference
Utilities.formatDate()

Index Match Large Array Google Script Taking Very Long

I have the function below where I am trying to scrape 4 websites, and then combine the results into a spreadsheet. Is there a faster way to match over a large array that isn't the INDEX/MATCH formulas. My desired output would be (obv this is an example)
MLBID | FG_ID | PA | K | K% | wOBA
12345 | 12345 | 12 | 5 | 41.7% | .300
While the code I have below works, it takes wayyyy too long reaches the 6-minute limit of Google Script. The matching that I am trying to do is with ~4000 rows. I have commented my code as much as possible.
function minors_batting_stats() {
//this is the spreadsheet where I have a list of all of the IDs -- MLB and FG
var ids = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Player List");
//this is the output sheet
var mb18vR_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("2018 minors bat vs R");
//various URLs I am trying to scrape
var mb18vR_PA_url = 'https://www.mlb.com/prospects/stats/search?level=11&level=12&level=13&level=14&level=15&level=16&pitcher_throws=R&batter_stands=&game_date_gt=&game_date_lt=&season=2017&home_away=&draft_year=&prospect=&player_type=batter&sort_by=results&sort_order=desc&group_by=name&min_pa=&min_pitches=#results'
var mb18vR_SO_url = 'https://www.mlb.com/prospects/stats/search?pa_result=strikeout&level=11&level=12&level=13&level=14&level=15&level=16&pitcher_throws=R&batter_stands=&game_date_gt=&game_date_lt=&season=2017&home_away=&draft_year=&prospect=&player_type=batter&sort_by=results&sort_order=desc&group_by=name&min_pa=&min_pitches=#results'
var mb18vR_wOBA_url = 'https://www.mlb.com/prospects/stats/search?level=11&level=12&level=13&level=14&level=15&level=16&pitcher_throws=R&batter_stands=&game_date_gt=&game_date_lt=&season=2017&home_away=&draft_year=&prospect=&player_type=batter&sort_by=woba&sort_order=desc&group_by=name&min_pa=&min_pitches=#results'
//creating an array for each scrape
var res = [];
var res1 = [];
var res2 = [];
var res3 = [];
//getting the MLB and FG ids from the spreadsheet
var mlbids = ids.getRange(1, 11, ids.getLastRow()).getValues();
var fgids = ids.getRange(1,9, ids.getLastRow()).getValues();
//scraping SO against RHP
var content_SO = UrlFetchApp.fetch(mb18vR_SO_url).getContentText();
var e_SO = Parser.data(content_SO).from('tbody').to('</tbody>').build();
var rows_SO = Parser.data(e_SO).from('<tr class="player_row"').to('</tr>').iterate();
for (var i=0; i<rows_SO.length; i++) { //rows.length
res1[i] = [];
res1[i][0] = Parser.data(rows_SO[i]).from('/player/').to('/').build();
var SOs = Parser.data(rows_SO[i]).from('<td align="left">').to('</td>').iterate();
res1[i][1] = SOs[1];
}
//scraping wOBA against RHP
var content_wOBA = UrlFetchApp.fetch(mb18vR_wOBA_url).getContentText();
var e_wOBA = Parser.data(content_wOBA).from('tbody').to('</tbody>').build();
var rows_wOBA = Parser.data(e_wOBA).from('<tr class="player_row"').to('</tr>').iterate();
for (var i=0; i<rows_wOBA.length; i++) { //rows.length
res2[i] = [];
res2[i][0] = Parser.data(rows_wOBA[i]).from('/player/').to('/').build();
var wOBAs = Parser.data(rows_wOBA[i]).from('<td align="left">').to('</td>').iterate();
res2[i][1] = wOBAs[2];
}
//scraping PA against RHP
var content = UrlFetchApp.fetch(mb18vR_PA_url).getContentText();
var e = Parser.data(content).from('tbody').to('</tbody>').build();
var rows = Parser.data(e).from('<tr class="player_row"').to('</tr>').iterate();
for (var i=0; i<rows.length; i++) { //rows.length
res[i] = [];
res[i][0] = Parser.data(rows[i]).from('/player/').to('/').build();
res[i][1] = [];
//matching the MLB_ID with FG_ID
var mlbID = res[i][0];
for(var j = 0; j<mlbids.length;j++){
if(mlbids[j] == mlbID){
res[i][1] = fgids[j];
}
}
var PAs = Parser.data(rows[i]).from('<td align="left">').to('</td>').iterate();
res[i][2] = PAs[1];
//matching the MLB_ID from PA (res) with SO (res1)
res[i][3] = 0;
for (var w=0; w<res1.length; w++) {
if (res[i][0] == res1[w][0]) {
res[i][3] = res1[w][1];
}
}
//Calculating K%
res[i][4] = res[i][3] / res[i][2]
//matching the MLB_ID from PA (res) with wOBA (res1)
res[i][5] = 0;
for (var v=0; v<res2.length; v++) {
if (res[i][0] == res2[v][0]) {
res[i][5] = res2[v][1];
}
}
}
//pasting values
mb18vR_sheet.getRange(2, 1, res.length, res[0].length).setValues(res);
}
The issue you have is that you are forcing your script to loop through large datasets many many times for each row of compared data. A better approach is to build a lookup object, which maps between a desired unique identifier and the row of the data array you want to access:
/* Make an object from an Array[][] that has a unique identifier in one of the columns.
* #param Array[][] data The 2D array of data to index, e.g. [ [r1c1, r1c2, ...], [r2c1, r2c2, ...], ... ]
* #param Integer idColumn The column in the data array that is a unique row identifier
e.g. the column index that contains the product's serial number, in a data
array that has only a single row per unique product.
#return Object {} An object that maps between an id and a row index, such that
`object[id]` = the row index for the specific row in data that has id = id
*/
function makeKey(data, idColumn) {
if(!data || !data.length || !data[0].length)
throw new ValueError("Input data argument is not Array[][]");
// Assume the first column is the column with the unique identifier if not given by the caller.
if(idColumn === undefined)
idColumn = 0;
var key = {};
for(var r = 0, rows = data.length; r < rows; ++r) {
var id = data[r][idColumn];
if (key[id])
throw new ValueError("ID is not unique for id='" + id + "'");
key[id] = r;
}
return key;
}
Usage:
var database = someSheet.getDataRange().getValues();
var lookup = makeKey(database, 3); // here we say that the 4th column has the unique values.
var newData = /* read a 2D array from somewhere */;
for(var r = 0, rows < newData.length; r < rows; ++r) {
var id = newData[r][3];
var existingIndex = lookup[id];
if (existingIndex) {
var oldDataRow = database[existingIndex];
} else {
// No existing data.
}
}
By making a lookup object for your data arrays, you no longer have to re-search them and make comparisons, because you did the search once and stored the relationship, rather than discarding it every time. Note that the key that was made is based on a specific (and unique) property of the data. Without that relationship, this particular indexing approach won't work - but a different one will.

Passing a table as argument to function in Lua

I want to loop through different indexed tables by only passing the initial table as an argument.
I currently have this table:
local table = {
stuff_1 = {
categories = {},
[1] = {
name = 'wui',
time = 300
}
},
stuff_2 = {
categories = {'stuff_10', 'stuff_11', 'stuff_12'},
stuff_10 = {
categories = {},
[1] = {
name = 'peo',
time = 150
},
[2] = {
name = 'uik',
time = 15
},
[3] = {
name = 'kpk',
time = 1230
},
[4] = {
name = 'aer',
time = 5000
}
},
stuff_11 = {
categories = {},
[1] = {
name = 'juio',
time = 600
}
},
stuff_12 = {
categories = {},
[1] = {
name = 'erq',
time = 980
},
[2] = {
name = 'faf',
time = 8170
}
}
}
I wanted to make a recursive function to check if the name in any of those tables was equal to some certain thing and return a string.
The recursivity lies in the idea of updating this table with whatever ammount I'd like (or until a certain limit).
I don't understand exactly what's wrong since when I try:
for k, v in pairs(table) do
print(k, v, #v.categories)
end
It correctly prints:
stuff_2 table: 0x10abb0 3
stuff_1 table: 0x10aab8 0
But when passing the table as a parameter to the the function below, it gives this error:
[string "stdin"]:84: attempt to get length of field 'categories' (a nil value)
Function:
function checkMessage(table)
local i = 1
local message = ""
for k, v in pairs(table) do
if(#v.categories == 0) then
while(v[i]) do
if(v[i].name == 'opd') then
if(v[i].time ~= 0) then
message = "return_1"
else
message = "return_2"
end
end
i = i + 1
end
else
checkMessage(table[k])
end
end
return message
end
EDIT: The problem lies in not ignoring that when using pairs onto the table, this doesn't just have tables with a category subtable but it also has a table named category, if this is ignored then the problem is fixed.
You're recursing into subtables that don't have a categories field. Trying to access categories on them yields nil, which you then try to use the length operator on. Hence your error:
attempt to get length of field 'categories' (a nil value)
If you can't hand trace your app, put in more print statements or get a line level debugger.

Sort object by another object value inside

Here some complication sorting in my application.
Now i have data object is like following(called pCList):
Object[0]:
Id: 1
comp: Test
med: xyz
condition: valueObject.Condition
Object[1]:
Id: 2
comp: Test1
med: pqr
condition: valueObject.Condition
Object[2]:
Id: 3
comp: Test
med: abc
condition: valueObject.Condition
condition VO Have data like:
condition data1:
conId: 001
cond: abcds
condition data2:
conId: 001
cond: trdfd
condition data3:
conId: 001
cond: dsdsds
For normal sorting i will do as following way;
var sort:ISort = new Sort();
var sortField:ISortField = new SortField("med");
sort.fields = [sortField];
if(pCList != null)
{
pCList.sort = sort;
pCList.refresh();
}
In which pcList is sort by med.
But now, I want to sort by condition.cond
like first come which have cond value abcds then dsdsds then trdfd and so on...
I Have tried it using:
var sort:ISort = new Sort();
var sortField:ISortField = new SortField("condition.cond");
sort.fields = [sortField];
But not succeed. Any help is greatly appreciated.
ISort has a property compareFunction, that can be used for custom sorting. See example below.
var sort:ISort = new Sort();
sort.compareFunction = function(a:Object, b:Object, fields:Array = null):int {
var conditionA:String = a.Condition.cond;
var conditionB:String = b.Condition.cond;
if (conditionA < conditionB) {
return -1;
} else if (conditionA > conditionB) {
return 1;
} else {
return 0;
}
};

finding unique names before saving in c# and sql server

i have to handle unique names and save it in db like -
If name already exists, find the smallest number you can append to the name to save it as a unique name.
For example:
If username Scott already exists, save as Scott(1). If Scott(1) already exists, save as Scott(2). Etc.
i am using c# and sql server 2010
any great ideas ?
figured that out - but appreciate improvements
var seprator = "scott";
var list = new List<string>();
list.Add("scott");
list.Add("scott(1)");
list.Add("scott Alex");
list.Add("scott (4)");
list.Add("scott(xxx)");
list.Add("scott(250)");
list.Add("scott(12s)");
list.Add("scott(123)x");
list.Add("Scott caps");
list.Add("Alex Scott caps");
list.Add("xxxscottmmm");
var numberList = new List<int>();
foreach (var v in list)
{
var parts = Regex.Split(v, seprator, RegexOptions.IgnoreCase);
if (parts.Length > 1) //(1) Alex (4) (xxx) (250) (12s) (123)x caps caps
{
var secondPart = parts[1].Trim();
if (secondPart.StartsWith("(") && secondPart.EndsWith(")")) // (1) (4) (xxx) (250) (12s)
{
var valuebetweenbraces = secondPart.Substring(1, secondPart.Length - 2); //1 4 xxx 250 12s
int number;
var isNumber = int.TryParse(valuebetweenbraces, out number);
if (isNumber)
{
numberList.Add(number);
}
}
}
}
int maxValue = 0;
if (numberList.Count > 0)
maxValue = numberList.Max() + 1;
else
maxValue = maxValue + 1;
Response.Write(seprator + "(" + maxValue + ")");