Array in sql statement not working with placeholder ?nodejs - javascript

sql query does not accept array as value when it is used in a placeholder, It only returns one result even though result is greater than 1. Not using a placeholder and withouting escaping it works perfectly returns the right amount of results.
//works
SELECT * FROM users WHERE userId IN (" + followerIds.join() + ");";
//does not work
SELECT * FROM users WHERE userId IN (?);";
con.query(queryFollowerstTable, [followeringIsd.join()],function(err,result)..

All I had to do was parse followerIds.join() to an int and It worked.
followerIdsParsed = followerIds.join().split(',').map(Number);
followingIdsParsed = followingIds.join().split(',').map(Number);
var queryFollowerstTable = "SELECT * FROM users WHERE userId IN (?); SELECT *
FROM users WHERE userId IN (?);";
con.query(queryFollowerstTable, [followerIdsParsed, followingIdsParsed],
function(err, result) {..

Change
con.query(queryFollowerstTable, [followeringIds.join()],function(err,result)
to
con.query(queryFollowerstTable, followeringIds.join(),function(err,result)
In your original example:
SELECT * FROM users WHERE userId IN (" + followerIds.join() + ");";
You are passing in a string not an array

Related

Dynamic SQL using Snowflake SQL Stored Procedure

I want to be able to update rows of data in a set list of tables for certain columns within those tables.
Basically something like this;
TABLE_NAME COL1
TABLE1 NAME
TABLE2 ADDRESS
select * from TABLE1;
Aidan
Select * from TABLE2;
Ireland
So something like the query below as a stored procedure that would gather all the tables and columns to be altered and update the records accordingly.
update $TABLE_NAME set $COL1 ='*' where ID in (select ID FROM EXTERNAL_TABLE)
Any help greatly appreciated.
Tried messing around with this sample but got nowhere when I try build on it
CREATE OR REPLACE PROCEDURE DATA_MASKING("P_TABLE_NAME" VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS '
// Define query String
var sql_command = "UPDATE " + P_TABLE_NAME + " SET IND_ADDR1 = NULL;"
//Prepare SQL statement
var stmt = snowflake.createStatement({sqlText: sql_command});
//Execute SQL Statement
var rs = stmt.execute();
return ''Table truncated successfully.''
';
call PERSISTENT_DATA_MASKING('TEST_TABLE');
The Proc you had given works. Just needs few amends which you must have been able to do. So, not sure what exactly is the question.
CREATE OR REPLACE PROCEDURE DATA_MASKING("P_TABLE_NAME" VARCHAR(16777216), "P_COLUMN_NAME" VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS '
// Define query String
var sql_command = "UPDATE " + P_TABLE_NAME + " SET " + P_COLUMN_NAME + " = ''x'';"
//Prepare SQL statement
var stmt = snowflake.createStatement({sqlText: sql_command});
//Execute SQL Statement
var rs = stmt.execute();
return ''successful''
';
CALL DATA_MASKING('SCHEMA.TABLE_NAME','COLUMN_NAME');
SELECT * FROM SCHEMA.TABLE_NAME;

SQL assign infinite params

Usually we will use SQL queries like below, we will pass params with predifined number $1
queryRunner.query('SELECT * FROM sample_data WHERE code IN ($1)', ['1'])
But I want to pass multiple params without predifined $1. Any way to resolve this?
queryRunner.query('SELECT * FROM sample_data WHERE code IN ($$)', ['1','2','3'])
One approach dynamically builds the IN clause based on the expected number of parameters. Consider:
var params = ['1','2','3'];
var inClause = '?' + ', ?'.repeat(params.length - 1);
var sql = 'SELECT * FROM sample_data WHERE code IN (' + inClause + ')';
console.log(sql);
Once we have a statement with the right number of placeholders, we can simply bind the collection or array with no trouble.

Ignore Case sql query

I am trying to basically ignore the case sensitivity for my db2 sql select * query, so that I can populate the products to my catalogue page. Ex. If I type in my search bar 'squeege', I want the item 'Squeege' to populate, even if there is a difference in Upper/lower case. What is the best way to do this, based on the code I have below?
var searchProduct = "select * from LISTOFPRODUCTS where ITEM LIKE '%" + searchValue + "%'"
Thanks in advance for the help :)
I think this could work:
var searchProduct = "select * from LISTOFPRODUCTS where UPPER(ITEM) LIKE UPPER('%" + searchValue + "%'")
Also the same with LOWER()
Note that the trick is parse both values to UPPER() or LOWER() to match them.
You can use the function LOWER().
For example:
var searchProduct = "select * from LISTOFPRODUCTS where LOWER(ITEM) LIKE '%" + searchValue + "%'"
You can also consider using REGEXP_LIKE which has a case-insensitive option i

How to use IN with a query parameter?

I have a query like this.
SELECT * FROM player_details where name in ('messi','neymar','suarez','alves')
I want to execute this query in titanium.
I tried like this
var in = ['messi','neymar','suarez','alves'];
db.execute('SELECT * FROM player_details where name in ?',in);
But above code producing error.
How can i add IN and NOT IN condition in sqlite in titanium ?
A single parameter ? replaces a single expression.
When you have four values, you need four parameters:
db.execute('SELECT * FROM player_details where name in (?,?,?,?)', in);
If the length of the array is dynamic try something like this:
var params = ["messi", "neymar", "suarez", "alves"],
qMarks = new Array(params.length).join("?,") + "?";
db.execute("SELECT * FROM player_details WHERE name in (" + qMarks + ");", params);

WebSQL: Error processing SQL: number of '?'s in statement string does not match argument count

I want to create a dynamic function to INSERT data into the webSQL Database. I cannot use indexed DB because Zetakey does not support it.
tx.executeSql("INSERT INTO " + table + "(" + formatfields + ")
VALUES (" + formatqm + ")",
[formatvalues],
webdb.onSuccess,
webdb.onError);
Ich übergebe an den Query:
formatfields = "one, two"; (up to an undefined number)
formatqm = "?, ?";
formatvalues = "123, 456"; (dynamic user entries for x fields)
Can someone tell me what do I have to do with the formatvalues? When I write 123, 456 directly its working fine.
Thanks in advance!
Instead of dynamically create or change table column fields, use JSON serialization of the record. Basically store stringify user given object data on INSERT and parse on retrieval. If you need query over column, initialize those columns only. It will be just like IndexedDB does.
/*array.push */
formatvalues = new Array;
formatvalues.push("123");
and so on!

Categories