简体   繁体   中英

How do I store data in an SQL database if the database columns can be different?

I'm creating an ASP.NET web application which allows users to digitize paper forms. The user will import their own forms which will be converted into HTML with placeholders inserted to accept values from an input form.

Using the fields on this imported paper form, the website will create an input form based on what information is required. "Templates" can also be created for a specific form which allows a user to auto-fill any data that doesn't normally change with each form fill. A user can also save a form they haven't finished for completing/reviewing later.

My question is: how do I store this data? I can't really use a traditional database table because Form X could look nothing like Form Y and require completely different data. I have a SQL database to store the data in (I need this for other aspects of the site too), but I can't simply store all form data in one table or even have separate tables for each form as this will be impractical on a larger scale.

My initial thoughts were using JSON but I have absolutely no idea where to start with this. Can I put JSON data into a regular SQL database column? Can this be used to generate code to build a web form to allow a user to easily fill out their forms using any device (as per my design requirements)?

I think your problem would be very well served using a document DB like mongoDB or Arangodb. Reality nowadays is that applications can , and sometimes should, use more than one DB.

Having said that, if I had to use a relational DB, I would convert your forms into 3 tables. The first top level form would just store something like:

  • form name ,
  • form id ,
  • etc...

The second table would capture the form fields and would look be something like:

  • FormID
  • field Id
  • field name
  • fiel type (int, varchar, etc...)
  • sort no.
  • etc ...

The third table would capture the information entered by the user:

  • user id
  • form id
  • field id
  • value
  • creation date time
  • last modification date time
  • etc...

Note that by storing the fields in rows instead of columns, it does not matter that you have different types of forms.

I should mention that the above table definitions are not meant to be complete by any means, they are there to give you an idea on how to get started.

Finally, note that many relational DB allow you to store JSON nowadays directly in the DB as you suggested, but that may not be a very good option depending on which DB you are using. Here is an example of storing JSON in mysql just for your reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM