Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating multiple rows using list of Ids

Tags:

sql

mysql

I need to update multiple rows in the table on the basis of Ids. In the stored procedure, I'm creating a varchar variable that holds the Ids list.

Now, in the table I have entries with Ids 1, 2. The varchar variable has value 1,2; so I'm expecting no row to be updated with following query.

UPDATE mytbl
SET flag = 1
WHERE Id IN (IdList); -- Here IdList has value '1,2'

But here row with Id as 2 is getting updated. Select query also returns the same row. I tried concatenating IdList as "'1','2'", then it retuens both the rows (with Ids 1 and 2). The data type of Id is int. Is there proper way to maintain integer list?

like image 497
benjamin54 Avatar asked Dec 23 '14 10:12

benjamin54


People also ask

How do I UPDATE multiple rows at once?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);

Can we UPDATE multiple rows in a single UPDATE statement?

We can update the multiple rows of the table using the single update command.

How do you UPDATE multiple rows in a column?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.


2 Answers

just use the ids as integers like so:

UPDATE mytbl
SET flag = 1
WHERE id in (1,2,3,....)
like image 156
Olli Avatar answered Oct 01 '22 07:10

Olli


Try this:

UPDATE mytbl
SET flag = 1
WHERE @IdList LIKE CONCAT('%,',Id,',%');

Note that your varchar list @IdList must start and end with comma (e.g. ,1,2,20,30,).

like image 34
i486 Avatar answered Oct 01 '22 05:10

i486