Update table based on criteria from a second table - db2

I am trying to update one table based on selection criteria from another table. My SQL is
update
hshed
set
oaeiin = 'Y',
OAEIND = '170201'
from
hshed
join cusms on oacono = cmcono
and oacsno = cmcsno
where
cmtpid like 'OB10%'
and oainvd > 180120
and oaeiin = 'N'
However, I am getting an error that
Keyword FROM not expected. Valid tokens: USE SKIP WAIT WITH WHERE.
I am not sure how to update a table based on criteria from a second table, or how to use joins. This is using SQL in a DB2 database.
I have tried searching for a solution with no success.
Any assistance is appreciated.

I think the main issue here is that DB2 does not support the update join syntax you are using. One possible workaround might be to use EXISTS clauses to handle the same logic you intend:
UPDATE
hshed
SET
oaeiin = 'Y',
OAEIND = '170201'
WHERE
EXISTS (SELECT 1 FROM cusms WHERE oacono = cmcono) AND
EXISTS (SELECT 1 FROM cusms WHERE oacsno = cmcsno) AND
cmtpid LIKE 'OB10%' AND
oainvd > 180120 AND
oaeiin = 'N';
Here is a link to a good Stack Overflow question discussing this problem in general.

Related

Postgres - Pull results from multiple tables based on declared variable

I am new to Postgres. I have 7 tables that have a common field (AcctID). I would like to pull results from each of the tables (without joining) based on the AcctID that I set (e.g. AcctID = '2352').
DO $$
Declare
AcctID := '2352';
BEGIN
Select * from pbx.users where acct = AcctID;
Select * from pbx.transactions where acct = AcctID;
Select * from pbx.logs where acct = AcctID;
....
END;
$$;
I get error message that query has no destination. Any recommendation is greatly appreciated.
The error message is essentially telling you: "okay, so you want to pull these results, but then what?"
It is unclear to me why a join is inadequate for you, it would make things so much easier.
For this purpose, you can create a stored procedure, using a composite out parameter, such as the one proposed as an answer to this question: Composite Array Type as OUTPUT parameter in PostgreSQL
Yet, instead of that I really recommend the use of joins, such as
Select *
from pbx.users
join pbx.transactions on pbx.users.acct = '2352' and pbx.users.acct = pbx.transactions.acct
join pbx.logs on pbx.transactions.acct = pbx.logs.acct;

How can I get update rows with mybatis?

If I use mybatis, I can easily get the count of updated rows, just like
update table set desc = 'xxx' where name = ?
However, if I want to get the updated rows, not the count, how can I achieve this by mybatis?
mybatis itself can't do that because this update happens in database and no row data is returned back.
The only option is to modify the query and make it update and select the data you need. The exact way how to achieve this effect depends on the database you are using and/or driver support.
In postgres for example you can change the query and add RETURNING clause like this:
UPDATE table
SET desc = 'xxx'
WHERE name = ?
RETURNING *
This will turn this query to a select one and you can map it as select query in mybatis. Some other databases have similar features.
Another option (if you database and/or JDBC driver support this) is to do two queries, update and select like this
<select id='updateAndReturnModified" resultMap="...">
UPDATE table
SET desc = 'xxx'
WHERE name = #{name};
SELECT *
FROM table
WHERE name = #{name};
</select>
This however may require to use more strict isolation level (READ_COMMITED for example will not work) to make sure the second select sees the state after update and does not see changes made by some concurrent update. Again whether you need this or not depends on the database your are using.

SQL Injection : Syntax error

