I am trying to write an SQL query that will update an entry if it exists and insert a new one if it does not exist. The UPDATE ON DUPLICATE KEY option doesn't work because I am not querying by the primary key. The SQL statement I am referring to is in the sql.query() function below. I have also added the error message.
Asset.create = (newAsset, result) => {
sql.query(
`if exists(SELECT * from asset WHERE
AssetId="${newAsset.AssetId}" AND
AccountID="${newAsset.AccountId}") BEGIN UPDATE asset set
Amount="${newAsset.Amount}" where AssetId="${newAsset.AssetId}"
AND AccountID="${newAsset.AccountId}" End else begin INSERT
INTO asset SET ? end`,
newAsset,
(err, res) => {
if (err) {
console.log("error", err);
result(err, null);
return;
}
result(null, { id: res.insertId, ...newAsset });
}
);
};
Error message:
sqlMessage: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if exists(SELECT * from asset WHERE AssetId="bitcoin" AND AccountID="2c341fed-cf' at line 1
,