SQL Server

Using a Cursor in SQL2 min read

Everything is in the title, this tutorial uses for example the insertion of data into a table according to the result of a query based on a linked table

For our example let’s take a simplified database containing 2 tables.
The first: USERS (ID_USER, NAME, PW, STATE) manages the users. The second GROUPS (ID_USER, NOM_GROUP) manages the groups assigned to the users.




CONTENT OF TABLES

Table USERS
ID_USER NAME PW STATE
1 MARK Xb4545 FATIGUE
2 MOLLY FfAA45A MOBILITY
3 CANDY RT4ACZ FATIGUE

 

Table GROUPS
ID_USER NAME_GROUP
1 ADMIN
1 CHIEF
2 ADVISOR
2 CHIEF
3 FIREFIGHTER

 

On this table I want all users whose STATUS is “FATIGUE” to belong to a new group “NEED HOLIDAYS”. To do it I will use a CURSOR which will recover all the ID_USER of the users (table USERS) whose field STATE = “FATIGUE” and for each one of these ID_USER one will add a line in the table GROUPS with for NOM_GROUP the value “NEED HOLIDAYS”.

 

Leave a Comment