Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are values stored in an NVARCHAR column sometimes padded with trailing spaces?

An app I'm working on is storing Unicode strings in an NVARCHAR(50) column in an SQL Server 2005 database.

Sometimes, the database returns a string padded with spaces up to the max length of the column (50). At other times the padding doesn't happen.

I think that the type of this column was originally specified as NCHAR, but that when we realized the spaces were being added, we changed it to NVARCHAR(50). Could this have anything to do with it?

Either way, can this 'feature' be turned off?

Clarification

I just realized that what I wrote above doesn't make it clear that even newly-inserted strings are getting padded with spaces.

like image 846
dandan78 Avatar asked Apr 21 '11 15:04

dandan78


People also ask

Does NVARCHAR include spaces?

An NVARCHAR value can include tabs, spaces, and nonprintable characters. Nonprintable NVARCHAR characters are entered, displayed, and treated in the same way as nonprintable VARCHAR characters.

What are trailing spaces in SQL?

When the right side of a LIKE predicate expression features a value with a trailing space, SQL Server does not pad the two values to the same length before the comparison occurs.

Does SQL ignore trailing spaces?

Takeaway: According to SQL Server, an identifier with trailing spaces is considered equivalent to the same identifier with those spaces removed.

How is NVARCHAR stored?

The key difference between varchar and nvarchar is the way they are stored, varchar is stored as regular 8-bit data(1 byte per character) and nvarchar stores data at 2 bytes per character. Due to this reason, nvarchar can hold upto 4000 characters and it takes double the space as SQL varchar.


1 Answers

NCHAR pads the field, NVARCHAR doesn't. But if the data is from the old field then the spaces will remain until trimmed.

like image 145
Chris Snowden Avatar answered Sep 18 '22 15:09

Chris Snowden