问题: 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);发布于 2016-02-08 10:46:50
第二个问题是,这确实很难发现,因为:
select pid from sales group by pid只返回一个值:示例中的a
下面是一个帮助检测问题的技巧:
select pid from sales group by binary(pid)这将返回2行:a和A(带尾空格)
干杯,
发布于 2016-01-21 07:50:10
如果您只是简单地不想允许尾随空格:
create table sales
(
pid nvarchar(20) references products(pid),
units int,
constraint CK_sales_pid CHECK (RIGHT(pid,1) <> ' ')
);否则,你需要意识到这不仅仅是一个“意外”的情况。SQL Standard指出,当有两个长度不等的字符串时,短字符串首先填充空格以使长度相等,然后再进行比较。
https://stackoverflow.com/questions/34917261
复制相似问题