I'm using Microsoft SQL Server 2008 R2 (with latest service pack/patches) and the database collation is SQL_Latin1_General_CP1_CI_AS.
The following code:
SET ANSI_PADDING ON;
GO
CREATE TABLE Test (
Code VARCHAR(16) NULL
);
CREATE UNIQUE INDEX UniqueIndex
ON Test(Code);
INSERT INTO Test VALUES ('sample');
INSERT INTO Test VALUES ('sample ');
SELECT '>' + Code + '<' FROM Test WHERE Code = 'sample ';
GO
produces the following results:
(1 row(s) affected)
Msg 2601, Level 14, State 1, Line 8
Cannot insert duplicate key row in object 'dbo.Test' with unique index 'UniqueIndex'. The duplicate key value is (sample ).
The statement has been terminated.
‐‐‐‐‐‐‐‐‐‐‐‐
>sample<
(1 row(s) affected)
My questions are:
- I assume the index cannot store trailing spaces. Can anyone point me to official documentation that specifies/defines this behavior?
- Is there a setting to change this behavior, that is, make it recognize 'sample' and 'sample ' as two different values (which they are, by the way) so both can be in the index.
- Why on Earth is the SELECT returning a row? SQL Server must be doing something really funny/clever with the spaces in the WHERE clause because if I remove the uniqueness in the index, both INSERTs will run OK and the SELECT will return two rows!
Any help/pointer in the right direction would be appreciated. Thanks.
Trailing blanks explained:
Here's a well known example of all the cases mentioned above:
Here's some more detail about trailing blanks and the
LIKE
clause.Regarding indexes:
(Taken from here.)