I have a table for storing a report template. The report is made up of 1, 2, 4, or 6 different graphs (the scale). There will be a separate row for each graph and each row will contain the number of graphs on the report.
CREATE TABLE ReportTemplate (
TemplateName varchar(100) not null,
UserName varchar(100) not null,
GraphPosition int not null,
Scale int not null,
-- graph specific stuff here
Constraint PK_ReportTemplate primary key clustered
(TemplateName ASC, UserName ASC, GraphPosition ASC)
)
I have constraints that ensure that Scale is 1, 2, 4, or 6 and that the GraphPosition is <= Scale.
What I want to do, is ensure that for each template (TemplateName/UserName pair) value, all rows have the same value for Scale. I'm wondering how I might do that.
答案 0 :(得分:1)
You want to ensure that all rows which share a TemplateName, UserName
also have the same Scale
?
This means your design is not normalised as Scale is functionally dependent on those two columns. So to normalise this you would use a different table with a PK of TemplateName, UserName
to ensure a single row for each (and a column for the desired Scale) so you only store this fact once.
But with your existing structure you can use an indexed view to enforce this constraint.
CREATE VIEW SomeView
WITH SCHEMABINDING
AS
SELECT TemplateName,
UserName,
Scale,
COUNT_BIG(*) AS C
FROM dbo.YourTable
GROUP BY TemplateName, UserName, Scale
GO
CREATE UNIQUE CLUSTERED INDEX IX ON SomeView(TemplateName, UserName)