外键中允许的尾随空格

时间:2016-01-21 06:59:24

标签: sql-server sql-server-2008-r2

问题: SQL Server允许将尾随空格添加到外键中!

这种行为当然会导致应用程序中出现各种不需要的行为。怎么能阻止它?

示例: 1:n关系中的两个表:

create table products 
(
    pid nvarchar(20) primary key
;)

create table sales 
(
    pid nvarchar(20) references products(pid), 
    units int
);

现在插入主键'A'

insert into products (pid) values ('A');

现在插入外键:

-- 'A' is accepted, as expected:
insert into sales (pid, units) values ('A', 23); 

-- 'B' is declined, as expected:
insert into sales (pid, units) values ('B', 12); 

-- 'A ' (with a trailing space)
-- This is ACCEPTED, but of course this is NOT EXPECTED !! 
insert into sales (pid, units) values ('A ', 12);

2 个答案:

答案 0 :(得分:2)

第二个问题是,从那以后很难检测到:

    select pid from sales group by pid

只返回一个值:示例中的A

这是一个帮助检测问题的技巧:

    select pid from sales group by binary(pid)

返回2行:A和A(带尾随空格)

干杯,

答案 1 :(得分:1)

如果你只是简单地不想允许尾随空格:

create table sales 
(
    pid nvarchar(20) references products(pid), 
    units int,
    constraint CK_sales_pid CHECK (RIGHT(pid,1) <> ' ')
);

否则,您需要意识到这不仅仅是一个“意外”的情况。 SQL标准说当有两个长度不等的字符串时,在进行比较之前,首先用空格填充较短的字符串以使长度相等。