Monday, March 19, 2012

How to dynamically create Tables

I'm currently developing an RDF application which need to handle lots of datatypes. But I want to use SQL-Servers capabilities for efficient querying and sorting. Therefore, I've wanted to create a Main Table which stores a Reference to the Table where the Data is stored. The Data itself should get stored in a Datatype-specific Table.
The Typed Table might get created by something like:

public void CreateTypedLiterals(Type type)
{

String sql = String.Format(

"CREATE TABLE [Literals_{1}] (" +
"ID int DISTINCT NOT NULL, Value {1})",

// BUG: does not work
// WARNING: introduces a potential sql-injection problem
type.ToString()

);

...


As you can see on the statements this solution makes many troubles. So I've wanted to implement it in a more fine way using a DataTable:

[SqlProcedure]
public void CreateTypedLiterals(Type type)
{

DataTable TypedLiterals =

new DataTable(

String.Format("Literals_{0}", type.ToString()));

TypedLiterals.Columns.Add(

"ID", typeof(int), "DISTINCT NOT NULL");

TypedLiterals.Columns.Add("Value", type);

...


But I have totally no Idea how to fetch this result into the existing Database. It might be cool to simply access the Database as it would be a .NET Dataset in the form:

using(Microsoft.SqlServer.Server)
{

CurrentDatabase.Tables.Add(TypedLiterals);

}

But this is afaik not possible. Has anybody an idea how to solve this issure?Have you considere using the new XML datatype of SqlServer2005 ? As MS documentation says, it well fits into scenarios where you have sparse data.
You could use a single table that contains variable data and types in XML format.|||The ADO.NET datatable (which you are using) is not the same as the SQL Server table. YOu either will have to use your script approach or use SMO to create objects using the current server connection.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de|||I think it might be better to use strings or at least tables for the most common types as defined in XSD and handling all others simply as strings. Using XML format is ineffective, because the main reason for using different Tables for each type is because I want to get more effective sorting.|||That the ADO.NET datatable is not the same than a SQL Server table was clear. Because I'm not a fan of the script Approach using String.Format to get SQL-Commands because of the fear of SQL-Injections, so I'll take a closer look at SMO. Thanks for the hint.

No comments:

Post a Comment