mysql update with if and max - mysql

I have lost hours on this and nothing works for me.
I have filed strp_aa that is default NULL. The filed strp_aa should update only if its null with MAX strp_aa + 1, and if its not null if it already has a number it should stay the same.
short version of code is
UPDATE STRANKEP
SET strp_aa = IF(strp_aa=null, strp_aa+1, strp_aa)
WHERE strp_ID=36;
Also tired
UPDATE STRANKEP
SET strp_aa = IF(strp_aa=null, (SELECT MAX(strp_aa)) +1, (SELECT (strp_aa) WHERE strp_ID=36)
WHERE strp_ID=36;
I tried multiple things like this one mentioned here Update MySQL with if condition:
UPDATE STRANKEP
SET strp_aa = CASE WHEN strp_aa = NULL THEN MAX(strp_aa) + 1 ELSE strp_aa END
WHERE strp_ID = 36;
I have also found this mysql query to update field to max(field) + 1 and tried all sorts of combinations with supplied answer and it wont work for me. One of the version is:
UPDATE STRANKEP
SET strp_aa = IF((SELECT strp_aa )!=null,((SELECT selected_value2 FROM (SELECT (strp_aa) AS selected_value2 FROM STRANKEP WHERE strp_ID=36) AS sub_selected_value2)), ((SELECT selected_value FROM (SELECT MAX(strp_aa) AS selected_value FROM STRANKEP) AS sub_selected_value) + 1) )
WHERE strp_ID=36;
This just keep adding one even if there is a number set on strp_aa...
I don't know what else to try.
EDIT:
Had s little problem with #GMB answer because all fields are starting with NULL, so max(strp_aa) gives 0 results in case none of the fields had a number in it.
I solved that with COALESCE statement and posting it here if someone has similar problem.
UPDATE STRANKEP t
CROSS JOIN (select COALESCE(MAX(strp_aa),0) max_strp_aa from STRANKEP) m
set t.strp_aa = m.max_strp_aa + 1
where t.strp_ID = 36 and t.strp_aa is null

You can use the update ... join syntax for this:
update strankep s
cross join (select max(strp_aa) max_strp_aa from strankep) m
set s.strp_aa = m.max_strp_aa + 1
where s.strp_id = 36 and s.strp_aa is null
The cross join brings the max value of strp_aa over the whole table. The where clause eliminate row(s) where strp_aa is not null.

Related

UPDATE from SELECT but still return selected data in MySQL

I have read a bunch of ways that has gotten me this far. But I can't get to the finish line.
I have a table of coupon codes. I want to use one transaction to select the next available code, mark it as used and input the order number. I can get the update and nested select to work, but I cannot figure out how to actually return the coupon code from the select. It just returns 1 row updated.
Here's what I've got:
UPDATE `prcoupon` pr
SET
`pr`.`status` = '1',
`pr`.`invoicenumber` = '09990002'
WHERE
`pr`.`couponCode` = (SELECT
`prcoupon`.`couponcode`
FROM
`prcoupon`
WHERE
`status` = 0
LIMIT 1)
Sample data
What I need returned is: couponCode: SL2T-03A0-JVCY-W2XMXG
If I understand correctly, you can try to use UPDATE ... JOIN with ROW_Nunber windwon function.
UPDATE prcoupon pr
JOIN (
SELECT *,ROW_NUMBER() OVER(ORDER BY couponCode) rn
FROM prcoupon
WHERE status = 0
) t2 ON pr.couponcode = t2.couponcode
SET pr.status = 1,
pr.invoicenumber = '09990002'
WHERE rn = 1
sqlfiddle

User variable is giving last assigned values in a Session

We recently found the re-declaration issue in Mysql. If the query or procedure is called repeatedly in loop it retained last values.
SET #ToolType = 'test-Tool1';
SET #ToolType = (select Tool_type from IBP__Tool_type aa inner join IBP__xTool_set bb on aa.Tool_type_id=-1) ;
select #ToolType;
SET #ToolType = 'test-Tool1';
select #ToolType:=Tool_type from IBP__Tool_type aa inner join IBP__xTool_set bb on aa.Tool_type_id=-1;
select #ToolType; -- = OR :=
SET #ToolType = 'test-Tool2';
select Tool_type into #ToolType from IBP__Tool_type aa inner join IBP__xTool_set bb on aa.Tool_type_id=-1;
select #ToolType;
Above code will have Results : (when -1 is not present in tables so the output should be null in all cases)
null
test-tool1
test-tool2
what is the best way to resolve This Issue.
assign the variable to null before using it each time in query. User Session issues will always store the variable value in Mysql server and cause these issues.
SET #ToolType = null;

Trying to merge multiple UPDATE statements into one within SQL stored procedure

I have multiple update statements in a stored procedure (as shown below).
Question is I am trying to combine them into one UPDATE statement as there is a performance issue (takes longer to execute stored procedure). I tried putting columns (such as PONUMBER, VENDORID etc) in a single update statement but it is throwing errors.
Please suggest.
UPDATE rptMaster SET PONUMBER = (select top 1 poMaster.PONUMBER from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and
poMaster.UnCommited > 0)
UPDATE rptMaster SET VENDORID = (select top 1 poMaster.VENDORID from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and
poMaster.UnCommited > 0)
UPDATE rptMaster SET DUEDATE = (select top 1 poMaster.REQDATE from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and
poMaster.UnCommited > 0)
UPDATE rptMaster SET POQTYORDER = (select top 1 (poMaster.QTYORDER / rptMaster.UOMQTY) from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and
poMaster.UnCommited > 0)
Mine is similar to polkduran's:
WITH PO AS (
SELECT PONUMBER
, VENDORID
, REQDATE
, QTYORDER
, ITEMNMBR
, ROW_NUMBER() OVER (PARTITION BY ITEMNMBR ORDER BY ??) as RN
FROM poMaster
WHERE UnCommited > 0
)
UPDATE rptMaster
SET PONUMBER = po.PONUMBER
, VENDORID = po.VENDORID
, DUEDATE = po.REQDATE
, POQTYORDER = po.QTYORDER / rptMaster.UOMQTY
FROM rptMaster
JOIN PO
ON PO.ITEMNMBR = rptMaster.ITEMNMBR
and PO.RN = 1
I'm using a Common Table Expression (CTE) to assign a row number to each poMaster record, with the records for each value of ITEMNMBR numbered separately. This allows us to pick to the first record for each ITEMNBR in our JOIN, later, similar to the way you were using Top 1 in your subqueries.
Please note, though: because you didn't indicate how you wanted to select the Top 1 record in your query, I had to leave the ORDER BY clause in the CTE unspecified. (I put ?? in as a placeholder.) You need to specify one or more sort fields in place of the ?? so it knows how to sort and number the records.
You can make an update using a join clause:
update rpt
set
PONUMBER = po.PONUMBER,
VENDORID = po.VENDORID,
DUEDATE = po.REQDATE,
POQTYORDER = (po.QTYORDER / rpt.UOMQTY)
from rptMaster rpt
inner join poMaster po
on po.ITEMNMBR = rpt.ITEMNMBR
where po.UnCommited > 0
I don't have a way to test it right now but that might work.

How do I update a table with fields selected from another table?

Although there are many questions similar to this, such as
"Updating a record from another table", but i could not get this working.
I have a query that selects and updates table sem_stdexamfinresmark. The select subquery returns multiple rows of data whose size may not be equal to the table being updated, but the update is now working.
The query looks like :
update sem_stdexamfinresmark sr,
(select
se.currsession,
str.studentid,
str.classid,
str.subjectid,
str.aggScore*(select gbtp.percentage from gb_termpercentage gbtp where gbtp.termname = se.examtype)/100 as aggPer,
str.aggGrade
from
sem_stdexamtermresr str,
sem_exam se
where
str.examid=se.examid and
se.examtype = 'Second Term' and
se.currsession =1 and classid='8'
) s
set
sr.SecondTermMark = s.aggPer and
sr.SecondTermGrade = s.aggGrade
where
sr.studentid=s.studentid and
sr.subjectid=s.subjectid and
s.currsession = s.currsession and
sr.classid='8';
EDIT:
update sem_stdexamfinresmark
set
sr.SecondTermMark = s.aggPer and
sr.SecondTermGrade = s.aggGrade
from
(select
se.currsession,
str.studentid,
str.classid,
str.subjectid,
str.aggScore*(select gbtp.percentage from gb_termpercentage gbtp where gbtp.termname = se.examtype)/100 as aggPer,
str.aggGrade
from
sem_stdexamtermresr str,
sem_exam se
where
str.examid=se.examid and
se.examtype = 'Second Term' and
se.currsession = 1 and classid='8'
) s
where
sr.studentid=s.studentid and
sr.subjectid=s.subjectid and
s.currsession =1 and
sr.classid='8';
select * from sem_exam;
update sem_exam set currsession =1;
try something that looks more like:
update foo
set col = bar.col
from bar
where ...
This is what happens when one loses sleep :( I just did a silly mistake here and added "and"

Strange Sql Update behavior

I'm trying to update supplier table on both PostgreSQL and MySQL using the following update statement:
UPDATE SUPPLIERS SET CURDEBT = CURDEBT + 10 WHERE ID = 5
This works fine as long as the CURDEBT column not equals null, if it is null it won't update the record. Does any body have a solution to this problem?
Thanks
In SQL, NULL is not the same thing as 0. Any operations on a NULL value still yield a NULL result. NULL + 10 is still NULL.
If you want NULL to automatically turn into "0" in this query, try this (PostgreSQL):
UPDATE SUPPLIERS SET CURDEBT = coalesce(CURDEBT, 0) + 10 WHERE ID = 5
Or MySQL:
UPDATE SUPPLIERS SET CURDEBT = ifnull(CURDEBT, 0) + 10 WHERE ID = 5
Use coalesce
UPDATE SUPPLIERS SET CURDEBT = coalesce(CURDEBT,0) + 10 WHERE ID = 5
See sqlbook
What you're looking for is COALESCE:
UPDATE SUPPLIERS
SET CURDEBT = COALESCE(CURDEBT, 0) + 10
WHERE ID = 5
Coalesce (MySQL):
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce
That behaviour is exactly what you should expect from SQL, since null + x = null, always.
You can solve it by using the COALESCE function, available in both postgres and mysql, like so:
UPDATE SUPPLIERS SET CURDEBT = COALESCE(CURDEBT,0) + 10 WHERE ID = 5