views:

226

answers:

5

Is it possible to have a varchar column 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

A: 

use a datatype that doesn't strip trailing spaces.

just somebody
+1  A: 

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.

Oded
text and ntext are deprecated, and char will pad with blanks if you don't provide them.
RickNZ
I converted to char but sql server gives the same error.
cacaupt
`text` and `ntext` may be deprecated, but for a one time import to a temporary table I don't see a problem.
Oded
To char, 'a' and 'a ' will both pad to 'a '. To varchar, they both get changed to 'a'
CodeByMoonlight
Oh, and text and ntext are not indexable and therefore cannot be used as primary keys.
CodeByMoonlight
A: 

You might try storing as a varbinary, and then converting to varchar when you select.

RickNZ
A: 

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/

monojohnny
thanks I've see that to, what I don't know is if there is an option form changing the way(with trailing pad or not) sql server compare unique keys...
cacaupt
+1  A: 

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.

Steven