views:

93

answers:

4

I have a table with two integer columns and a bit column. How can I put a constraint on the table so that it will not allow duplicates with the combination of two integers with a true. For example:

1 2 True
1 2 False
1 2 True ------> This should not be allowed

A: 

create unique index idxName on (Field1, Field2) where Condition = 'True';

Remus Rusanu
I don't have a handy SQL 2k8 system to test, not sure if unique filtered indexes are allowed: http://technet.microsoft.com/en-us/library/cc280372.aspx
Remus Rusanu
+1  A: 
ALTER TABLE Table_1 ADD CONSTRAINT col1_col2_COL3
   UNIQUE (col1, col2, col3);
kevinw
I think he wants to allow for duplicates if col3 is False though
Remus Rusanu
This will allow for a 1 2 true and a 1 2 false.
Ben
+1  A: 

This might be heavier than you like but I believe it gives what you want. Create a view on the rows where the bit column is TRUE then materialize it with a unique index. The below example works on SQL Server 2008.

--Set statements required for creating materialized views.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON 
GO

--Set statements required when creating index for materialized views.
SET ANSI_PADDING ON 
GO
SET ANSI_WARNINGS ON 
GO
SET ARITHABORT ON   --only required in 80 compatibility mode.
GO
SET CONCAT_NULL_YIELDS_NULL ON 
GO
SET NUMERIC_ROUNDABORT OFF
GO

CREATE TABLE dbo.Test (a int not null, b int not null, c bit not null);
GO

CREATE VIEW dbo.vTest (a,b) WITH SCHEMABINDING AS 
SELECT a,b FROM dbo.Test WHERE c = 'TRUE' ;
GO

CREATE UNIQUE CLUSTERED INDEX [AK_vTest] ON dbo.vTest ( a,b );
GO

INSERT dbo.Test (a,b,c) VALUES (1,2,'TRUE');  --succeeds.
INSERT dbo.Test (a,b,c) VALUES (1,2,'FALSE'); --succeeds.
INSERT dbo.Test (a,b,c) VALUES (1,2,'FALSE'); --succeeds.
INSERT dbo.Test (a,b,c) VALUES (1,2,'TRUE');  --fails "Msg 2601, Level 14"
GO

SELECT * FROM dbo.Test
SELECT * FROM dbo.vTest

DROP VIEW  dbo.vTest
DROP TABLE dbo.Test
McSQL
A: 

for doing this in SSMS, expand the table name and then press write click of your mouse on it. click on new index in exposed menu. in New Index window, and in general tab you can add your arbitrary columns. in filter tab, add your filter expression.

masoud ramezani

related questions