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:
MyAppTable
withId
0MyAppColumn
withId
0,TableId
0,Position
0MyAppColumn
withId
1,TableId
0,Position
1MyAppRow
withColumnId
0,Data
[something]MyAppRow
withColumnId
1,Data
[something]MyAppTable
withId
1MyAppColumn
withId
2,TableId
1,Position
0MyAppRow
withColumnId
2,Data
[something]
An example of a situation I want to make impossible in the database:
MyAppTable
withId
0MyAppColumn
withId
0,TableId
0,Position
0MyAppColumn
withId
1,TableId
0,Position
0
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?