Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Blank or unique value?
Message
From
23/01/2005 10:09:16
 
 
General information
Forum:
Microsoft SQL Server
Category:
Database design
Miscellaneous
Thread ID:
00979508
Message ID:
00979800
Views:
9
>How can I setup a field-level constraint so that the value for a field is either blank or unique? I have a field that the user has to fill-in later with a unique value but the data is initially blank and bunch of records are added in batch mode. TIA.

Hi John
I suggest you to use value NULL in place of the value blank.
However in MSSQL is not possible devine a unique contraint for the defined field values only
( a serious lack for me ).

The simple solution with NULL is:
USE tempdb
CREATE FUNCTION dbo.CheckUniqueT1F1 (@id INT, @F1 VARCHAR(10))  
RETURNS BIT AS  
BEGIN 
  RETURN (SELECT 1 FROM dbo.T1 WHERE id<>@id AND f1=@F1)
END

GO

CREATE TABLE dbo.T1 (id INT IDENTITY, F1 VARCHAR(10) NULL)
GO


ALTER TABLE dbo.T1 ADD CONSTRAINT
   CK_T1_UniqueF1 CHECK (([dbo].[CheckUniqueT1F1]([id], [F1]) is null))
GO

INSERT  dbo.T1 (F1) VALUES ('A')
INSERT  dbo.T1 (F1) VALUES ('B')
INSERT  dbo.T1 DEFAULT VALUES 
INSERT  dbo.T1 DEFAULT VALUES 
INSERT  dbo.T1 DEFAULT VALUES 
INSERT  dbo.T1 (F1) VALUES (NULL)
GO

INSERT  dbo.T1 (F1) VALUES ('A')

SELECT * FROM dbo.T1
DROP TABLE dbo.T1
DROP FUNCTION dbo.CheckUniqueT1F1
You can adapt it to the empty value.

Fabio
Previous
Reply
Map
View

Click here to load this message in the networking platform