Search code examples
mysqlsqlstored-procedurescursordynamic-sql

SQL Updating Rows Without Knowing Column Name


I am attempting to create a stored procedure that will update a specific row and column location based on user input. My table has approximately 100 columns utilizing names in progressive increments. Ex Page1, Page2, Page3, Page 4.... etc. The data must also be updated in progressive increments as users finish different versions of each page.

When the procedure is called I need it to find the user's row(Page1 is the key and unique), and put the information in where their version of the file is saved into the first NULL column. I have seen talk about using cursors for similar applications but I am not sure if this is the proper solution.

 ----------------------------------------------------
 |  Page1    |   Page2    |   Page3    |   Page4    |   
 ----------------------------------------------------
 |  /pg1.htm |   /pg2.htm |  /pg3.htm  |   NULL     |
 ----------------------------------------------------
 | /pg1.doc  |   /pg2.doc |   NULL     |   NULL     |
 ----------------------------------------------------
 | /pg1.pdf  |  NULL      |   NULL     |   NULL     |
 ----------------------------------------------------

I need the procedure to update the row sequentially each time with one piece of data when it is called. My issue is in making this scaleable instead of limiting it with 100 + IF statements.

The pseudo code I cooked up looks like this but is terribly inefficient:

 FIND ROW that matches unique key
 LOOP Find_NULL
     IF Column2 == NULL
         UPDATE DATA HERE
     ELSE IF Column3 == NULL
         UPDATE DATA HERE
     ELSE IF Column4 == NULL
         UPDATE DATA HERE
     ELSE IF.... and on and on
 END LOOP Find_NULL

I am utilizing MySQL which I have been told does not support Dynamic SQL. I attempted to create a variable and modify it as I went through the data to store the next NULL column however this did not work.

If anyone has any solutions or advice I would appreciate it.

Thanks in advance.


Solution

  • At first glance, you seem to be suffering from rather poor database design.

    You don't want to name columns "Page1", "Page2" ... "Page 100", and then have these columns be NULL much of the time. This violates sound database design. You might want to review concepts such as database normalization (e.g., first normal form, second and so on).

    I think you would be much better off having a column named "Page" and then each row would have a value of 1 through 100 along with the information related to the page. This way you wouldn't need to try to dynamically piece together columns names when forming an insert/update query.