日期:2014-05-18  浏览次数:20484 次

创建“允许为空,但不为空时不能重复”的约束
我有一个字符串(最长18位)的列,要求创建“允许为空,但不为空时不能重复”的约束,不知哪位大侠能否解决,谢谢!

------解决方案--------------------

SQL code

CREATE TABLE [tb3] (
    [myid] [char] (10)  ,
    [mytext] [char] (10)  
)

ALTER TABLE [tb3] ADD 
    CONSTRAINT [wy] UNIQUE  NONCLUSTERED 
    (
        [myid]
    ) 

insert into tb3
select null,'adsfad' union all
select 'aaaa','adsfad' union all
select 'bbbb','adsfad' union all
select 'cccc','ccccd'

select * 
from tb3
/*
myid       mytext     
---------- ---------- 
NULL       adsfad    
aaaa       adsfad    
bbbb       adsfad    
cccc       ccccd     

(所影响的行数为 4 行)
*/

------解决方案--------------------
SQL code

CREATE FUNCTION f_check(@a VARCHAR(10))
RETURNS BIT
AS
BEGIN
    DECLARE @bit BIT
    SELECT @bit = 0
    WHERE (SELECT COUNT(1) FROM tb WHERE a = @a) = 1
        OR @a IS NULL 
    
    SET @bit = ISNULL(@bit,1)
    RETURN @bit
END
GO
CREATE TABLE tb(a VARCHAR(10)  NULL,CONSTRAINT ck_tb CHECK (dbo.f_check(a) = 0))
GO
INSERT tb SELECT 'cc' UNION ALL SELECT NULL
GO
INSERT tb SELECT 'cc'
GO
INSERT tb SELECT NULL
GO
SELECT * FROM tb
GO
DROP TABLE tb 
DROP FUNCTION dbo.f_check
/*
(2 row(s) affected)
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "ck_tb". The conflict occurred in database "WebReport", table "dbo.tb", column 'a'.
The statement has been terminated.

(1 row(s) affected)
a
----------
cc
NULL
NULL

(3 row(s) affected)
*/