The immediate solution to your problem is to dynamically generate UPDATE
including the database name in the statement to identify the table, and then using EXEC
to execute the UPDATE
.
So, instead of:
EXEC('USE '+ @Base_de_datos)
UPDATE RPARAMS SET Param='Dato_que_cambiare' WHERE copar='CONFIGUR'
Replace these 2 sentences with this:
EXEC('UPDATE ' + @Base_de_datos + '..RPARAMS SET Param=''Dato_que_cambiare'' WHERE copar=''CONFIGUR''')
But repeating what I left in the comments, the fact that you have to use dynamic SQL in a cycle is a strong indication that the design of your model is not correct. It is not good design that the tables are repeated in different databases for each student.
Rather, it is normal to define a database, with a single structure of tables shared by all students, and that each student has their own records identified by a column AlumnoId
or something like that.
For example, taking the example in your question, instead of having several tables RPARAMS
in different databases, you would only need one, but with a column AlumnoId
to be able to distinguish the records of each student and be able to manipulate them separately when necessary.
With this design, your problem would be solved by executing a single UPDATE
sentence without the need for cycles or dynamic SQL:
UPDATE RPARAMS
SET Param='Dato_que_cambiare'
WHERE copar='CONFIGUR'
And if you need to update a data for a single student in particular, it would be just a matter of adding an additional filter to the sentence:
UPDATE RPARAMS
SET Param='Dato_que_cambiare'
WHERE copar='CONFIGUR'
AND AlumnoId = 5