update table when row value is not equal to specific value - mysql

I have a object like this
{ emId: '1', emEmail: 'sreepurna#xxx.com' }
I am using nodejs at backend and mysql for database. I want to update table only when my value is not equal to specific value. Is there any possibility to write this within a query.
I tried the few sql statements but it doesnt work:
let sql = `UPDATE details SET name = CASE WHEN '${req.body.emName}' != 'hi' THEN ${req.body.emName} END where id=${req.body.emId}`;

There is not such a thing called undefined inside the SQL language, you have to validate your values via JavaScript
if(req.body.emName){
// This code block will run when req.body.emName contains value and is not undefined or null
let sql = `UPDATE details SET name = CASE WHEN '${req.body.emName}' THEN ${req.body.emName} END where id=${req.body.emId}`;
}else{
// req.body.emName is either empty/undefined or null
// ...
}

Related

How to use placeholders while inserting data in MySql database using nodejs?

let r={ email:faker.internet.email() } ;
connection_var.query("insert into users set ?",r, function(err,res){
if(err) throw err;
console.log(res);
} );
connection_var.end();
I wrote this code to insert a fake email addr in already existing database and into the users table just the problem is I am not fully able to understand what and how does the " SET ?" work and how is it relating to r and what if r has more than 1 key-value pairs
? is a placeholder. It gets replaced with all the keys and values in the object passed as the next argument. So if you have
let r = {col1: 1, col2: "abc", col3: 999};
the query will become
insert into users set col1 = 1, col2 = 'abc', col3 = 999
You have 2 separated things here
First is the SET clause (for the insert) that from the documentation:
A SET clause indicates columns explicitly by name, together with the value to assign each one.
link: https://dev.mysql.com/doc/refman/8.0/en/insert.html
The other part is the ? the according to the documentation of mysqljs:
... you can use ? characters as placeholders for values you would like to
have escaped
link: https://github.com/mysqljs/mysql
So, the SET indicates the assignment list of the insert and the ? escapes the values.

How can I pass a returned VARCHAR from a SELECT statement in a stored procedure?

Relevant code:
SELECT `startdate`, `problem`
INTO tktCompletedDate, problem
FROM servicerequest
WHERE (requestID = tktRequestID);
CASE problem
WHEN "Screen is broken" THEN
SET tktProbSpec = 'installed replacement screen';
ELSE SET tktProbSpec = 'Ran Diagnostics';
END CASE;
Trying to complete a class assignment (big surprise) and when I run this SELECT is returns the startdate and passes it into tktCompletedDate variable no problem, but the problem field does not get passed. When I check it later it says the value is NULL.

How do I set the placeholder for `knex`'s` raw` method to null?

I tried invoke bulk update query on mysql using knex raw method.
const ids:number[] = [1,2,3];
const values:string[] = ['apple', null, "orange"]
knex('testtable').raw(
`
UPDATE
TEST_TABLE
SET
COL1 = ELT(FIELD(id, :searchIds), :searchValues),
UPDATE_DATE = NOW()
WHERE ID IN (:searchIds)
`,
{ searchIds: ids, searchValues: values },
);`enter code here`
However, the intended result was not obtained.
This is because values contains a string and null, but theraw method's placeholders do not allow nulls.
Please tell me ,How do I set null to placeholder?
Binding array of values in knex doesn't work like that. SQL has multiple type of arrays, so those cannot be mapped to SQL unambiguous manner.
In docs: https://knexjs.org/#Raw-Bindings is an example how to pass arrays of values to knex.
const myArray = [1,2,3]
knex.raw(
`select * from users where id in (${myArray.map(() => '?').join(',')})`,
[...myArray]
);
In this case using named bindings pretty much impossible (actually named bindings are converted to positional bindings inside knex so there wont be even performance hit because of that).

PDO prepared statements increment/decrement by bool

In my POST file, I need to change the order of my items. I basically send a parameter called moveDown which is a bool, to check whether the item is higher or lower. So, I got this to get my parameter:
$moveDown = filter_input(INPUT_POST, 'moveDown', FILTER_VALIDATE_BOOLEAN);
I got another parameter for the item id. This is just a simple filter_input, nothing special.
$itemId = filter_input(INPUT_POST, 'itemId', FILTER_SANITIZE_NUMBER_INT);
Now, I need to use that variable to define whether to increment or decrement the order column. So I tried this:
$changeOrderStmt = $cmsDbh->prepare('UPDATE `items` SET `order` = ? WHERE `id` = ?');
$changeOrderStmt->execute(array('`order` ' . ($moveDown ? '+' : '-') . ' 1', $itemId));
However, now the order column is 0. I really don't want to concatenate the query string and rather use PDO params. Is this possible or not?

Can any one provide me LINQ to update data inside xml column?

I have a table Table1 has columns ID (int) and XMLTEXT of xml type
Can any one provide me LINQ query which is equivalent to below sql query
Update Table1 set XMLTEXT .modify('delete (/root/child1/child2)')
where ID=1001
In Linq2SQL, something like this should work.
long ProductID = 1;
ORM.Table1 p = context.Table1s.Where(o => o.ID == ProductID).FirstOrDefault();
if(p != null) {
p.XMLTEXTe.Element("child2").Remove();
// Need to do this so Linq picks up on the data change
// as it doesnt implement the correct XElement data changed event handler
// and thus won't submit the changes made if you dont do the reassignment!
p.XMLTEXT = new XElement(p.XMLTEXT);
context.SubmitChanges();
}