Update a column based on list

Question:

I am using MSSQL. I have a table students.

| id |name |attendance|status|
|----|-----|----------|------|
| 1  |Tom |present    |Due   |
| 2  |Jerry|absent    |Due   |
| 3  |Tim  |present   |Due   |
| 4  |Aan  |present   |Due   |
| 5  |Niya |absent    |synced|

I want to fetch id, name and attendance from students, whose status is ‘Due’. After fetching this data, I want to update the status to ‘sync-in-progress’ by using the fetched id’s list. Is there a way to update the status without using the loop.
This is my code:

# Select  id,name and attendance data from students table whose status
 is due.

cursor.execute("""SELECT id,name,attendance FROM students

                  WHERE status = 'DUE'""")

data = cursor.fetchall()



# List of id's selected.

log_id = [i[0] for i in data]



# Update the status of the selected id's to sync-in-progress.

cursor.execute("""UPDATE students

                  SET  status = 'sync-in-progress'

                  WHERE id IN(?)""", (log_id,))

connection.commit()


Asked By: Ajdal

||

Answers:

You can done it with single query:

UPDATE students
SET  status = 'sync-in-progress'
WHERE status = 'DUE'
Answered By: Slava Rozhnev

You can do it like this.

# Select id, name and attendance data from students table whose status
 
# is due.

cursor.execute("""SELECT id,name,attendance
                  FROM students

                  WHERE status = 'DUE'""")

data = cursor.fetchall()


# List of id's selected.

log_id = [i[0] for i in data]

place_holder = '?'
place_holders = ','.join(place_holder * len(log_id))


# Update the status of the selected id's to sync-in-progress.

cursor.execute("""UPDATE students

                  SET  status = 'sync-in-progress'

                  WHERE id IN(%s)""" % place_holders, log_id)

connection.commit()

Answered By: Ajdal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.