I have an essay on SQL injection ( what it is - how its done and how can it be avoided ). I get what it is and how it works. But i dont seem to be able to reproduce an injection on my database.
I made a pretty simple database ,using mysql workbench, meant for a video club. movies - stock - price - customers shopping cart etc.
I also made a pretty simple html page from which i can add movies - view what i have in stock etc.
So i have a txt field in which i enter a movie name and i get back some info for this specific movie.
The code that gets the name i type and makes the query is ::
$name = $_POST ['txtfld'];
$sql = ("SELECT * FROM test_table WHERE adad = '$Mname'");
if ($result = mysqli_query($dbc,$sql))
Now when i give 'a' as an input everything works as expected. I get back the one entry that has pk equal to [a].
Query becomes :: SELECT * FROM test_table WHERE adad= 'a'.
Next step was to see if i can get the whole table or some random entry from it.
Input was : [ a' OR 'x'='x ]
Query becomes :: SELECT * FROM test_table where adad = ' a' OR 'x' = 'x '
Everything works as expected and i get back the whole table contents.
Next step was to try inject a second query. I tried to update the test_table.
Input was :: [ a;' update test_table set asda = '123456' where adad = 'u ]
Query now becomes :: SELECT * FROM test_table WHERE adad= ' a;' UPDATE test_table SET asda ='123456' WHERE adad = 'u '
I got a syntax error so i tried every syntax i could think of including
[ a;' UPDATE test_table SET asda = '123456' where adad = 'u';# ]
. None of them worked.
Thing is, i dont really get why i get a syntax error.
For the input given above mysqli_error returns this message
error: 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 'update test_table set asda =
'123456' where adad = 'u'' at line 1
while an echo i inserted returns this
SELECT * FROM test_table WHERE adad = 'a;' UPDATE test_table SET asda = '123456' WHERE
adad = 'u'
I dont see any syntax error in the echo return and i dont get where the second [ ' ] character in the end of the mysqli_error return, comes from.
From what i understand this is rather a failure in executing a second query ( no matter what the query is - drop, insert, update )
Do i miss something?
Thanks in advance.
Michael.
mysql's PHP driver does NOT allow multiple queries in a single ->query() call, exactly for this reason. It's an anti-injection defense, to prevent the classic Bobby Tables attack. This true for all PHP db interfaces (mysql, mysqli, pdo), as they all use the same underlying mysql C api library to actually talk to the db. Any attempt to run 2+ queries in a single query call results in the syntax error.
Note that it does NOT protect against your ' or 1=1 injection, however.
In order for your stacked query injection technique to work, you will need to use the "mysqli_multi_query()" function:
http://php.net/manual/en/mysqli.multi-query.php
http://www.websec.ca/kb/sql_injection#MySQL_Stacked_Queries
MsSQL is the only database that supports stacked queries by default.
Also possibly a better injection technique, and a more reliable one, would be a UNION attack, and then dump the MySQL credentials from the "mysql.user" table, then use these to compromise the database.

Getting Affected Rows by UPDATE statement in RAW plpgsql

This has been asked multiple times here and here, but none of the answers are suitable in my case because I do not want to execute my update statement in a PL/PgSQL function and use GET DIAGNOSTICS integer_var = ROW_COUNT.
I have to do this in raw SQL.
For instance, in MS SQL SERVER we have ##ROWCOUNT which could be used like the following :
UPDATE <target_table>
SET Proprerty0 = Value0
WHERE <predicate>;
SELECT <computed_value_columns>
FROM <target>
WHERE ##ROWCOUNT > 0;
In one roundtrip to the database I know if the update was successfull and get the calculated values back.
What could be used instead of '##ROWCOUNT' ?
Can someone confirm that this is in fact impossible at this time ?
Thanks in advance.
EDIT 1 : I confirm that I need to use raw SQL (I wrote "raw plpgsql" in the original description).
In an attempt to make my question clearer please consider that the update statement affects only one row and think about optimistic concurrency:
The client did a SELECT Statement at first.
He builds the UPDATE and knows which database computed columns are to be included in the SELECT clause. Among other things, the predicate includes a timestamp that is computed each time the rows is updated.
So, if we have 1 row returned then everything is OK. If no row is returned then we know that there was a previous update and the client may need to refresh the data before trying to update clause again. This is why we need to know how many rows where affected by the update statement before returning computed columns. No row should be returned if the update fails.
What you want is not currently possible in the form that you describe, but I think you can do what you want with UPDATE ... RETURNING. See UPDATE ... RETURNING in the manual.
UPDATE <target_table>
SET Proprerty0 = Value0
WHERE <predicate>
RETURNING Property0;
It's hard to be sure, since the example you've provided is so abstract as to be somewhat meaningless.
You can also use a wCTE, which allows more complex cases:
WITH updated_rows AS (
UPDATE <target_table>
SET Proprerty0 = Value0
WHERE <predicate>
RETURNING row_id, Property0
)
SELECT row_id, some_computed_value_from_property
FROM updated_rows;
See common table expressions (WITH queries) and depesz's article on wCTEs.
UPDATE based on some added detail in the question, here's a demo using UPDATE ... RETURNING:
CREATE TABLE upret_demo(
id serial primary key,
somecol text not null,
last_updated timestamptz
);
INSERT INTO upret_demo (somecol, last_updated) VALUES ('blah',current_timestamp);
UPDATE upret_demo
SET
somecol = 'newvalue',
last_updated = current_timestamp
WHERE last_updated = '2012-12-03 19:36:15.045159+08' -- Change to your timestamp
RETURNING
somecol || '_computed' AS a,
'totally_new_computed_column' AS b;
Output when run the 1st time:
a | b
-------------------+-----------------------------
newvalue_computed | totally_new_computed_column
(1 row)
When run again, it'll have no effect and return no rows.
If you have more complex calculations to do in the result set, you can use a wCTE so you can JOIN on the results of the update and do other complex things.
WITH upd_row AS (
UPDATE upret_demo SET
somecol = 'newvalue',
last_updated = current_timestamp
WHERE last_updated = '2012-12-03 19:36:15.045159+08'
RETURNING id, somecol, last_updated
)
SELECT
'row_'||id||'_'||somecol||', updated '||last_updated AS calc1,
repeat('x',4) AS calc2
FROM upd_row;
In other words: Use UPDATE ... RETURNING, either directly to produce the calculated rows, or in a writeable CTE for more complex cases.
Generally the answer to this question depends on the type of the driver used.
PQcmdTuples() function does what is needed, if the application uses libpq. Other libraries on top of libpq need to have some wrapper on top of this function.
For JDBC the Statement.executeUpdate() method seems to the job.
ODBC provides SQLRowCount() function for the similar purpose.

How to select and delete at once in DB2 for the queue functionality

I am trying to implement simple table queue in DB2 database. What I need
is to select and delete the row in the table at once so the multiple clients will not get the same row from the queue twice. I was looking for similiar questions but they describes the solution for another database or describes quite complicated solutions. I only need to select and delete the row at once.
UPDATE: I found on the web db2 clause like this, which look exactly like what i need - the select from delete: example:
SELECT * FROM OLD TABLE (DELETE FROM example WHERE example_id = 1)
but I am wondering if this statement is atomic if the two concurent request don't get the same result or delete the same row.
Something like this:
SELECT COL1, COL2, ... FROM TABLE WHERE TABLE_ID = value
WITH RR USE AND KEEP EXCLUSIVE LOCKS;
DELETE FROM TABLE WHERE TABLE_ID = value;
COMMIT;
If you're on DB2 for z/OS (Mainframe DB2) since version 9.1, or Linux/Unix/Windows (since at least 9.5, search for data-change-table-reference), you can use a SELECT FROM DELETE statement:
SELECT *
FROM OLD TABLE
(DELETE FROM TAB1
WHERE COL1 = 'asdf');
That would give you all the rows that were deleted.
Edit: Ooops, just saw your edit about using this type of statement. And as he said in the comment, two separate application getting the same row depends on your Isolation Level.