Click here to Skip to main content
15,891,629 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I am trying to determine the best way to solve the following problem:

My application needs to allow a user to define a table structure, then create a table in SQL out of this structure. Then the application needs to be able to allow the user to perform CRUD operations on the new table.

I think what I am looking for is similar to what CMS applications do when they create custom content.

What is the best way to accomplish this?

What I have tried:

I've been doing a lot of googling but I haven't found anything similar to what I have been looking for.
Posted
Updated 11-Aug-18 8:54am
v2

1 solution

0) Allow the user to specify the column names and types.

1) Create a collection of an object that store your column names and types. Make sure you add code to prevent duplicate column names. There are several techniques you can use to black-box this code so you can hide validation complexity. I'll let you be a programmer and finger out how much validation is necessary, and where it should be implemented.

2) Build a string that represents the desired query.

C#
string userTable = "MyTable";
HashSet columns = new HashSet<string,string>(); // populate this somewhere else

StringBuilder query = new StringBuilder();
query.AppendFormat("IF OBJECT_ID('{0}','U') IS NOT NULL DROP TABLE dbo.{0}; ", userTable).AppendLine();
query.AppendFormat("CREATE TABLE dbo.{0} (", userTable);

MyColumnItem lastColumn = columns.Last();

foreach(MyColumnItem item in columns)
{
    query.AppendFormat("{0} {1}", item.ColumnName, item.ColumnType);
    it (!item.Equals(lastItem)
    {
        query.Append(",");
    }
}
query.Append(");");


3) Use ADO classes to execute the query.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900