简体   繁体   中英

SQL Server 2005 create constraint or indexed view

I've been reading a lot of the posts here on SO about creating constraints or indexed views but I've never written a complex constraint before and I'm hoping someone can tell me the best approach for this. I basically have a table with structure like below and a record can only ever have 1 active admin.

 Id     Admin
 --     ------
 1      1
 1      null
 1      null
 2      1
 2      null
 2      null

I started by writing just a regular constraint statement but quickly realized this wouldn't work because the multiple null values are not unique. Is there a way to modify this constraint to disallow/disregard nulls?

  ALTER TABLE dbo.table
  ADD CONSTRAINT OnlyOneAdmin UNIQUE(Id, Admin)

Based on my research it seems like a good option is an indexed view but I'm concerned that creating this view would introduce too much overhead. And I'm not certain the below view is structured correctly to achieve the results I want.

 CREATE VIEW AdminView WITH SCHEMABINDING AS
     SELECT Admin 
     FROM dbo.table 
     WHERE Admin IS NOT NULL;
 GO

 CREATE UNIQUE CLUSTERED INDEX AdminUnique 
 ON dbo.AdminView(Admin);

Any guidance is greatly appreciated, thanks in advance.

Additional question: Would it be better to use a computed column for this?

I think what you want is a filtered index. Unfortunately available only in versions 2008 and later:

CREATE UNIQUE INDEX OnlyOneAdmin
  ON dbo.table (Id)
  WHERE Admin IS NOT NULL ;

For 2005, this should work (please test, I have no 2005 version available to check it.) It's very close to the code you have but with Admin replaced with Id in some places:

CREATE VIEW AdminView WITH SCHEMABINDING AS 
  SELECT Id 
  FROM dbo.table 
  WHERE Admin IS NOT NULL; 

CREATE UNIQUE CLUSTERED INDEX AdminUnique 
  ON dbo.AdminView (Id) ;

You can create an AFTER TRIGGER on the table to enforce this requirement.

Once you update a row to be the new admin your trigger would be setup to update all other rows to be regular users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM