Varchar with trailing spaces as a Primary Key in SQL Server 2008
Is it possible to have a varchar col开发者_StackOverflow中文版umn as a primary key with values like 'a ' and 'a', is gives always this error "Violation of PRIMARY KEY constraint" in MS SQL Server 2008. In Oracle dons't give any error. BTW I'm not implementing this way I'm only trying to migrate the data from oracle to sql server.
Regards
The SQL-92 standard dictates that for character string comparison purposes, the strings are padded to be the same length prior to comparison: typically the pad character is a space.
Therefore 'a' and 'a ' compare EQUAL and this violates the PK constraint. http://support.microsoft.com/kb/316626
I could find nothing to indicate this behaviour has changed since then.
You may get away with using varbinary instead of varchar but this may not do what you want either.
You can use a text
or ntext
column, which one depends on the kind of data you are importing and its length - this will preserve spaces. char
will pad spaces, so may not be suitable.
I thought this might have something to do with ANSI_PADDING: but my testing here, indicates that for PKs (possibly UNIQUE INDEXES as well, not tried) this still doesn't help unfortunately.
So:
SET ANSI_PADDING ON
Works for non-PK fields - that is, it preserves the trailing space on the insert, but for some reason not on PKs...
See :
http://support.microsoft.com/kb/154886/EN-US/
use a datatype that doesn't strip trailing spaces.
You might try storing as a varbinary, and then converting to varchar when you select.
You could add another column to your primary key constraint which holds the length of the data in the oracle column. This will allow you to import the data and to reconstruct the oracle data when you need to - with a view that uses the length of the oracle data along with the length in the microsoft table to add back the missing spaces for display in reports etc.
精彩评论