If value = 0000 Insert and set value with max()+1 - mysql

I need to get the maximum value +1 for a field, if that filed as the 0000 value.
IF
(acc_id = 0000)
FROM
crm_accounts;
INSERT
INTO
crm_accounts(acc_id)
SELECT MAX
(acc_id) + 1
FROM
crm_accounts;

I think you're looking to do an UPDATE statement...
This should get it done for you:
SELECT #id := MAX(acc_id) FROM crm_accounts;
UPDATE crm_accounts
SET acc_id = #id := #id + 1
WHERE acc_id = 0000;

Related

Update multiple rows, but only first row with different value

table
create table tst(locationId int,
scheduleCount tinyint(1) DEFAULT 0,
displayFlag tinyint(1) DEFAULT 0);
INSERT INTO tst(locationId,scheduleCount)
values(5,0),(2,0),(5,1),(5,2),(2,1),(2,2);
I update multiple rows and multiple columns with one query, but want to change the one of the columns only for the first row and keep the other things the same for that column.
I want to update all the rows with some location id and change displayFlag to 1 and increment scheduleCount of only the top entry with 1 , rest would remain the same
**Query **
update tst,(select #rownum:=0) r,
set tst.displayFlag =1,
scheduleCount = (CASE WHEN #rownum=0
then scheduleCount+1
ELSE scheduleCount
END),
#rownum:=1 where locationId = 5
But it gives error and does not set the user defined variable rownum, I am able to join the tables in a select and change the value of the rownum, is there any other way to update the values.
I'm not sure this is the correct way of doing such a thing, but it is possible to include the user variable logic in the CASE condition:
UPDATE tst
JOIN (SELECT #first_row := 1) r
SET tst.displayFlag = 1,
scheduleCount = CASE
WHEN #first_row = 1 AND ((#first_row := 0) OR TRUE) THEN scheduleCount+1
ELSE scheduleCount
END
WHERE locationId = 5;
I have used a #first_row flag as this is more inline with your initial attempt.
The CASE works as follows:
On the first row #first_row = 1 so the second part of the WHEN after AND is processed, setting #first_row := 0. Unfortunately for us, the assignment returns 0, hence the OR TRUE to ensure the condition as a whole is TRUE. Thus scheduleCount + 1 is used.
On the second row #first_row != 1 so the condition is FALSE, the second part of the WHEN after AND is not processed and the ELSE scheduleCount is used.
You can see it working in this SQL Fiddle. Note; I have had to set the column types to TINYINT(3) to get the correct results.
N.B. Without an ORDER BY there is no guarantee as to what the '1st' row will be; not even that it will be the 1st as returned by a SELECT * FROM tst.
UPDATE
Unfortunately one cannot add an ORDER BY if there is a join.. so you have a choice:
Initialise #first_row outside the query and remove the JOIN.
Otherwise you are probably better off rewriting the query to something similar to:
UPDATE tst
JOIN (
SELECT locationId,
scheduleCount,
displayFlag,
#row_number := #row_number + 1 AS row_number
FROM tst
JOIN (SELECT #row_number := 0) init
WHERE locationId = 5
ORDER BY scheduleCount DESC
) tst2
ON tst2.locationId = tst.locationId
AND tst2.scheduleCount = tst.scheduleCount
AND tst2.displayFlag = tst.displayFlag
SET tst.displayFlag = 1,
tst.scheduleCount = CASE
WHEN tst2.row_number = 1 THEN tst.scheduleCount+1
ELSE tst.scheduleCount
END;
Or write two queries:
UPDATE tst
SET displayFlag = 1
WHERE locationId = 5;
UPDATE tst
SET scheduleCount = scheduleCount + 1
WHERE locationId = 5
ORDER BY scheduleCount DESC
LIMIT 1;

Toggle boolean in MySQL / Oracle Database

Update myTable SET field = 1 (if field = 0 or if field is null) where myid = 12345;
Update myTable SET field = 0 (if field = 1) where myid = 12345;
What is the best way to transform this Pseudocode in proper SQL for Oracle and MySQL?
You could simply use the modulo like this:
UPDATE myTable SET field = (field + 1) % 2 WHERE myId = 12345;
Due to the lack of a real boolean in both DBMS you need a case statement:
update myTable
set the_column = case when the_column = 1 then 0 else 1 end
where myId = 12345;
This assumes that the column never has different values than 0 and 1

How to loop a MYSQL query / maybe in a function?

What I've got so far is a code which updates one row as based on the IF conditions - but it
It is important that it is reliable and atomic (so with transaction).
It should loop/repeat itself based on #q which is quantity - however it can be in a MYSQL function rather than one fixed variable. How can I do that? I've added how the table should look like in the end
SET #q=1000;
SET #p=5.00;
SET #email='test#test.com';
update 1detail
SET quantity =
if((#q := quantity - #q) >= 0, #q, 0)
WHERE price>=#p ORDER BY datetime DESC LIMIT 1;
SET #q = if(#q <0,#q-#q-#q, #q);
UPDATE 1detail
SET quantity =
if(#q > 0, #q,quantity),
email=
if(#q > 0, #email, email)
WHERE price>=#p ORDER BY datetime DESC LIMIT 1;
The table at the beginning
quantity price email datetime
---------------------------------------------------
800 5.00 test1#test.com oldest
50 5.00 test2#test.com 2nd oldest
100 10.00 test3#test.com 3rd oldest (ignore in processing because #p < price)
How it should looks like after looping
quantity price email datetime
-----------------------------------------------------------------
0 5.00 test1#test.com oldest
150* 5.00 test#test.com (changed to #email) 2nd oldest (now newest)
100 10.00 test3#test.com 3rd oldest (ignored)
*this has changed as the oldest only had 800 and the 2nd oldest just had 50
So #q= 1000 (#q) - 800 (oldest) = 200
then #q = 200 (#q) - 50 (2nd oldest)
--> #q = 150
this updates the 2nd oldest row
A small loop can be achieved like this :
declare #counter int
set #counter=0
gohere:
set #counter=#counter+1
if #counter<10
BEGIN
select #counter
GOTO gohere;
END

How to Auto Increment ID Numbers with Letters and Numbers

How to Auto Increment ID Numbers with Letters and Numbers, example "KP-0001" it will increment to "KP-0002"
Thank you!
here is a useful article
auto increment with a string of numbers and letters
But basically I encourage you to create your own algorithm on this. You can add that algorithm in BEFORE INSERT trigger. Or you can do that on the front-end.
Example of pseudocode for the algorthm
get the lastID [KP-0001]
remove some characters and put it in a variable [KP-]
convert the remaining into number since it's a string [0001]
increment by 1 [1 + 1 = 2]
convert it back to string and pad zero on the right [0002]
concatenate the variable and the newly incremented number [KP-0002]
save it.
I tried to do that in many ways but was unable to reach the solution... I also used triggers but that too didn't help me...
But I found a quick solution for that...
For example you want your employee to have employee codes 'emp101', 'emp102',...etc.
that too with an auto increment...
First of all create a table with three fields the first field containing the letters you want to have at the beginning i.e."emp", the second field containing the auto increasing numbers i.e 101,102,..etc., the third field containing both i.e 'emp101', 'emp102',...etc.
CREATE TABLE employee
(
empstr varchar( 5 ) default 'emp',
empno int( 5 ) AUTO_INCREMENT PRIMARY KEY ,
empcode varchar( 10 )
);
now providing an auto_increment value to empno.
ALTER TABLE employee AUTO_INCREMENT=101;
now coming to the topic... each time you insert values you have to concatenate the first two fields to get the values for the third field
INSERT INTO employee( empcode )
VALUES ('xyz');
UPDATE employee SET empcode = concat( empstr, empno ) ;
You can't auto increment varchar data type. Other way of doing this is to bifurcate varchar column into two different columns one will have integer part and other will have alphabet like in your case KP- once you auto increment all integer rows just concatenate these two columns
CREATE TABLE Customer (
CUSId INT NOT NULL IDENTITY(1, 1) PRIMARY KEY
,CUSKey AS 'Cus' + RIGHT('000' + CONVERT(VARCHAR(5), CUSId), 6) PERSISTED
,CusName VARCHAR(50)
,mobileno INT
,Gender VARCHAR(10)
)
Auto-increment is an integer, so adding text will not be possible.
Check out this question for other references.
Make a procedure, in my case MySQL.
CREATE PROCEDURE MOSTRAR_CODIGO_CLASE_PRODUCTO()
BEGIN
declare max varchar(10);
declare num int;
declare CCodigo varchar(10);
set max = (select MAX(Codigo_CP) from CLASE_PRODUCTO);
set num = (SELECT LTRIM(RIGHT(max,4)));
if num>=1 and num <=8 then
set num = num + 1;
set CCodigo = (select concat('CP000' , CAST(num as CHAR)));
elseif num>=9 and num <=98 then
set num = num + 1;
set CCodigo = (select concat('CP00' , CAST(num as CHAR)));
elseif num>=99 and num <=998 then
set num = num + 1;
set CCodigo = (select concat('CP0' , CAST(num as CHAR)));
elseif num>=999 and num <=9998 then
set num = num + 1;
set CCodigo = (select concat('CP' , CAST(num as CHAR)));
else
set CCodigo=(select 'CP0001');
end if;
SELECT MAX(CCodigo) AS Codigo_CP FROM CLASE_PRODUCTO;
END $
Java Class
public static boolean insertarClaseProducto(ClaseP cp){
boolean resp = false;
Connection cn;
Connection con = new Connection();
cn = con.connect();
try{
CallableStatement cs = cn.prepareCall("CALL REGISTRAR_CLASE_PRODUCTO (?)");
cs.setString(1, cp.getNombreCP());
int i = cs.executeUpdate();
if(i==1)
resp = true;
else
resp = false;
}catch(Exception e){System.out.println(e);}
return resp;
}
returns:
Codigo_MP Nombre_MP Estado_MP
MP0001 LG HAB
MP0002 GENIUS HAB
MP0003 MICRONICS HAB
MP0004 SONY HAB
MP0005 PANASONIC HAB

Is it possible to update the cell value only to the specific maximum value?

Is it possible to update the cell value only to the specific maximum value? Here is query:
UPDATE table_1 SET premium_photos = premium_photos + 2 WHERE number = '1234'
I want to limit premium_photos (tinyint) value to max value of 4. Is it possible? For example if premium_photos current value is 2 and query is + 3, then after this query value will be 4.
try
UPDATE table_1 SET
premium_photos = (CASE WHEN (premium_photos + 2) > 4 THEN 4 ELSE (premium_photos + 2) END)
WHERE number = '1234'
you can also use IF function
UPDATE table_1 SET
premium_photos = IF(premium_photos+2>4, 4, premium_photos+2)
WHERE number = '1234'
IF() function documentation