I have an application that displays tabular information and allows the user to enter and edit it. I have been working on the database design for this and have come across the following problem.
I want to avoid creating an MSSQL table for each table in the application, so I’ve been trying to represent all of the tables together, in two tables.
I have defined a MyAppTable table which has Id INTEGER primary key and a Name CHARACTER VARYING(255) columns.
From there, I have defined a MyAppColumn table which foreign keys against the MyAppTable.Id column and also has a Position INTEGER column to indicate its position in the rendered table.
Finally, I have defined a MyAppRow table which foreign keys against the MyAppColumn.Id column and has a Data BINARY(32) column. It’s a table of small files, so this data type is fitting.
The actual problem is that I cannot guarantee that the MyAppColumn.Position column will be unique for each MyAppTable.
An example of a normal situation:
MyAppTablewithId0MyAppColumnwithId0,TableId0,Position0MyAppColumnwithId1,TableId0,Position1MyAppRowwithColumnId0,Data[something]MyAppRowwithColumnId1,Data[something]MyAppTablewithId1MyAppColumnwithId2,TableId1,Position0MyAppRowwithColumnId2,Data[something]
An example of a situation I want to make impossible in the database:
MyAppTablewithId0MyAppColumnwithId0,TableId0,Position0MyAppColumnwithId1,TableId0,Position0
As you can see, I want some way of constraining a pair of columns. The two columns TableId and Position should be UNIQUE but if that were done independently, it would mean two tables could never have columns both at a Position of 0.
How can I accomplish this in Microsoft SQL Server 2012?
The solution to your problem is to not encode metadata in tables but to create actual tables, even if it’s inconvenient or a lot of work.
Some stuff that will bite you in the rear very soon:
Save yourself a lot of time and effort in the future and just make actual tables now in the design phase. This type of meta-data “god table” has been tried repeatedly and never works.
That being said, if you are representing a very limited set of data (like you say, for files only), I would consider a coordinate system.
Keep your
MyAppTableas is.Create a
MyAppFiletable with fields:MyAppTableId(FK)Data(varbinary)XPos(int)YPos(int)With a unique constraint on
(MyAppTableId, Xpos, Ypos).This more accurately represents what you are trying to store, will be easier to maintain, and allows you to enforce integrity.